1dda28197Spatrick //===-- ObjectFileMachO.cpp -----------------------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick
9*f6aab3d8Srobert #include "llvm/ADT/ScopeExit.h"
10061da546Spatrick #include "llvm/ADT/StringRef.h"
11061da546Spatrick
12061da546Spatrick #include "Plugins/Process/Utility/RegisterContextDarwin_arm.h"
13061da546Spatrick #include "Plugins/Process/Utility/RegisterContextDarwin_arm64.h"
14061da546Spatrick #include "Plugins/Process/Utility/RegisterContextDarwin_i386.h"
15061da546Spatrick #include "Plugins/Process/Utility/RegisterContextDarwin_x86_64.h"
16061da546Spatrick #include "lldb/Core/Debugger.h"
17061da546Spatrick #include "lldb/Core/FileSpecList.h"
18061da546Spatrick #include "lldb/Core/Module.h"
19061da546Spatrick #include "lldb/Core/ModuleSpec.h"
20061da546Spatrick #include "lldb/Core/PluginManager.h"
21be691f3bSpatrick #include "lldb/Core/Progress.h"
22061da546Spatrick #include "lldb/Core/Section.h"
23061da546Spatrick #include "lldb/Core/StreamFile.h"
24061da546Spatrick #include "lldb/Host/Host.h"
25061da546Spatrick #include "lldb/Symbol/DWARFCallFrameInfo.h"
26be691f3bSpatrick #include "lldb/Symbol/LocateSymbolFile.h"
27061da546Spatrick #include "lldb/Symbol/ObjectFile.h"
28061da546Spatrick #include "lldb/Target/DynamicLoader.h"
29061da546Spatrick #include "lldb/Target/MemoryRegionInfo.h"
30061da546Spatrick #include "lldb/Target/Platform.h"
31061da546Spatrick #include "lldb/Target/Process.h"
32061da546Spatrick #include "lldb/Target/SectionLoadList.h"
33061da546Spatrick #include "lldb/Target/Target.h"
34061da546Spatrick #include "lldb/Target/Thread.h"
35061da546Spatrick #include "lldb/Target/ThreadList.h"
36061da546Spatrick #include "lldb/Utility/ArchSpec.h"
37061da546Spatrick #include "lldb/Utility/DataBuffer.h"
38061da546Spatrick #include "lldb/Utility/FileSpec.h"
39*f6aab3d8Srobert #include "lldb/Utility/LLDBLog.h"
40061da546Spatrick #include "lldb/Utility/Log.h"
41061da546Spatrick #include "lldb/Utility/RangeMap.h"
42061da546Spatrick #include "lldb/Utility/RegisterValue.h"
43061da546Spatrick #include "lldb/Utility/Status.h"
44061da546Spatrick #include "lldb/Utility/StreamString.h"
45061da546Spatrick #include "lldb/Utility/Timer.h"
46061da546Spatrick #include "lldb/Utility/UUID.h"
47061da546Spatrick
48*f6aab3d8Srobert #include "lldb/Host/SafeMachO.h"
49*f6aab3d8Srobert
50be691f3bSpatrick #include "llvm/ADT/DenseSet.h"
51be691f3bSpatrick #include "llvm/Support/FormatVariadic.h"
52061da546Spatrick #include "llvm/Support/MemoryBuffer.h"
53061da546Spatrick
54061da546Spatrick #include "ObjectFileMachO.h"
55061da546Spatrick
56be691f3bSpatrick #if defined(__APPLE__)
57be691f3bSpatrick #include <TargetConditionals.h>
58061da546Spatrick // GetLLDBSharedCacheUUID() needs to call dlsym()
59061da546Spatrick #include <dlfcn.h>
60*f6aab3d8Srobert #include <mach/mach_init.h>
61*f6aab3d8Srobert #include <mach/vm_map.h>
62*f6aab3d8Srobert #include <lldb/Host/SafeMachO.h>
63061da546Spatrick #endif
64061da546Spatrick
65061da546Spatrick #ifndef __APPLE__
66061da546Spatrick #include "Utility/UuidCompatibility.h"
67061da546Spatrick #else
68061da546Spatrick #include <uuid/uuid.h>
69061da546Spatrick #endif
70061da546Spatrick
71be691f3bSpatrick #include <bitset>
72061da546Spatrick #include <memory>
73*f6aab3d8Srobert #include <optional>
74061da546Spatrick
75be691f3bSpatrick // Unfortunately the signpost header pulls in the system MachO header, too.
76*f6aab3d8Srobert #ifdef CPU_TYPE_ARM
77be691f3bSpatrick #undef CPU_TYPE_ARM
78*f6aab3d8Srobert #endif
79*f6aab3d8Srobert #ifdef CPU_TYPE_ARM64
80be691f3bSpatrick #undef CPU_TYPE_ARM64
81*f6aab3d8Srobert #endif
82*f6aab3d8Srobert #ifdef CPU_TYPE_ARM64_32
83be691f3bSpatrick #undef CPU_TYPE_ARM64_32
84*f6aab3d8Srobert #endif
85*f6aab3d8Srobert #ifdef CPU_TYPE_I386
86be691f3bSpatrick #undef CPU_TYPE_I386
87*f6aab3d8Srobert #endif
88*f6aab3d8Srobert #ifdef CPU_TYPE_X86_64
89be691f3bSpatrick #undef CPU_TYPE_X86_64
90*f6aab3d8Srobert #endif
91*f6aab3d8Srobert #ifdef MH_DYLINKER
92be691f3bSpatrick #undef MH_DYLINKER
93*f6aab3d8Srobert #endif
94*f6aab3d8Srobert #ifdef MH_OBJECT
95be691f3bSpatrick #undef MH_OBJECT
96*f6aab3d8Srobert #endif
97*f6aab3d8Srobert #ifdef LC_VERSION_MIN_MACOSX
98be691f3bSpatrick #undef LC_VERSION_MIN_MACOSX
99*f6aab3d8Srobert #endif
100*f6aab3d8Srobert #ifdef LC_VERSION_MIN_IPHONEOS
101be691f3bSpatrick #undef LC_VERSION_MIN_IPHONEOS
102*f6aab3d8Srobert #endif
103*f6aab3d8Srobert #ifdef LC_VERSION_MIN_TVOS
104be691f3bSpatrick #undef LC_VERSION_MIN_TVOS
105*f6aab3d8Srobert #endif
106*f6aab3d8Srobert #ifdef LC_VERSION_MIN_WATCHOS
107be691f3bSpatrick #undef LC_VERSION_MIN_WATCHOS
108*f6aab3d8Srobert #endif
109*f6aab3d8Srobert #ifdef LC_BUILD_VERSION
110*f6aab3d8Srobert #undef LC_BUILD_VERSION
111*f6aab3d8Srobert #endif
112*f6aab3d8Srobert #ifdef PLATFORM_MACOS
113be691f3bSpatrick #undef PLATFORM_MACOS
114*f6aab3d8Srobert #endif
115*f6aab3d8Srobert #ifdef PLATFORM_MACCATALYST
116be691f3bSpatrick #undef PLATFORM_MACCATALYST
117*f6aab3d8Srobert #endif
118*f6aab3d8Srobert #ifdef PLATFORM_IOS
119be691f3bSpatrick #undef PLATFORM_IOS
120*f6aab3d8Srobert #endif
121*f6aab3d8Srobert #ifdef PLATFORM_IOSSIMULATOR
122be691f3bSpatrick #undef PLATFORM_IOSSIMULATOR
123*f6aab3d8Srobert #endif
124*f6aab3d8Srobert #ifdef PLATFORM_TVOS
125be691f3bSpatrick #undef PLATFORM_TVOS
126*f6aab3d8Srobert #endif
127*f6aab3d8Srobert #ifdef PLATFORM_TVOSSIMULATOR
128be691f3bSpatrick #undef PLATFORM_TVOSSIMULATOR
129*f6aab3d8Srobert #endif
130*f6aab3d8Srobert #ifdef PLATFORM_WATCHOS
131be691f3bSpatrick #undef PLATFORM_WATCHOS
132*f6aab3d8Srobert #endif
133*f6aab3d8Srobert #ifdef PLATFORM_WATCHOSSIMULATOR
134be691f3bSpatrick #undef PLATFORM_WATCHOSSIMULATOR
135be691f3bSpatrick #endif
136be691f3bSpatrick
137061da546Spatrick #define THUMB_ADDRESS_BIT_MASK 0xfffffffffffffffeull
138061da546Spatrick using namespace lldb;
139061da546Spatrick using namespace lldb_private;
140061da546Spatrick using namespace llvm::MachO;
141061da546Spatrick
142dda28197Spatrick LLDB_PLUGIN_DEFINE(ObjectFileMachO)
143dda28197Spatrick
144061da546Spatrick // Some structure definitions needed for parsing the dyld shared cache files
145061da546Spatrick // found on iOS devices.
146061da546Spatrick
147061da546Spatrick struct lldb_copy_dyld_cache_header_v1 {
148061da546Spatrick char magic[16]; // e.g. "dyld_v0 i386", "dyld_v1 armv7", etc.
149061da546Spatrick uint32_t mappingOffset; // file offset to first dyld_cache_mapping_info
150061da546Spatrick uint32_t mappingCount; // number of dyld_cache_mapping_info entries
151061da546Spatrick uint32_t imagesOffset;
152061da546Spatrick uint32_t imagesCount;
153061da546Spatrick uint64_t dyldBaseAddress;
154061da546Spatrick uint64_t codeSignatureOffset;
155061da546Spatrick uint64_t codeSignatureSize;
156061da546Spatrick uint64_t slideInfoOffset;
157061da546Spatrick uint64_t slideInfoSize;
158061da546Spatrick uint64_t localSymbolsOffset;
159061da546Spatrick uint64_t localSymbolsSize;
160061da546Spatrick uint8_t uuid[16]; // v1 and above, also recorded in dyld_all_image_infos v13
161061da546Spatrick // and later
162061da546Spatrick };
163061da546Spatrick
PrintRegisterValue(RegisterContext * reg_ctx,const char * name,const char * alt_name,size_t reg_byte_size,Stream & data)164061da546Spatrick static void PrintRegisterValue(RegisterContext *reg_ctx, const char *name,
165061da546Spatrick const char *alt_name, size_t reg_byte_size,
166061da546Spatrick Stream &data) {
167061da546Spatrick const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
168061da546Spatrick if (reg_info == nullptr)
169061da546Spatrick reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
170061da546Spatrick if (reg_info) {
171061da546Spatrick lldb_private::RegisterValue reg_value;
172061da546Spatrick if (reg_ctx->ReadRegister(reg_info, reg_value)) {
173061da546Spatrick if (reg_info->byte_size >= reg_byte_size)
174061da546Spatrick data.Write(reg_value.GetBytes(), reg_byte_size);
175061da546Spatrick else {
176061da546Spatrick data.Write(reg_value.GetBytes(), reg_info->byte_size);
177061da546Spatrick for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n; ++i)
178061da546Spatrick data.PutChar(0);
179061da546Spatrick }
180061da546Spatrick return;
181061da546Spatrick }
182061da546Spatrick }
183061da546Spatrick // Just write zeros if all else fails
184061da546Spatrick for (size_t i = 0; i < reg_byte_size; ++i)
185061da546Spatrick data.PutChar(0);
186061da546Spatrick }
187061da546Spatrick
188061da546Spatrick class RegisterContextDarwin_x86_64_Mach : public RegisterContextDarwin_x86_64 {
189061da546Spatrick public:
RegisterContextDarwin_x86_64_Mach(lldb_private::Thread & thread,const DataExtractor & data)190061da546Spatrick RegisterContextDarwin_x86_64_Mach(lldb_private::Thread &thread,
191061da546Spatrick const DataExtractor &data)
192061da546Spatrick : RegisterContextDarwin_x86_64(thread, 0) {
193061da546Spatrick SetRegisterDataFrom_LC_THREAD(data);
194061da546Spatrick }
195061da546Spatrick
InvalidateAllRegisters()196061da546Spatrick void InvalidateAllRegisters() override {
197061da546Spatrick // Do nothing... registers are always valid...
198061da546Spatrick }
199061da546Spatrick
SetRegisterDataFrom_LC_THREAD(const DataExtractor & data)200061da546Spatrick void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
201061da546Spatrick lldb::offset_t offset = 0;
202061da546Spatrick SetError(GPRRegSet, Read, -1);
203061da546Spatrick SetError(FPURegSet, Read, -1);
204061da546Spatrick SetError(EXCRegSet, Read, -1);
205061da546Spatrick bool done = false;
206061da546Spatrick
207061da546Spatrick while (!done) {
208061da546Spatrick int flavor = data.GetU32(&offset);
209061da546Spatrick if (flavor == 0)
210061da546Spatrick done = true;
211061da546Spatrick else {
212061da546Spatrick uint32_t i;
213061da546Spatrick uint32_t count = data.GetU32(&offset);
214061da546Spatrick switch (flavor) {
215061da546Spatrick case GPRRegSet:
216061da546Spatrick for (i = 0; i < count; ++i)
217061da546Spatrick (&gpr.rax)[i] = data.GetU64(&offset);
218061da546Spatrick SetError(GPRRegSet, Read, 0);
219061da546Spatrick done = true;
220061da546Spatrick
221061da546Spatrick break;
222061da546Spatrick case FPURegSet:
223061da546Spatrick // TODO: fill in FPU regs....
224061da546Spatrick // SetError (FPURegSet, Read, -1);
225061da546Spatrick done = true;
226061da546Spatrick
227061da546Spatrick break;
228061da546Spatrick case EXCRegSet:
229061da546Spatrick exc.trapno = data.GetU32(&offset);
230061da546Spatrick exc.err = data.GetU32(&offset);
231061da546Spatrick exc.faultvaddr = data.GetU64(&offset);
232061da546Spatrick SetError(EXCRegSet, Read, 0);
233061da546Spatrick done = true;
234061da546Spatrick break;
235061da546Spatrick case 7:
236061da546Spatrick case 8:
237061da546Spatrick case 9:
238061da546Spatrick // fancy flavors that encapsulate of the above flavors...
239061da546Spatrick break;
240061da546Spatrick
241061da546Spatrick default:
242061da546Spatrick done = true;
243061da546Spatrick break;
244061da546Spatrick }
245061da546Spatrick }
246061da546Spatrick }
247061da546Spatrick }
248061da546Spatrick
Create_LC_THREAD(Thread * thread,Stream & data)249061da546Spatrick static bool Create_LC_THREAD(Thread *thread, Stream &data) {
250061da546Spatrick RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
251061da546Spatrick if (reg_ctx_sp) {
252061da546Spatrick RegisterContext *reg_ctx = reg_ctx_sp.get();
253061da546Spatrick
254061da546Spatrick data.PutHex32(GPRRegSet); // Flavor
255061da546Spatrick data.PutHex32(GPRWordCount);
256061da546Spatrick PrintRegisterValue(reg_ctx, "rax", nullptr, 8, data);
257061da546Spatrick PrintRegisterValue(reg_ctx, "rbx", nullptr, 8, data);
258061da546Spatrick PrintRegisterValue(reg_ctx, "rcx", nullptr, 8, data);
259061da546Spatrick PrintRegisterValue(reg_ctx, "rdx", nullptr, 8, data);
260061da546Spatrick PrintRegisterValue(reg_ctx, "rdi", nullptr, 8, data);
261061da546Spatrick PrintRegisterValue(reg_ctx, "rsi", nullptr, 8, data);
262061da546Spatrick PrintRegisterValue(reg_ctx, "rbp", nullptr, 8, data);
263061da546Spatrick PrintRegisterValue(reg_ctx, "rsp", nullptr, 8, data);
264061da546Spatrick PrintRegisterValue(reg_ctx, "r8", nullptr, 8, data);
265061da546Spatrick PrintRegisterValue(reg_ctx, "r9", nullptr, 8, data);
266061da546Spatrick PrintRegisterValue(reg_ctx, "r10", nullptr, 8, data);
267061da546Spatrick PrintRegisterValue(reg_ctx, "r11", nullptr, 8, data);
268061da546Spatrick PrintRegisterValue(reg_ctx, "r12", nullptr, 8, data);
269061da546Spatrick PrintRegisterValue(reg_ctx, "r13", nullptr, 8, data);
270061da546Spatrick PrintRegisterValue(reg_ctx, "r14", nullptr, 8, data);
271061da546Spatrick PrintRegisterValue(reg_ctx, "r15", nullptr, 8, data);
272061da546Spatrick PrintRegisterValue(reg_ctx, "rip", nullptr, 8, data);
273061da546Spatrick PrintRegisterValue(reg_ctx, "rflags", nullptr, 8, data);
274061da546Spatrick PrintRegisterValue(reg_ctx, "cs", nullptr, 8, data);
275061da546Spatrick PrintRegisterValue(reg_ctx, "fs", nullptr, 8, data);
276061da546Spatrick PrintRegisterValue(reg_ctx, "gs", nullptr, 8, data);
277061da546Spatrick
278061da546Spatrick // // Write out the FPU registers
279061da546Spatrick // const size_t fpu_byte_size = sizeof(FPU);
280061da546Spatrick // size_t bytes_written = 0;
281061da546Spatrick // data.PutHex32 (FPURegSet);
282061da546Spatrick // data.PutHex32 (fpu_byte_size/sizeof(uint64_t));
283061da546Spatrick // bytes_written += data.PutHex32(0); // uint32_t pad[0]
284061da546Spatrick // bytes_written += data.PutHex32(0); // uint32_t pad[1]
285061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "fcw", "fctrl", 2,
286061da546Spatrick // data); // uint16_t fcw; // "fctrl"
287061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "fsw" , "fstat", 2,
288061da546Spatrick // data); // uint16_t fsw; // "fstat"
289061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "ftw" , "ftag", 1,
290061da546Spatrick // data); // uint8_t ftw; // "ftag"
291061da546Spatrick // bytes_written += data.PutHex8 (0); // uint8_t pad1;
292061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "fop" , NULL, 2,
293061da546Spatrick // data); // uint16_t fop; // "fop"
294061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "fioff", "ip", 4,
295061da546Spatrick // data); // uint32_t ip; // "fioff"
296061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "fiseg", NULL, 2,
297061da546Spatrick // data); // uint16_t cs; // "fiseg"
298061da546Spatrick // bytes_written += data.PutHex16 (0); // uint16_t pad2;
299061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "dp", "fooff" , 4,
300061da546Spatrick // data); // uint32_t dp; // "fooff"
301061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "foseg", NULL, 2,
302061da546Spatrick // data); // uint16_t ds; // "foseg"
303061da546Spatrick // bytes_written += data.PutHex16 (0); // uint16_t pad3;
304061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "mxcsr", NULL, 4,
305061da546Spatrick // data); // uint32_t mxcsr;
306061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "mxcsrmask", NULL,
307061da546Spatrick // 4, data);// uint32_t mxcsrmask;
308061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "stmm0", NULL,
309061da546Spatrick // sizeof(MMSReg), data);
310061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "stmm1", NULL,
311061da546Spatrick // sizeof(MMSReg), data);
312061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "stmm2", NULL,
313061da546Spatrick // sizeof(MMSReg), data);
314061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "stmm3", NULL,
315061da546Spatrick // sizeof(MMSReg), data);
316061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "stmm4", NULL,
317061da546Spatrick // sizeof(MMSReg), data);
318061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "stmm5", NULL,
319061da546Spatrick // sizeof(MMSReg), data);
320061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "stmm6", NULL,
321061da546Spatrick // sizeof(MMSReg), data);
322061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "stmm7", NULL,
323061da546Spatrick // sizeof(MMSReg), data);
324061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm0" , NULL,
325061da546Spatrick // sizeof(XMMReg), data);
326061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm1" , NULL,
327061da546Spatrick // sizeof(XMMReg), data);
328061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm2" , NULL,
329061da546Spatrick // sizeof(XMMReg), data);
330061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm3" , NULL,
331061da546Spatrick // sizeof(XMMReg), data);
332061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm4" , NULL,
333061da546Spatrick // sizeof(XMMReg), data);
334061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm5" , NULL,
335061da546Spatrick // sizeof(XMMReg), data);
336061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm6" , NULL,
337061da546Spatrick // sizeof(XMMReg), data);
338061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm7" , NULL,
339061da546Spatrick // sizeof(XMMReg), data);
340061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm8" , NULL,
341061da546Spatrick // sizeof(XMMReg), data);
342061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm9" , NULL,
343061da546Spatrick // sizeof(XMMReg), data);
344061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm10", NULL,
345061da546Spatrick // sizeof(XMMReg), data);
346061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm11", NULL,
347061da546Spatrick // sizeof(XMMReg), data);
348061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm12", NULL,
349061da546Spatrick // sizeof(XMMReg), data);
350061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm13", NULL,
351061da546Spatrick // sizeof(XMMReg), data);
352061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm14", NULL,
353061da546Spatrick // sizeof(XMMReg), data);
354061da546Spatrick // bytes_written += WriteRegister (reg_ctx, "xmm15", NULL,
355061da546Spatrick // sizeof(XMMReg), data);
356061da546Spatrick //
357061da546Spatrick // // Fill rest with zeros
358061da546Spatrick // for (size_t i=0, n = fpu_byte_size - bytes_written; i<n; ++
359061da546Spatrick // i)
360061da546Spatrick // data.PutChar(0);
361061da546Spatrick
362061da546Spatrick // Write out the EXC registers
363061da546Spatrick data.PutHex32(EXCRegSet);
364061da546Spatrick data.PutHex32(EXCWordCount);
365061da546Spatrick PrintRegisterValue(reg_ctx, "trapno", nullptr, 4, data);
366061da546Spatrick PrintRegisterValue(reg_ctx, "err", nullptr, 4, data);
367061da546Spatrick PrintRegisterValue(reg_ctx, "faultvaddr", nullptr, 8, data);
368061da546Spatrick return true;
369061da546Spatrick }
370061da546Spatrick return false;
371061da546Spatrick }
372061da546Spatrick
373061da546Spatrick protected:
DoReadGPR(lldb::tid_t tid,int flavor,GPR & gpr)374061da546Spatrick int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
375061da546Spatrick
DoReadFPU(lldb::tid_t tid,int flavor,FPU & fpu)376061da546Spatrick int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
377061da546Spatrick
DoReadEXC(lldb::tid_t tid,int flavor,EXC & exc)378061da546Spatrick int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
379061da546Spatrick
DoWriteGPR(lldb::tid_t tid,int flavor,const GPR & gpr)380061da546Spatrick int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
381061da546Spatrick return 0;
382061da546Spatrick }
383061da546Spatrick
DoWriteFPU(lldb::tid_t tid,int flavor,const FPU & fpu)384061da546Spatrick int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
385061da546Spatrick return 0;
386061da546Spatrick }
387061da546Spatrick
DoWriteEXC(lldb::tid_t tid,int flavor,const EXC & exc)388061da546Spatrick int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
389061da546Spatrick return 0;
390061da546Spatrick }
391061da546Spatrick };
392061da546Spatrick
393061da546Spatrick class RegisterContextDarwin_i386_Mach : public RegisterContextDarwin_i386 {
394061da546Spatrick public:
RegisterContextDarwin_i386_Mach(lldb_private::Thread & thread,const DataExtractor & data)395061da546Spatrick RegisterContextDarwin_i386_Mach(lldb_private::Thread &thread,
396061da546Spatrick const DataExtractor &data)
397061da546Spatrick : RegisterContextDarwin_i386(thread, 0) {
398061da546Spatrick SetRegisterDataFrom_LC_THREAD(data);
399061da546Spatrick }
400061da546Spatrick
InvalidateAllRegisters()401061da546Spatrick void InvalidateAllRegisters() override {
402061da546Spatrick // Do nothing... registers are always valid...
403061da546Spatrick }
404061da546Spatrick
SetRegisterDataFrom_LC_THREAD(const DataExtractor & data)405061da546Spatrick void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
406061da546Spatrick lldb::offset_t offset = 0;
407061da546Spatrick SetError(GPRRegSet, Read, -1);
408061da546Spatrick SetError(FPURegSet, Read, -1);
409061da546Spatrick SetError(EXCRegSet, Read, -1);
410061da546Spatrick bool done = false;
411061da546Spatrick
412061da546Spatrick while (!done) {
413061da546Spatrick int flavor = data.GetU32(&offset);
414061da546Spatrick if (flavor == 0)
415061da546Spatrick done = true;
416061da546Spatrick else {
417061da546Spatrick uint32_t i;
418061da546Spatrick uint32_t count = data.GetU32(&offset);
419061da546Spatrick switch (flavor) {
420061da546Spatrick case GPRRegSet:
421061da546Spatrick for (i = 0; i < count; ++i)
422061da546Spatrick (&gpr.eax)[i] = data.GetU32(&offset);
423061da546Spatrick SetError(GPRRegSet, Read, 0);
424061da546Spatrick done = true;
425061da546Spatrick
426061da546Spatrick break;
427061da546Spatrick case FPURegSet:
428061da546Spatrick // TODO: fill in FPU regs....
429061da546Spatrick // SetError (FPURegSet, Read, -1);
430061da546Spatrick done = true;
431061da546Spatrick
432061da546Spatrick break;
433061da546Spatrick case EXCRegSet:
434061da546Spatrick exc.trapno = data.GetU32(&offset);
435061da546Spatrick exc.err = data.GetU32(&offset);
436061da546Spatrick exc.faultvaddr = data.GetU32(&offset);
437061da546Spatrick SetError(EXCRegSet, Read, 0);
438061da546Spatrick done = true;
439061da546Spatrick break;
440061da546Spatrick case 7:
441061da546Spatrick case 8:
442061da546Spatrick case 9:
443061da546Spatrick // fancy flavors that encapsulate of the above flavors...
444061da546Spatrick break;
445061da546Spatrick
446061da546Spatrick default:
447061da546Spatrick done = true;
448061da546Spatrick break;
449061da546Spatrick }
450061da546Spatrick }
451061da546Spatrick }
452061da546Spatrick }
453061da546Spatrick
Create_LC_THREAD(Thread * thread,Stream & data)454061da546Spatrick static bool Create_LC_THREAD(Thread *thread, Stream &data) {
455061da546Spatrick RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
456061da546Spatrick if (reg_ctx_sp) {
457061da546Spatrick RegisterContext *reg_ctx = reg_ctx_sp.get();
458061da546Spatrick
459061da546Spatrick data.PutHex32(GPRRegSet); // Flavor
460061da546Spatrick data.PutHex32(GPRWordCount);
461061da546Spatrick PrintRegisterValue(reg_ctx, "eax", nullptr, 4, data);
462061da546Spatrick PrintRegisterValue(reg_ctx, "ebx", nullptr, 4, data);
463061da546Spatrick PrintRegisterValue(reg_ctx, "ecx", nullptr, 4, data);
464061da546Spatrick PrintRegisterValue(reg_ctx, "edx", nullptr, 4, data);
465061da546Spatrick PrintRegisterValue(reg_ctx, "edi", nullptr, 4, data);
466061da546Spatrick PrintRegisterValue(reg_ctx, "esi", nullptr, 4, data);
467061da546Spatrick PrintRegisterValue(reg_ctx, "ebp", nullptr, 4, data);
468061da546Spatrick PrintRegisterValue(reg_ctx, "esp", nullptr, 4, data);
469061da546Spatrick PrintRegisterValue(reg_ctx, "ss", nullptr, 4, data);
470061da546Spatrick PrintRegisterValue(reg_ctx, "eflags", nullptr, 4, data);
471061da546Spatrick PrintRegisterValue(reg_ctx, "eip", nullptr, 4, data);
472061da546Spatrick PrintRegisterValue(reg_ctx, "cs", nullptr, 4, data);
473061da546Spatrick PrintRegisterValue(reg_ctx, "ds", nullptr, 4, data);
474061da546Spatrick PrintRegisterValue(reg_ctx, "es", nullptr, 4, data);
475061da546Spatrick PrintRegisterValue(reg_ctx, "fs", nullptr, 4, data);
476061da546Spatrick PrintRegisterValue(reg_ctx, "gs", nullptr, 4, data);
477061da546Spatrick
478061da546Spatrick // Write out the EXC registers
479061da546Spatrick data.PutHex32(EXCRegSet);
480061da546Spatrick data.PutHex32(EXCWordCount);
481061da546Spatrick PrintRegisterValue(reg_ctx, "trapno", nullptr, 4, data);
482061da546Spatrick PrintRegisterValue(reg_ctx, "err", nullptr, 4, data);
483061da546Spatrick PrintRegisterValue(reg_ctx, "faultvaddr", nullptr, 4, data);
484061da546Spatrick return true;
485061da546Spatrick }
486061da546Spatrick return false;
487061da546Spatrick }
488061da546Spatrick
489061da546Spatrick protected:
DoReadGPR(lldb::tid_t tid,int flavor,GPR & gpr)490061da546Spatrick int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
491061da546Spatrick
DoReadFPU(lldb::tid_t tid,int flavor,FPU & fpu)492061da546Spatrick int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
493061da546Spatrick
DoReadEXC(lldb::tid_t tid,int flavor,EXC & exc)494061da546Spatrick int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
495061da546Spatrick
DoWriteGPR(lldb::tid_t tid,int flavor,const GPR & gpr)496061da546Spatrick int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
497061da546Spatrick return 0;
498061da546Spatrick }
499061da546Spatrick
DoWriteFPU(lldb::tid_t tid,int flavor,const FPU & fpu)500061da546Spatrick int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
501061da546Spatrick return 0;
502061da546Spatrick }
503061da546Spatrick
DoWriteEXC(lldb::tid_t tid,int flavor,const EXC & exc)504061da546Spatrick int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
505061da546Spatrick return 0;
506061da546Spatrick }
507061da546Spatrick };
508061da546Spatrick
509061da546Spatrick class RegisterContextDarwin_arm_Mach : public RegisterContextDarwin_arm {
510061da546Spatrick public:
RegisterContextDarwin_arm_Mach(lldb_private::Thread & thread,const DataExtractor & data)511061da546Spatrick RegisterContextDarwin_arm_Mach(lldb_private::Thread &thread,
512061da546Spatrick const DataExtractor &data)
513061da546Spatrick : RegisterContextDarwin_arm(thread, 0) {
514061da546Spatrick SetRegisterDataFrom_LC_THREAD(data);
515061da546Spatrick }
516061da546Spatrick
InvalidateAllRegisters()517061da546Spatrick void InvalidateAllRegisters() override {
518061da546Spatrick // Do nothing... registers are always valid...
519061da546Spatrick }
520061da546Spatrick
SetRegisterDataFrom_LC_THREAD(const DataExtractor & data)521061da546Spatrick void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
522061da546Spatrick lldb::offset_t offset = 0;
523061da546Spatrick SetError(GPRRegSet, Read, -1);
524061da546Spatrick SetError(FPURegSet, Read, -1);
525061da546Spatrick SetError(EXCRegSet, Read, -1);
526061da546Spatrick bool done = false;
527061da546Spatrick
528061da546Spatrick while (!done) {
529061da546Spatrick int flavor = data.GetU32(&offset);
530061da546Spatrick uint32_t count = data.GetU32(&offset);
531061da546Spatrick lldb::offset_t next_thread_state = offset + (count * 4);
532061da546Spatrick switch (flavor) {
533061da546Spatrick case GPRAltRegSet:
534061da546Spatrick case GPRRegSet:
535061da546Spatrick // On ARM, the CPSR register is also included in the count but it is
536061da546Spatrick // not included in gpr.r so loop until (count-1).
537*f6aab3d8Srobert
538*f6aab3d8Srobert // Prevent static analysis warnings by explicitly contstraining 'count'
539*f6aab3d8Srobert // to acceptable range. Handle possible underflow of count-1
540*f6aab3d8Srobert if (count > 0 && count <= sizeof(gpr.r) / sizeof(gpr.r[0])) {
541061da546Spatrick for (uint32_t i = 0; i < (count - 1); ++i) {
542061da546Spatrick gpr.r[i] = data.GetU32(&offset);
543061da546Spatrick }
544*f6aab3d8Srobert }
545061da546Spatrick // Save cpsr explicitly.
546061da546Spatrick gpr.cpsr = data.GetU32(&offset);
547061da546Spatrick
548061da546Spatrick SetError(GPRRegSet, Read, 0);
549061da546Spatrick offset = next_thread_state;
550061da546Spatrick break;
551061da546Spatrick
552061da546Spatrick case FPURegSet: {
553*f6aab3d8Srobert uint8_t *fpu_reg_buf = (uint8_t *)&fpu.floats;
554061da546Spatrick const int fpu_reg_buf_size = sizeof(fpu.floats);
555061da546Spatrick if (data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
556061da546Spatrick fpu_reg_buf) == fpu_reg_buf_size) {
557061da546Spatrick offset += fpu_reg_buf_size;
558061da546Spatrick fpu.fpscr = data.GetU32(&offset);
559061da546Spatrick SetError(FPURegSet, Read, 0);
560061da546Spatrick } else {
561061da546Spatrick done = true;
562061da546Spatrick }
563061da546Spatrick }
564061da546Spatrick offset = next_thread_state;
565061da546Spatrick break;
566061da546Spatrick
567061da546Spatrick case EXCRegSet:
568061da546Spatrick if (count == 3) {
569061da546Spatrick exc.exception = data.GetU32(&offset);
570061da546Spatrick exc.fsr = data.GetU32(&offset);
571061da546Spatrick exc.far = data.GetU32(&offset);
572061da546Spatrick SetError(EXCRegSet, Read, 0);
573061da546Spatrick }
574061da546Spatrick done = true;
575061da546Spatrick offset = next_thread_state;
576061da546Spatrick break;
577061da546Spatrick
578061da546Spatrick // Unknown register set flavor, stop trying to parse.
579061da546Spatrick default:
580061da546Spatrick done = true;
581061da546Spatrick }
582061da546Spatrick }
583061da546Spatrick }
584061da546Spatrick
Create_LC_THREAD(Thread * thread,Stream & data)585061da546Spatrick static bool Create_LC_THREAD(Thread *thread, Stream &data) {
586061da546Spatrick RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
587061da546Spatrick if (reg_ctx_sp) {
588061da546Spatrick RegisterContext *reg_ctx = reg_ctx_sp.get();
589061da546Spatrick
590061da546Spatrick data.PutHex32(GPRRegSet); // Flavor
591061da546Spatrick data.PutHex32(GPRWordCount);
592061da546Spatrick PrintRegisterValue(reg_ctx, "r0", nullptr, 4, data);
593061da546Spatrick PrintRegisterValue(reg_ctx, "r1", nullptr, 4, data);
594061da546Spatrick PrintRegisterValue(reg_ctx, "r2", nullptr, 4, data);
595061da546Spatrick PrintRegisterValue(reg_ctx, "r3", nullptr, 4, data);
596061da546Spatrick PrintRegisterValue(reg_ctx, "r4", nullptr, 4, data);
597061da546Spatrick PrintRegisterValue(reg_ctx, "r5", nullptr, 4, data);
598061da546Spatrick PrintRegisterValue(reg_ctx, "r6", nullptr, 4, data);
599061da546Spatrick PrintRegisterValue(reg_ctx, "r7", nullptr, 4, data);
600061da546Spatrick PrintRegisterValue(reg_ctx, "r8", nullptr, 4, data);
601061da546Spatrick PrintRegisterValue(reg_ctx, "r9", nullptr, 4, data);
602061da546Spatrick PrintRegisterValue(reg_ctx, "r10", nullptr, 4, data);
603061da546Spatrick PrintRegisterValue(reg_ctx, "r11", nullptr, 4, data);
604061da546Spatrick PrintRegisterValue(reg_ctx, "r12", nullptr, 4, data);
605061da546Spatrick PrintRegisterValue(reg_ctx, "sp", nullptr, 4, data);
606061da546Spatrick PrintRegisterValue(reg_ctx, "lr", nullptr, 4, data);
607061da546Spatrick PrintRegisterValue(reg_ctx, "pc", nullptr, 4, data);
608061da546Spatrick PrintRegisterValue(reg_ctx, "cpsr", nullptr, 4, data);
609061da546Spatrick
610061da546Spatrick // Write out the EXC registers
611061da546Spatrick // data.PutHex32 (EXCRegSet);
612061da546Spatrick // data.PutHex32 (EXCWordCount);
613061da546Spatrick // WriteRegister (reg_ctx, "exception", NULL, 4, data);
614061da546Spatrick // WriteRegister (reg_ctx, "fsr", NULL, 4, data);
615061da546Spatrick // WriteRegister (reg_ctx, "far", NULL, 4, data);
616061da546Spatrick return true;
617061da546Spatrick }
618061da546Spatrick return false;
619061da546Spatrick }
620061da546Spatrick
621061da546Spatrick protected:
DoReadGPR(lldb::tid_t tid,int flavor,GPR & gpr)622061da546Spatrick int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
623061da546Spatrick
DoReadFPU(lldb::tid_t tid,int flavor,FPU & fpu)624061da546Spatrick int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
625061da546Spatrick
DoReadEXC(lldb::tid_t tid,int flavor,EXC & exc)626061da546Spatrick int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
627061da546Spatrick
DoReadDBG(lldb::tid_t tid,int flavor,DBG & dbg)628061da546Spatrick int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
629061da546Spatrick
DoWriteGPR(lldb::tid_t tid,int flavor,const GPR & gpr)630061da546Spatrick int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
631061da546Spatrick return 0;
632061da546Spatrick }
633061da546Spatrick
DoWriteFPU(lldb::tid_t tid,int flavor,const FPU & fpu)634061da546Spatrick int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
635061da546Spatrick return 0;
636061da546Spatrick }
637061da546Spatrick
DoWriteEXC(lldb::tid_t tid,int flavor,const EXC & exc)638061da546Spatrick int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
639061da546Spatrick return 0;
640061da546Spatrick }
641061da546Spatrick
DoWriteDBG(lldb::tid_t tid,int flavor,const DBG & dbg)642061da546Spatrick int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
643061da546Spatrick return -1;
644061da546Spatrick }
645061da546Spatrick };
646061da546Spatrick
647061da546Spatrick class RegisterContextDarwin_arm64_Mach : public RegisterContextDarwin_arm64 {
648061da546Spatrick public:
RegisterContextDarwin_arm64_Mach(lldb_private::Thread & thread,const DataExtractor & data)649061da546Spatrick RegisterContextDarwin_arm64_Mach(lldb_private::Thread &thread,
650061da546Spatrick const DataExtractor &data)
651061da546Spatrick : RegisterContextDarwin_arm64(thread, 0) {
652061da546Spatrick SetRegisterDataFrom_LC_THREAD(data);
653061da546Spatrick }
654061da546Spatrick
InvalidateAllRegisters()655061da546Spatrick void InvalidateAllRegisters() override {
656061da546Spatrick // Do nothing... registers are always valid...
657061da546Spatrick }
658061da546Spatrick
SetRegisterDataFrom_LC_THREAD(const DataExtractor & data)659061da546Spatrick void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
660061da546Spatrick lldb::offset_t offset = 0;
661061da546Spatrick SetError(GPRRegSet, Read, -1);
662061da546Spatrick SetError(FPURegSet, Read, -1);
663061da546Spatrick SetError(EXCRegSet, Read, -1);
664061da546Spatrick bool done = false;
665061da546Spatrick while (!done) {
666061da546Spatrick int flavor = data.GetU32(&offset);
667061da546Spatrick uint32_t count = data.GetU32(&offset);
668061da546Spatrick lldb::offset_t next_thread_state = offset + (count * 4);
669061da546Spatrick switch (flavor) {
670061da546Spatrick case GPRRegSet:
671061da546Spatrick // x0-x29 + fp + lr + sp + pc (== 33 64-bit registers) plus cpsr (1
672061da546Spatrick // 32-bit register)
673061da546Spatrick if (count >= (33 * 2) + 1) {
674061da546Spatrick for (uint32_t i = 0; i < 29; ++i)
675061da546Spatrick gpr.x[i] = data.GetU64(&offset);
676061da546Spatrick gpr.fp = data.GetU64(&offset);
677061da546Spatrick gpr.lr = data.GetU64(&offset);
678061da546Spatrick gpr.sp = data.GetU64(&offset);
679061da546Spatrick gpr.pc = data.GetU64(&offset);
680061da546Spatrick gpr.cpsr = data.GetU32(&offset);
681061da546Spatrick SetError(GPRRegSet, Read, 0);
682061da546Spatrick }
683061da546Spatrick offset = next_thread_state;
684061da546Spatrick break;
685061da546Spatrick case FPURegSet: {
686061da546Spatrick uint8_t *fpu_reg_buf = (uint8_t *)&fpu.v[0];
687061da546Spatrick const int fpu_reg_buf_size = sizeof(fpu);
688061da546Spatrick if (fpu_reg_buf_size == count * sizeof(uint32_t) &&
689061da546Spatrick data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
690061da546Spatrick fpu_reg_buf) == fpu_reg_buf_size) {
691061da546Spatrick SetError(FPURegSet, Read, 0);
692061da546Spatrick } else {
693061da546Spatrick done = true;
694061da546Spatrick }
695061da546Spatrick }
696061da546Spatrick offset = next_thread_state;
697061da546Spatrick break;
698061da546Spatrick case EXCRegSet:
699061da546Spatrick if (count == 4) {
700061da546Spatrick exc.far = data.GetU64(&offset);
701061da546Spatrick exc.esr = data.GetU32(&offset);
702061da546Spatrick exc.exception = data.GetU32(&offset);
703061da546Spatrick SetError(EXCRegSet, Read, 0);
704061da546Spatrick }
705061da546Spatrick offset = next_thread_state;
706061da546Spatrick break;
707061da546Spatrick default:
708061da546Spatrick done = true;
709061da546Spatrick break;
710061da546Spatrick }
711061da546Spatrick }
712061da546Spatrick }
713061da546Spatrick
Create_LC_THREAD(Thread * thread,Stream & data)714061da546Spatrick static bool Create_LC_THREAD(Thread *thread, Stream &data) {
715061da546Spatrick RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
716061da546Spatrick if (reg_ctx_sp) {
717061da546Spatrick RegisterContext *reg_ctx = reg_ctx_sp.get();
718061da546Spatrick
719061da546Spatrick data.PutHex32(GPRRegSet); // Flavor
720061da546Spatrick data.PutHex32(GPRWordCount);
721061da546Spatrick PrintRegisterValue(reg_ctx, "x0", nullptr, 8, data);
722061da546Spatrick PrintRegisterValue(reg_ctx, "x1", nullptr, 8, data);
723061da546Spatrick PrintRegisterValue(reg_ctx, "x2", nullptr, 8, data);
724061da546Spatrick PrintRegisterValue(reg_ctx, "x3", nullptr, 8, data);
725061da546Spatrick PrintRegisterValue(reg_ctx, "x4", nullptr, 8, data);
726061da546Spatrick PrintRegisterValue(reg_ctx, "x5", nullptr, 8, data);
727061da546Spatrick PrintRegisterValue(reg_ctx, "x6", nullptr, 8, data);
728061da546Spatrick PrintRegisterValue(reg_ctx, "x7", nullptr, 8, data);
729061da546Spatrick PrintRegisterValue(reg_ctx, "x8", nullptr, 8, data);
730061da546Spatrick PrintRegisterValue(reg_ctx, "x9", nullptr, 8, data);
731061da546Spatrick PrintRegisterValue(reg_ctx, "x10", nullptr, 8, data);
732061da546Spatrick PrintRegisterValue(reg_ctx, "x11", nullptr, 8, data);
733061da546Spatrick PrintRegisterValue(reg_ctx, "x12", nullptr, 8, data);
734061da546Spatrick PrintRegisterValue(reg_ctx, "x13", nullptr, 8, data);
735061da546Spatrick PrintRegisterValue(reg_ctx, "x14", nullptr, 8, data);
736061da546Spatrick PrintRegisterValue(reg_ctx, "x15", nullptr, 8, data);
737061da546Spatrick PrintRegisterValue(reg_ctx, "x16", nullptr, 8, data);
738061da546Spatrick PrintRegisterValue(reg_ctx, "x17", nullptr, 8, data);
739061da546Spatrick PrintRegisterValue(reg_ctx, "x18", nullptr, 8, data);
740061da546Spatrick PrintRegisterValue(reg_ctx, "x19", nullptr, 8, data);
741061da546Spatrick PrintRegisterValue(reg_ctx, "x20", nullptr, 8, data);
742061da546Spatrick PrintRegisterValue(reg_ctx, "x21", nullptr, 8, data);
743061da546Spatrick PrintRegisterValue(reg_ctx, "x22", nullptr, 8, data);
744061da546Spatrick PrintRegisterValue(reg_ctx, "x23", nullptr, 8, data);
745061da546Spatrick PrintRegisterValue(reg_ctx, "x24", nullptr, 8, data);
746061da546Spatrick PrintRegisterValue(reg_ctx, "x25", nullptr, 8, data);
747061da546Spatrick PrintRegisterValue(reg_ctx, "x26", nullptr, 8, data);
748061da546Spatrick PrintRegisterValue(reg_ctx, "x27", nullptr, 8, data);
749061da546Spatrick PrintRegisterValue(reg_ctx, "x28", nullptr, 8, data);
750061da546Spatrick PrintRegisterValue(reg_ctx, "fp", nullptr, 8, data);
751061da546Spatrick PrintRegisterValue(reg_ctx, "lr", nullptr, 8, data);
752061da546Spatrick PrintRegisterValue(reg_ctx, "sp", nullptr, 8, data);
753061da546Spatrick PrintRegisterValue(reg_ctx, "pc", nullptr, 8, data);
754061da546Spatrick PrintRegisterValue(reg_ctx, "cpsr", nullptr, 4, data);
755*f6aab3d8Srobert data.PutHex32(0); // uint32_t pad at the end
756061da546Spatrick
757061da546Spatrick // Write out the EXC registers
758*f6aab3d8Srobert data.PutHex32(EXCRegSet);
759*f6aab3d8Srobert data.PutHex32(EXCWordCount);
760*f6aab3d8Srobert PrintRegisterValue(reg_ctx, "far", nullptr, 8, data);
761*f6aab3d8Srobert PrintRegisterValue(reg_ctx, "esr", nullptr, 4, data);
762*f6aab3d8Srobert PrintRegisterValue(reg_ctx, "exception", nullptr, 4, data);
763061da546Spatrick return true;
764061da546Spatrick }
765061da546Spatrick return false;
766061da546Spatrick }
767061da546Spatrick
768061da546Spatrick protected:
DoReadGPR(lldb::tid_t tid,int flavor,GPR & gpr)769061da546Spatrick int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
770061da546Spatrick
DoReadFPU(lldb::tid_t tid,int flavor,FPU & fpu)771061da546Spatrick int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
772061da546Spatrick
DoReadEXC(lldb::tid_t tid,int flavor,EXC & exc)773061da546Spatrick int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
774061da546Spatrick
DoReadDBG(lldb::tid_t tid,int flavor,DBG & dbg)775061da546Spatrick int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
776061da546Spatrick
DoWriteGPR(lldb::tid_t tid,int flavor,const GPR & gpr)777061da546Spatrick int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
778061da546Spatrick return 0;
779061da546Spatrick }
780061da546Spatrick
DoWriteFPU(lldb::tid_t tid,int flavor,const FPU & fpu)781061da546Spatrick int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
782061da546Spatrick return 0;
783061da546Spatrick }
784061da546Spatrick
DoWriteEXC(lldb::tid_t tid,int flavor,const EXC & exc)785061da546Spatrick int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
786061da546Spatrick return 0;
787061da546Spatrick }
788061da546Spatrick
DoWriteDBG(lldb::tid_t tid,int flavor,const DBG & dbg)789061da546Spatrick int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
790061da546Spatrick return -1;
791061da546Spatrick }
792061da546Spatrick };
793061da546Spatrick
MachHeaderSizeFromMagic(uint32_t magic)794061da546Spatrick static uint32_t MachHeaderSizeFromMagic(uint32_t magic) {
795061da546Spatrick switch (magic) {
796061da546Spatrick case MH_MAGIC:
797061da546Spatrick case MH_CIGAM:
798be691f3bSpatrick return sizeof(struct llvm::MachO::mach_header);
799061da546Spatrick
800061da546Spatrick case MH_MAGIC_64:
801061da546Spatrick case MH_CIGAM_64:
802be691f3bSpatrick return sizeof(struct llvm::MachO::mach_header_64);
803061da546Spatrick break;
804061da546Spatrick
805061da546Spatrick default:
806061da546Spatrick break;
807061da546Spatrick }
808061da546Spatrick return 0;
809061da546Spatrick }
810061da546Spatrick
811061da546Spatrick #define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008
812061da546Spatrick
813061da546Spatrick char ObjectFileMachO::ID;
814061da546Spatrick
Initialize()815061da546Spatrick void ObjectFileMachO::Initialize() {
816061da546Spatrick PluginManager::RegisterPlugin(
817061da546Spatrick GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance,
818061da546Spatrick CreateMemoryInstance, GetModuleSpecifications, SaveCore);
819061da546Spatrick }
820061da546Spatrick
Terminate()821061da546Spatrick void ObjectFileMachO::Terminate() {
822061da546Spatrick PluginManager::UnregisterPlugin(CreateInstance);
823061da546Spatrick }
824061da546Spatrick
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)825061da546Spatrick ObjectFile *ObjectFileMachO::CreateInstance(const lldb::ModuleSP &module_sp,
826*f6aab3d8Srobert DataBufferSP data_sp,
827061da546Spatrick lldb::offset_t data_offset,
828061da546Spatrick const FileSpec *file,
829061da546Spatrick lldb::offset_t file_offset,
830061da546Spatrick lldb::offset_t length) {
831061da546Spatrick if (!data_sp) {
832061da546Spatrick data_sp = MapFileData(*file, length, file_offset);
833061da546Spatrick if (!data_sp)
834061da546Spatrick return nullptr;
835061da546Spatrick data_offset = 0;
836061da546Spatrick }
837061da546Spatrick
838061da546Spatrick if (!ObjectFileMachO::MagicBytesMatch(data_sp, data_offset, length))
839061da546Spatrick return nullptr;
840061da546Spatrick
841061da546Spatrick // Update the data to contain the entire file if it doesn't already
842061da546Spatrick if (data_sp->GetByteSize() < length) {
843061da546Spatrick data_sp = MapFileData(*file, length, file_offset);
844061da546Spatrick if (!data_sp)
845061da546Spatrick return nullptr;
846061da546Spatrick data_offset = 0;
847061da546Spatrick }
848061da546Spatrick auto objfile_up = std::make_unique<ObjectFileMachO>(
849061da546Spatrick module_sp, data_sp, data_offset, file, file_offset, length);
850061da546Spatrick if (!objfile_up || !objfile_up->ParseHeader())
851061da546Spatrick return nullptr;
852061da546Spatrick
853061da546Spatrick return objfile_up.release();
854061da546Spatrick }
855061da546Spatrick
CreateMemoryInstance(const lldb::ModuleSP & module_sp,WritableDataBufferSP data_sp,const ProcessSP & process_sp,lldb::addr_t header_addr)856061da546Spatrick ObjectFile *ObjectFileMachO::CreateMemoryInstance(
857*f6aab3d8Srobert const lldb::ModuleSP &module_sp, WritableDataBufferSP data_sp,
858061da546Spatrick const ProcessSP &process_sp, lldb::addr_t header_addr) {
859061da546Spatrick if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
860061da546Spatrick std::unique_ptr<ObjectFile> objfile_up(
861061da546Spatrick new ObjectFileMachO(module_sp, data_sp, process_sp, header_addr));
862061da546Spatrick if (objfile_up.get() && objfile_up->ParseHeader())
863061da546Spatrick return objfile_up.release();
864061da546Spatrick }
865061da546Spatrick return nullptr;
866061da546Spatrick }
867061da546Spatrick
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)868061da546Spatrick size_t ObjectFileMachO::GetModuleSpecifications(
869061da546Spatrick const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
870061da546Spatrick lldb::offset_t data_offset, lldb::offset_t file_offset,
871061da546Spatrick lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
872061da546Spatrick const size_t initial_count = specs.GetSize();
873061da546Spatrick
874061da546Spatrick if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
875061da546Spatrick DataExtractor data;
876061da546Spatrick data.SetData(data_sp);
877061da546Spatrick llvm::MachO::mach_header header;
878061da546Spatrick if (ParseHeader(data, &data_offset, header)) {
879061da546Spatrick size_t header_and_load_cmds =
880061da546Spatrick header.sizeofcmds + MachHeaderSizeFromMagic(header.magic);
881061da546Spatrick if (header_and_load_cmds >= data_sp->GetByteSize()) {
882061da546Spatrick data_sp = MapFileData(file, header_and_load_cmds, file_offset);
883061da546Spatrick data.SetData(data_sp);
884061da546Spatrick data_offset = MachHeaderSizeFromMagic(header.magic);
885061da546Spatrick }
886061da546Spatrick if (data_sp) {
887061da546Spatrick ModuleSpec base_spec;
888061da546Spatrick base_spec.GetFileSpec() = file;
889061da546Spatrick base_spec.SetObjectOffset(file_offset);
890061da546Spatrick base_spec.SetObjectSize(length);
891061da546Spatrick GetAllArchSpecs(header, data, data_offset, base_spec, specs);
892061da546Spatrick }
893061da546Spatrick }
894061da546Spatrick }
895061da546Spatrick return specs.GetSize() - initial_count;
896061da546Spatrick }
897061da546Spatrick
GetSegmentNameTEXT()898061da546Spatrick ConstString ObjectFileMachO::GetSegmentNameTEXT() {
899061da546Spatrick static ConstString g_segment_name_TEXT("__TEXT");
900061da546Spatrick return g_segment_name_TEXT;
901061da546Spatrick }
902061da546Spatrick
GetSegmentNameDATA()903061da546Spatrick ConstString ObjectFileMachO::GetSegmentNameDATA() {
904061da546Spatrick static ConstString g_segment_name_DATA("__DATA");
905061da546Spatrick return g_segment_name_DATA;
906061da546Spatrick }
907061da546Spatrick
GetSegmentNameDATA_DIRTY()908061da546Spatrick ConstString ObjectFileMachO::GetSegmentNameDATA_DIRTY() {
909061da546Spatrick static ConstString g_segment_name("__DATA_DIRTY");
910061da546Spatrick return g_segment_name;
911061da546Spatrick }
912061da546Spatrick
GetSegmentNameDATA_CONST()913061da546Spatrick ConstString ObjectFileMachO::GetSegmentNameDATA_CONST() {
914061da546Spatrick static ConstString g_segment_name("__DATA_CONST");
915061da546Spatrick return g_segment_name;
916061da546Spatrick }
917061da546Spatrick
GetSegmentNameOBJC()918061da546Spatrick ConstString ObjectFileMachO::GetSegmentNameOBJC() {
919061da546Spatrick static ConstString g_segment_name_OBJC("__OBJC");
920061da546Spatrick return g_segment_name_OBJC;
921061da546Spatrick }
922061da546Spatrick
GetSegmentNameLINKEDIT()923061da546Spatrick ConstString ObjectFileMachO::GetSegmentNameLINKEDIT() {
924061da546Spatrick static ConstString g_section_name_LINKEDIT("__LINKEDIT");
925061da546Spatrick return g_section_name_LINKEDIT;
926061da546Spatrick }
927061da546Spatrick
GetSegmentNameDWARF()928061da546Spatrick ConstString ObjectFileMachO::GetSegmentNameDWARF() {
929061da546Spatrick static ConstString g_section_name("__DWARF");
930061da546Spatrick return g_section_name;
931061da546Spatrick }
932061da546Spatrick
GetSectionNameEHFrame()933061da546Spatrick ConstString ObjectFileMachO::GetSectionNameEHFrame() {
934061da546Spatrick static ConstString g_section_name_eh_frame("__eh_frame");
935061da546Spatrick return g_section_name_eh_frame;
936061da546Spatrick }
937061da546Spatrick
MagicBytesMatch(DataBufferSP data_sp,lldb::addr_t data_offset,lldb::addr_t data_length)938*f6aab3d8Srobert bool ObjectFileMachO::MagicBytesMatch(DataBufferSP data_sp,
939061da546Spatrick lldb::addr_t data_offset,
940061da546Spatrick lldb::addr_t data_length) {
941061da546Spatrick DataExtractor data;
942061da546Spatrick data.SetData(data_sp, data_offset, data_length);
943061da546Spatrick lldb::offset_t offset = 0;
944061da546Spatrick uint32_t magic = data.GetU32(&offset);
945*f6aab3d8Srobert
946*f6aab3d8Srobert offset += 4; // cputype
947*f6aab3d8Srobert offset += 4; // cpusubtype
948*f6aab3d8Srobert uint32_t filetype = data.GetU32(&offset);
949*f6aab3d8Srobert
950*f6aab3d8Srobert // A fileset has a Mach-O header but is not an
951*f6aab3d8Srobert // individual file and must be handled via an
952*f6aab3d8Srobert // ObjectContainer plugin.
953*f6aab3d8Srobert if (filetype == llvm::MachO::MH_FILESET)
954*f6aab3d8Srobert return false;
955*f6aab3d8Srobert
956061da546Spatrick return MachHeaderSizeFromMagic(magic) != 0;
957061da546Spatrick }
958061da546Spatrick
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)959061da546Spatrick ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
960*f6aab3d8Srobert DataBufferSP data_sp,
961061da546Spatrick lldb::offset_t data_offset,
962061da546Spatrick const FileSpec *file,
963061da546Spatrick lldb::offset_t file_offset,
964061da546Spatrick lldb::offset_t length)
965061da546Spatrick : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
966061da546Spatrick m_mach_segments(), m_mach_sections(), m_entry_point_address(),
967061da546Spatrick m_thread_context_offsets(), m_thread_context_offsets_valid(false),
968061da546Spatrick m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
969061da546Spatrick ::memset(&m_header, 0, sizeof(m_header));
970061da546Spatrick ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
971061da546Spatrick }
972061da546Spatrick
ObjectFileMachO(const lldb::ModuleSP & module_sp,lldb::WritableDataBufferSP header_data_sp,const lldb::ProcessSP & process_sp,lldb::addr_t header_addr)973061da546Spatrick ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
974*f6aab3d8Srobert lldb::WritableDataBufferSP header_data_sp,
975061da546Spatrick const lldb::ProcessSP &process_sp,
976061da546Spatrick lldb::addr_t header_addr)
977061da546Spatrick : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
978061da546Spatrick m_mach_segments(), m_mach_sections(), m_entry_point_address(),
979061da546Spatrick m_thread_context_offsets(), m_thread_context_offsets_valid(false),
980061da546Spatrick m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
981061da546Spatrick ::memset(&m_header, 0, sizeof(m_header));
982061da546Spatrick ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
983061da546Spatrick }
984061da546Spatrick
ParseHeader(DataExtractor & data,lldb::offset_t * data_offset_ptr,llvm::MachO::mach_header & header)985061da546Spatrick bool ObjectFileMachO::ParseHeader(DataExtractor &data,
986061da546Spatrick lldb::offset_t *data_offset_ptr,
987061da546Spatrick llvm::MachO::mach_header &header) {
988061da546Spatrick data.SetByteOrder(endian::InlHostByteOrder());
989061da546Spatrick // Leave magic in the original byte order
990061da546Spatrick header.magic = data.GetU32(data_offset_ptr);
991061da546Spatrick bool can_parse = false;
992061da546Spatrick bool is_64_bit = false;
993061da546Spatrick switch (header.magic) {
994061da546Spatrick case MH_MAGIC:
995061da546Spatrick data.SetByteOrder(endian::InlHostByteOrder());
996061da546Spatrick data.SetAddressByteSize(4);
997061da546Spatrick can_parse = true;
998061da546Spatrick break;
999061da546Spatrick
1000061da546Spatrick case MH_MAGIC_64:
1001061da546Spatrick data.SetByteOrder(endian::InlHostByteOrder());
1002061da546Spatrick data.SetAddressByteSize(8);
1003061da546Spatrick can_parse = true;
1004061da546Spatrick is_64_bit = true;
1005061da546Spatrick break;
1006061da546Spatrick
1007061da546Spatrick case MH_CIGAM:
1008061da546Spatrick data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1009061da546Spatrick ? eByteOrderLittle
1010061da546Spatrick : eByteOrderBig);
1011061da546Spatrick data.SetAddressByteSize(4);
1012061da546Spatrick can_parse = true;
1013061da546Spatrick break;
1014061da546Spatrick
1015061da546Spatrick case MH_CIGAM_64:
1016061da546Spatrick data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1017061da546Spatrick ? eByteOrderLittle
1018061da546Spatrick : eByteOrderBig);
1019061da546Spatrick data.SetAddressByteSize(8);
1020061da546Spatrick is_64_bit = true;
1021061da546Spatrick can_parse = true;
1022061da546Spatrick break;
1023061da546Spatrick
1024061da546Spatrick default:
1025061da546Spatrick break;
1026061da546Spatrick }
1027061da546Spatrick
1028061da546Spatrick if (can_parse) {
1029061da546Spatrick data.GetU32(data_offset_ptr, &header.cputype, 6);
1030061da546Spatrick if (is_64_bit)
1031061da546Spatrick *data_offset_ptr += 4;
1032061da546Spatrick return true;
1033061da546Spatrick } else {
1034061da546Spatrick memset(&header, 0, sizeof(header));
1035061da546Spatrick }
1036061da546Spatrick return false;
1037061da546Spatrick }
1038061da546Spatrick
ParseHeader()1039061da546Spatrick bool ObjectFileMachO::ParseHeader() {
1040061da546Spatrick ModuleSP module_sp(GetModule());
1041061da546Spatrick if (!module_sp)
1042061da546Spatrick return false;
1043061da546Spatrick
1044061da546Spatrick std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1045061da546Spatrick bool can_parse = false;
1046061da546Spatrick lldb::offset_t offset = 0;
1047061da546Spatrick m_data.SetByteOrder(endian::InlHostByteOrder());
1048061da546Spatrick // Leave magic in the original byte order
1049061da546Spatrick m_header.magic = m_data.GetU32(&offset);
1050061da546Spatrick switch (m_header.magic) {
1051061da546Spatrick case MH_MAGIC:
1052061da546Spatrick m_data.SetByteOrder(endian::InlHostByteOrder());
1053061da546Spatrick m_data.SetAddressByteSize(4);
1054061da546Spatrick can_parse = true;
1055061da546Spatrick break;
1056061da546Spatrick
1057061da546Spatrick case MH_MAGIC_64:
1058061da546Spatrick m_data.SetByteOrder(endian::InlHostByteOrder());
1059061da546Spatrick m_data.SetAddressByteSize(8);
1060061da546Spatrick can_parse = true;
1061061da546Spatrick break;
1062061da546Spatrick
1063061da546Spatrick case MH_CIGAM:
1064061da546Spatrick m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1065061da546Spatrick ? eByteOrderLittle
1066061da546Spatrick : eByteOrderBig);
1067061da546Spatrick m_data.SetAddressByteSize(4);
1068061da546Spatrick can_parse = true;
1069061da546Spatrick break;
1070061da546Spatrick
1071061da546Spatrick case MH_CIGAM_64:
1072061da546Spatrick m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1073061da546Spatrick ? eByteOrderLittle
1074061da546Spatrick : eByteOrderBig);
1075061da546Spatrick m_data.SetAddressByteSize(8);
1076061da546Spatrick can_parse = true;
1077061da546Spatrick break;
1078061da546Spatrick
1079061da546Spatrick default:
1080061da546Spatrick break;
1081061da546Spatrick }
1082061da546Spatrick
1083061da546Spatrick if (can_parse) {
1084061da546Spatrick m_data.GetU32(&offset, &m_header.cputype, 6);
1085061da546Spatrick
1086061da546Spatrick ModuleSpecList all_specs;
1087061da546Spatrick ModuleSpec base_spec;
1088061da546Spatrick GetAllArchSpecs(m_header, m_data, MachHeaderSizeFromMagic(m_header.magic),
1089061da546Spatrick base_spec, all_specs);
1090061da546Spatrick
1091061da546Spatrick for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
1092061da546Spatrick ArchSpec mach_arch =
1093061da546Spatrick all_specs.GetModuleSpecRefAtIndex(i).GetArchitecture();
1094061da546Spatrick
1095061da546Spatrick // Check if the module has a required architecture
1096061da546Spatrick const ArchSpec &module_arch = module_sp->GetArchitecture();
1097061da546Spatrick if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch))
1098061da546Spatrick continue;
1099061da546Spatrick
1100061da546Spatrick if (SetModulesArchitecture(mach_arch)) {
1101061da546Spatrick const size_t header_and_lc_size =
1102061da546Spatrick m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
1103061da546Spatrick if (m_data.GetByteSize() < header_and_lc_size) {
1104061da546Spatrick DataBufferSP data_sp;
1105061da546Spatrick ProcessSP process_sp(m_process_wp.lock());
1106061da546Spatrick if (process_sp) {
1107061da546Spatrick data_sp = ReadMemory(process_sp, m_memory_addr, header_and_lc_size);
1108061da546Spatrick } else {
1109061da546Spatrick // Read in all only the load command data from the file on disk
1110061da546Spatrick data_sp = MapFileData(m_file, header_and_lc_size, m_file_offset);
1111061da546Spatrick if (data_sp->GetByteSize() != header_and_lc_size)
1112061da546Spatrick continue;
1113061da546Spatrick }
1114061da546Spatrick if (data_sp)
1115061da546Spatrick m_data.SetData(data_sp);
1116061da546Spatrick }
1117061da546Spatrick }
1118061da546Spatrick return true;
1119061da546Spatrick }
1120061da546Spatrick // None found.
1121061da546Spatrick return false;
1122061da546Spatrick } else {
1123be691f3bSpatrick memset(&m_header, 0, sizeof(struct llvm::MachO::mach_header));
1124061da546Spatrick }
1125061da546Spatrick return false;
1126061da546Spatrick }
1127061da546Spatrick
GetByteOrder() const1128061da546Spatrick ByteOrder ObjectFileMachO::GetByteOrder() const {
1129061da546Spatrick return m_data.GetByteOrder();
1130061da546Spatrick }
1131061da546Spatrick
IsExecutable() const1132061da546Spatrick bool ObjectFileMachO::IsExecutable() const {
1133061da546Spatrick return m_header.filetype == MH_EXECUTE;
1134061da546Spatrick }
1135061da546Spatrick
IsDynamicLoader() const1136061da546Spatrick bool ObjectFileMachO::IsDynamicLoader() const {
1137061da546Spatrick return m_header.filetype == MH_DYLINKER;
1138061da546Spatrick }
1139061da546Spatrick
IsSharedCacheBinary() const1140*f6aab3d8Srobert bool ObjectFileMachO::IsSharedCacheBinary() const {
1141*f6aab3d8Srobert return m_header.flags & MH_DYLIB_IN_CACHE;
1142*f6aab3d8Srobert }
1143*f6aab3d8Srobert
GetAddressByteSize() const1144061da546Spatrick uint32_t ObjectFileMachO::GetAddressByteSize() const {
1145061da546Spatrick return m_data.GetAddressByteSize();
1146061da546Spatrick }
1147061da546Spatrick
GetAddressClass(lldb::addr_t file_addr)1148061da546Spatrick AddressClass ObjectFileMachO::GetAddressClass(lldb::addr_t file_addr) {
1149061da546Spatrick Symtab *symtab = GetSymtab();
1150061da546Spatrick if (!symtab)
1151061da546Spatrick return AddressClass::eUnknown;
1152061da546Spatrick
1153061da546Spatrick Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
1154061da546Spatrick if (symbol) {
1155061da546Spatrick if (symbol->ValueIsAddress()) {
1156061da546Spatrick SectionSP section_sp(symbol->GetAddressRef().GetSection());
1157061da546Spatrick if (section_sp) {
1158061da546Spatrick const lldb::SectionType section_type = section_sp->GetType();
1159061da546Spatrick switch (section_type) {
1160061da546Spatrick case eSectionTypeInvalid:
1161061da546Spatrick return AddressClass::eUnknown;
1162061da546Spatrick
1163061da546Spatrick case eSectionTypeCode:
1164061da546Spatrick if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
1165061da546Spatrick // For ARM we have a bit in the n_desc field of the symbol that
1166061da546Spatrick // tells us ARM/Thumb which is bit 0x0008.
1167061da546Spatrick if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
1168061da546Spatrick return AddressClass::eCodeAlternateISA;
1169061da546Spatrick }
1170061da546Spatrick return AddressClass::eCode;
1171061da546Spatrick
1172061da546Spatrick case eSectionTypeContainer:
1173061da546Spatrick return AddressClass::eUnknown;
1174061da546Spatrick
1175061da546Spatrick case eSectionTypeData:
1176061da546Spatrick case eSectionTypeDataCString:
1177061da546Spatrick case eSectionTypeDataCStringPointers:
1178061da546Spatrick case eSectionTypeDataSymbolAddress:
1179061da546Spatrick case eSectionTypeData4:
1180061da546Spatrick case eSectionTypeData8:
1181061da546Spatrick case eSectionTypeData16:
1182061da546Spatrick case eSectionTypeDataPointers:
1183061da546Spatrick case eSectionTypeZeroFill:
1184061da546Spatrick case eSectionTypeDataObjCMessageRefs:
1185061da546Spatrick case eSectionTypeDataObjCCFStrings:
1186061da546Spatrick case eSectionTypeGoSymtab:
1187061da546Spatrick return AddressClass::eData;
1188061da546Spatrick
1189061da546Spatrick case eSectionTypeDebug:
1190061da546Spatrick case eSectionTypeDWARFDebugAbbrev:
1191061da546Spatrick case eSectionTypeDWARFDebugAbbrevDwo:
1192061da546Spatrick case eSectionTypeDWARFDebugAddr:
1193061da546Spatrick case eSectionTypeDWARFDebugAranges:
1194061da546Spatrick case eSectionTypeDWARFDebugCuIndex:
1195061da546Spatrick case eSectionTypeDWARFDebugFrame:
1196061da546Spatrick case eSectionTypeDWARFDebugInfo:
1197061da546Spatrick case eSectionTypeDWARFDebugInfoDwo:
1198061da546Spatrick case eSectionTypeDWARFDebugLine:
1199061da546Spatrick case eSectionTypeDWARFDebugLineStr:
1200061da546Spatrick case eSectionTypeDWARFDebugLoc:
1201061da546Spatrick case eSectionTypeDWARFDebugLocDwo:
1202061da546Spatrick case eSectionTypeDWARFDebugLocLists:
1203061da546Spatrick case eSectionTypeDWARFDebugLocListsDwo:
1204061da546Spatrick case eSectionTypeDWARFDebugMacInfo:
1205061da546Spatrick case eSectionTypeDWARFDebugMacro:
1206061da546Spatrick case eSectionTypeDWARFDebugNames:
1207061da546Spatrick case eSectionTypeDWARFDebugPubNames:
1208061da546Spatrick case eSectionTypeDWARFDebugPubTypes:
1209061da546Spatrick case eSectionTypeDWARFDebugRanges:
1210061da546Spatrick case eSectionTypeDWARFDebugRngLists:
1211061da546Spatrick case eSectionTypeDWARFDebugRngListsDwo:
1212061da546Spatrick case eSectionTypeDWARFDebugStr:
1213061da546Spatrick case eSectionTypeDWARFDebugStrDwo:
1214061da546Spatrick case eSectionTypeDWARFDebugStrOffsets:
1215061da546Spatrick case eSectionTypeDWARFDebugStrOffsetsDwo:
1216dda28197Spatrick case eSectionTypeDWARFDebugTuIndex:
1217061da546Spatrick case eSectionTypeDWARFDebugTypes:
1218061da546Spatrick case eSectionTypeDWARFDebugTypesDwo:
1219061da546Spatrick case eSectionTypeDWARFAppleNames:
1220061da546Spatrick case eSectionTypeDWARFAppleTypes:
1221061da546Spatrick case eSectionTypeDWARFAppleNamespaces:
1222061da546Spatrick case eSectionTypeDWARFAppleObjC:
1223061da546Spatrick case eSectionTypeDWARFGNUDebugAltLink:
1224061da546Spatrick return AddressClass::eDebug;
1225061da546Spatrick
1226061da546Spatrick case eSectionTypeEHFrame:
1227061da546Spatrick case eSectionTypeARMexidx:
1228061da546Spatrick case eSectionTypeARMextab:
1229061da546Spatrick case eSectionTypeCompactUnwind:
1230061da546Spatrick return AddressClass::eRuntime;
1231061da546Spatrick
1232061da546Spatrick case eSectionTypeAbsoluteAddress:
1233061da546Spatrick case eSectionTypeELFSymbolTable:
1234061da546Spatrick case eSectionTypeELFDynamicSymbols:
1235061da546Spatrick case eSectionTypeELFRelocationEntries:
1236061da546Spatrick case eSectionTypeELFDynamicLinkInfo:
1237061da546Spatrick case eSectionTypeOther:
1238061da546Spatrick return AddressClass::eUnknown;
1239061da546Spatrick }
1240061da546Spatrick }
1241061da546Spatrick }
1242061da546Spatrick
1243061da546Spatrick const SymbolType symbol_type = symbol->GetType();
1244061da546Spatrick switch (symbol_type) {
1245061da546Spatrick case eSymbolTypeAny:
1246061da546Spatrick return AddressClass::eUnknown;
1247061da546Spatrick case eSymbolTypeAbsolute:
1248061da546Spatrick return AddressClass::eUnknown;
1249061da546Spatrick
1250061da546Spatrick case eSymbolTypeCode:
1251061da546Spatrick case eSymbolTypeTrampoline:
1252061da546Spatrick case eSymbolTypeResolver:
1253061da546Spatrick if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
1254061da546Spatrick // For ARM we have a bit in the n_desc field of the symbol that tells
1255061da546Spatrick // us ARM/Thumb which is bit 0x0008.
1256061da546Spatrick if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
1257061da546Spatrick return AddressClass::eCodeAlternateISA;
1258061da546Spatrick }
1259061da546Spatrick return AddressClass::eCode;
1260061da546Spatrick
1261061da546Spatrick case eSymbolTypeData:
1262061da546Spatrick return AddressClass::eData;
1263061da546Spatrick case eSymbolTypeRuntime:
1264061da546Spatrick return AddressClass::eRuntime;
1265061da546Spatrick case eSymbolTypeException:
1266061da546Spatrick return AddressClass::eRuntime;
1267061da546Spatrick case eSymbolTypeSourceFile:
1268061da546Spatrick return AddressClass::eDebug;
1269061da546Spatrick case eSymbolTypeHeaderFile:
1270061da546Spatrick return AddressClass::eDebug;
1271061da546Spatrick case eSymbolTypeObjectFile:
1272061da546Spatrick return AddressClass::eDebug;
1273061da546Spatrick case eSymbolTypeCommonBlock:
1274061da546Spatrick return AddressClass::eDebug;
1275061da546Spatrick case eSymbolTypeBlock:
1276061da546Spatrick return AddressClass::eDebug;
1277061da546Spatrick case eSymbolTypeLocal:
1278061da546Spatrick return AddressClass::eData;
1279061da546Spatrick case eSymbolTypeParam:
1280061da546Spatrick return AddressClass::eData;
1281061da546Spatrick case eSymbolTypeVariable:
1282061da546Spatrick return AddressClass::eData;
1283061da546Spatrick case eSymbolTypeVariableType:
1284061da546Spatrick return AddressClass::eDebug;
1285061da546Spatrick case eSymbolTypeLineEntry:
1286061da546Spatrick return AddressClass::eDebug;
1287061da546Spatrick case eSymbolTypeLineHeader:
1288061da546Spatrick return AddressClass::eDebug;
1289061da546Spatrick case eSymbolTypeScopeBegin:
1290061da546Spatrick return AddressClass::eDebug;
1291061da546Spatrick case eSymbolTypeScopeEnd:
1292061da546Spatrick return AddressClass::eDebug;
1293061da546Spatrick case eSymbolTypeAdditional:
1294061da546Spatrick return AddressClass::eUnknown;
1295061da546Spatrick case eSymbolTypeCompiler:
1296061da546Spatrick return AddressClass::eDebug;
1297061da546Spatrick case eSymbolTypeInstrumentation:
1298061da546Spatrick return AddressClass::eDebug;
1299061da546Spatrick case eSymbolTypeUndefined:
1300061da546Spatrick return AddressClass::eUnknown;
1301061da546Spatrick case eSymbolTypeObjCClass:
1302061da546Spatrick return AddressClass::eRuntime;
1303061da546Spatrick case eSymbolTypeObjCMetaClass:
1304061da546Spatrick return AddressClass::eRuntime;
1305061da546Spatrick case eSymbolTypeObjCIVar:
1306061da546Spatrick return AddressClass::eRuntime;
1307061da546Spatrick case eSymbolTypeReExported:
1308061da546Spatrick return AddressClass::eRuntime;
1309061da546Spatrick }
1310061da546Spatrick }
1311061da546Spatrick return AddressClass::eUnknown;
1312061da546Spatrick }
1313061da546Spatrick
IsStripped()1314061da546Spatrick bool ObjectFileMachO::IsStripped() {
1315061da546Spatrick if (m_dysymtab.cmd == 0) {
1316061da546Spatrick ModuleSP module_sp(GetModule());
1317061da546Spatrick if (module_sp) {
1318061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1319061da546Spatrick for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1320061da546Spatrick const lldb::offset_t load_cmd_offset = offset;
1321061da546Spatrick
1322*f6aab3d8Srobert llvm::MachO::load_command lc = {};
1323061da546Spatrick if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
1324061da546Spatrick break;
1325061da546Spatrick if (lc.cmd == LC_DYSYMTAB) {
1326061da546Spatrick m_dysymtab.cmd = lc.cmd;
1327061da546Spatrick m_dysymtab.cmdsize = lc.cmdsize;
1328061da546Spatrick if (m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1329061da546Spatrick (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) ==
1330061da546Spatrick nullptr) {
1331061da546Spatrick // Clear m_dysymtab if we were unable to read all items from the
1332061da546Spatrick // load command
1333061da546Spatrick ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
1334061da546Spatrick }
1335061da546Spatrick }
1336061da546Spatrick offset = load_cmd_offset + lc.cmdsize;
1337061da546Spatrick }
1338061da546Spatrick }
1339061da546Spatrick }
1340061da546Spatrick if (m_dysymtab.cmd)
1341061da546Spatrick return m_dysymtab.nlocalsym <= 1;
1342061da546Spatrick return false;
1343061da546Spatrick }
1344061da546Spatrick
GetEncryptedFileRanges()1345061da546Spatrick ObjectFileMachO::EncryptedFileRanges ObjectFileMachO::GetEncryptedFileRanges() {
1346061da546Spatrick EncryptedFileRanges result;
1347061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1348061da546Spatrick
1349be691f3bSpatrick llvm::MachO::encryption_info_command encryption_cmd;
1350061da546Spatrick for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1351061da546Spatrick const lldb::offset_t load_cmd_offset = offset;
1352061da546Spatrick if (m_data.GetU32(&offset, &encryption_cmd, 2) == nullptr)
1353061da546Spatrick break;
1354061da546Spatrick
1355061da546Spatrick // LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for the
1356061da546Spatrick // 3 fields we care about, so treat them the same.
1357061da546Spatrick if (encryption_cmd.cmd == LC_ENCRYPTION_INFO ||
1358061da546Spatrick encryption_cmd.cmd == LC_ENCRYPTION_INFO_64) {
1359061da546Spatrick if (m_data.GetU32(&offset, &encryption_cmd.cryptoff, 3)) {
1360061da546Spatrick if (encryption_cmd.cryptid != 0) {
1361061da546Spatrick EncryptedFileRanges::Entry entry;
1362061da546Spatrick entry.SetRangeBase(encryption_cmd.cryptoff);
1363061da546Spatrick entry.SetByteSize(encryption_cmd.cryptsize);
1364061da546Spatrick result.Append(entry);
1365061da546Spatrick }
1366061da546Spatrick }
1367061da546Spatrick }
1368061da546Spatrick offset = load_cmd_offset + encryption_cmd.cmdsize;
1369061da546Spatrick }
1370061da546Spatrick
1371061da546Spatrick return result;
1372061da546Spatrick }
1373061da546Spatrick
SanitizeSegmentCommand(llvm::MachO::segment_command_64 & seg_cmd,uint32_t cmd_idx)1374be691f3bSpatrick void ObjectFileMachO::SanitizeSegmentCommand(
1375be691f3bSpatrick llvm::MachO::segment_command_64 &seg_cmd, uint32_t cmd_idx) {
1376061da546Spatrick if (m_length == 0 || seg_cmd.filesize == 0)
1377061da546Spatrick return;
1378061da546Spatrick
1379*f6aab3d8Srobert if (IsSharedCacheBinary() && !IsInMemory()) {
1380be691f3bSpatrick // In shared cache images, the load commands are relative to the
1381be691f3bSpatrick // shared cache file, and not the specific image we are
1382be691f3bSpatrick // examining. Let's fix this up so that it looks like a normal
1383be691f3bSpatrick // image.
1384be691f3bSpatrick if (strncmp(seg_cmd.segname, "__TEXT", sizeof(seg_cmd.segname)) == 0)
1385be691f3bSpatrick m_text_address = seg_cmd.vmaddr;
1386be691f3bSpatrick if (strncmp(seg_cmd.segname, "__LINKEDIT", sizeof(seg_cmd.segname)) == 0)
1387be691f3bSpatrick m_linkedit_original_offset = seg_cmd.fileoff;
1388be691f3bSpatrick
1389be691f3bSpatrick seg_cmd.fileoff = seg_cmd.vmaddr - m_text_address;
1390be691f3bSpatrick }
1391be691f3bSpatrick
1392061da546Spatrick if (seg_cmd.fileoff > m_length) {
1393061da546Spatrick // We have a load command that says it extends past the end of the file.
1394061da546Spatrick // This is likely a corrupt file. We don't have any way to return an error
1395061da546Spatrick // condition here (this method was likely invoked from something like
1396061da546Spatrick // ObjectFile::GetSectionList()), so we just null out the section contents,
1397061da546Spatrick // and dump a message to stdout. The most common case here is core file
1398061da546Spatrick // debugging with a truncated file.
1399061da546Spatrick const char *lc_segment_name =
1400061da546Spatrick seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1401061da546Spatrick GetModule()->ReportWarning(
1402*f6aab3d8Srobert "load command {0} {1} has a fileoff ({2:x16}) that extends beyond "
1403*f6aab3d8Srobert "the end of the file ({3:x16}), ignoring this section",
1404061da546Spatrick cmd_idx, lc_segment_name, seg_cmd.fileoff, m_length);
1405061da546Spatrick
1406061da546Spatrick seg_cmd.fileoff = 0;
1407061da546Spatrick seg_cmd.filesize = 0;
1408061da546Spatrick }
1409061da546Spatrick
1410061da546Spatrick if (seg_cmd.fileoff + seg_cmd.filesize > m_length) {
1411061da546Spatrick // We have a load command that says it extends past the end of the file.
1412061da546Spatrick // This is likely a corrupt file. We don't have any way to return an error
1413061da546Spatrick // condition here (this method was likely invoked from something like
1414061da546Spatrick // ObjectFile::GetSectionList()), so we just null out the section contents,
1415061da546Spatrick // and dump a message to stdout. The most common case here is core file
1416061da546Spatrick // debugging with a truncated file.
1417061da546Spatrick const char *lc_segment_name =
1418061da546Spatrick seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1419061da546Spatrick GetModule()->ReportWarning(
1420*f6aab3d8Srobert "load command {0} {1} has a fileoff + filesize ({2:x16}) that "
1421*f6aab3d8Srobert "extends beyond the end of the file ({4:x16}), the segment will be "
1422*f6aab3d8Srobert "truncated to match",
1423061da546Spatrick cmd_idx, lc_segment_name, seg_cmd.fileoff + seg_cmd.filesize, m_length);
1424061da546Spatrick
1425061da546Spatrick // Truncate the length
1426061da546Spatrick seg_cmd.filesize = m_length - seg_cmd.fileoff;
1427061da546Spatrick }
1428061da546Spatrick }
1429061da546Spatrick
1430be691f3bSpatrick static uint32_t
GetSegmentPermissions(const llvm::MachO::segment_command_64 & seg_cmd)1431be691f3bSpatrick GetSegmentPermissions(const llvm::MachO::segment_command_64 &seg_cmd) {
1432061da546Spatrick uint32_t result = 0;
1433061da546Spatrick if (seg_cmd.initprot & VM_PROT_READ)
1434061da546Spatrick result |= ePermissionsReadable;
1435061da546Spatrick if (seg_cmd.initprot & VM_PROT_WRITE)
1436061da546Spatrick result |= ePermissionsWritable;
1437061da546Spatrick if (seg_cmd.initprot & VM_PROT_EXECUTE)
1438061da546Spatrick result |= ePermissionsExecutable;
1439061da546Spatrick return result;
1440061da546Spatrick }
1441061da546Spatrick
GetSectionType(uint32_t flags,ConstString section_name)1442061da546Spatrick static lldb::SectionType GetSectionType(uint32_t flags,
1443061da546Spatrick ConstString section_name) {
1444061da546Spatrick
1445061da546Spatrick if (flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS))
1446061da546Spatrick return eSectionTypeCode;
1447061da546Spatrick
1448061da546Spatrick uint32_t mach_sect_type = flags & SECTION_TYPE;
1449061da546Spatrick static ConstString g_sect_name_objc_data("__objc_data");
1450061da546Spatrick static ConstString g_sect_name_objc_msgrefs("__objc_msgrefs");
1451061da546Spatrick static ConstString g_sect_name_objc_selrefs("__objc_selrefs");
1452061da546Spatrick static ConstString g_sect_name_objc_classrefs("__objc_classrefs");
1453061da546Spatrick static ConstString g_sect_name_objc_superrefs("__objc_superrefs");
1454061da546Spatrick static ConstString g_sect_name_objc_const("__objc_const");
1455061da546Spatrick static ConstString g_sect_name_objc_classlist("__objc_classlist");
1456061da546Spatrick static ConstString g_sect_name_cfstring("__cfstring");
1457061da546Spatrick
1458061da546Spatrick static ConstString g_sect_name_dwarf_debug_abbrev("__debug_abbrev");
1459061da546Spatrick static ConstString g_sect_name_dwarf_debug_aranges("__debug_aranges");
1460061da546Spatrick static ConstString g_sect_name_dwarf_debug_frame("__debug_frame");
1461061da546Spatrick static ConstString g_sect_name_dwarf_debug_info("__debug_info");
1462061da546Spatrick static ConstString g_sect_name_dwarf_debug_line("__debug_line");
1463061da546Spatrick static ConstString g_sect_name_dwarf_debug_loc("__debug_loc");
1464061da546Spatrick static ConstString g_sect_name_dwarf_debug_loclists("__debug_loclists");
1465061da546Spatrick static ConstString g_sect_name_dwarf_debug_macinfo("__debug_macinfo");
1466061da546Spatrick static ConstString g_sect_name_dwarf_debug_names("__debug_names");
1467061da546Spatrick static ConstString g_sect_name_dwarf_debug_pubnames("__debug_pubnames");
1468061da546Spatrick static ConstString g_sect_name_dwarf_debug_pubtypes("__debug_pubtypes");
1469061da546Spatrick static ConstString g_sect_name_dwarf_debug_ranges("__debug_ranges");
1470061da546Spatrick static ConstString g_sect_name_dwarf_debug_str("__debug_str");
1471061da546Spatrick static ConstString g_sect_name_dwarf_debug_types("__debug_types");
1472061da546Spatrick static ConstString g_sect_name_dwarf_apple_names("__apple_names");
1473061da546Spatrick static ConstString g_sect_name_dwarf_apple_types("__apple_types");
1474061da546Spatrick static ConstString g_sect_name_dwarf_apple_namespaces("__apple_namespac");
1475061da546Spatrick static ConstString g_sect_name_dwarf_apple_objc("__apple_objc");
1476061da546Spatrick static ConstString g_sect_name_eh_frame("__eh_frame");
1477061da546Spatrick static ConstString g_sect_name_compact_unwind("__unwind_info");
1478061da546Spatrick static ConstString g_sect_name_text("__text");
1479061da546Spatrick static ConstString g_sect_name_data("__data");
1480061da546Spatrick static ConstString g_sect_name_go_symtab("__gosymtab");
1481061da546Spatrick
1482061da546Spatrick if (section_name == g_sect_name_dwarf_debug_abbrev)
1483061da546Spatrick return eSectionTypeDWARFDebugAbbrev;
1484061da546Spatrick if (section_name == g_sect_name_dwarf_debug_aranges)
1485061da546Spatrick return eSectionTypeDWARFDebugAranges;
1486061da546Spatrick if (section_name == g_sect_name_dwarf_debug_frame)
1487061da546Spatrick return eSectionTypeDWARFDebugFrame;
1488061da546Spatrick if (section_name == g_sect_name_dwarf_debug_info)
1489061da546Spatrick return eSectionTypeDWARFDebugInfo;
1490061da546Spatrick if (section_name == g_sect_name_dwarf_debug_line)
1491061da546Spatrick return eSectionTypeDWARFDebugLine;
1492061da546Spatrick if (section_name == g_sect_name_dwarf_debug_loc)
1493061da546Spatrick return eSectionTypeDWARFDebugLoc;
1494061da546Spatrick if (section_name == g_sect_name_dwarf_debug_loclists)
1495061da546Spatrick return eSectionTypeDWARFDebugLocLists;
1496061da546Spatrick if (section_name == g_sect_name_dwarf_debug_macinfo)
1497061da546Spatrick return eSectionTypeDWARFDebugMacInfo;
1498061da546Spatrick if (section_name == g_sect_name_dwarf_debug_names)
1499061da546Spatrick return eSectionTypeDWARFDebugNames;
1500061da546Spatrick if (section_name == g_sect_name_dwarf_debug_pubnames)
1501061da546Spatrick return eSectionTypeDWARFDebugPubNames;
1502061da546Spatrick if (section_name == g_sect_name_dwarf_debug_pubtypes)
1503061da546Spatrick return eSectionTypeDWARFDebugPubTypes;
1504061da546Spatrick if (section_name == g_sect_name_dwarf_debug_ranges)
1505061da546Spatrick return eSectionTypeDWARFDebugRanges;
1506061da546Spatrick if (section_name == g_sect_name_dwarf_debug_str)
1507061da546Spatrick return eSectionTypeDWARFDebugStr;
1508061da546Spatrick if (section_name == g_sect_name_dwarf_debug_types)
1509061da546Spatrick return eSectionTypeDWARFDebugTypes;
1510061da546Spatrick if (section_name == g_sect_name_dwarf_apple_names)
1511061da546Spatrick return eSectionTypeDWARFAppleNames;
1512061da546Spatrick if (section_name == g_sect_name_dwarf_apple_types)
1513061da546Spatrick return eSectionTypeDWARFAppleTypes;
1514061da546Spatrick if (section_name == g_sect_name_dwarf_apple_namespaces)
1515061da546Spatrick return eSectionTypeDWARFAppleNamespaces;
1516061da546Spatrick if (section_name == g_sect_name_dwarf_apple_objc)
1517061da546Spatrick return eSectionTypeDWARFAppleObjC;
1518061da546Spatrick if (section_name == g_sect_name_objc_selrefs)
1519061da546Spatrick return eSectionTypeDataCStringPointers;
1520061da546Spatrick if (section_name == g_sect_name_objc_msgrefs)
1521061da546Spatrick return eSectionTypeDataObjCMessageRefs;
1522061da546Spatrick if (section_name == g_sect_name_eh_frame)
1523061da546Spatrick return eSectionTypeEHFrame;
1524061da546Spatrick if (section_name == g_sect_name_compact_unwind)
1525061da546Spatrick return eSectionTypeCompactUnwind;
1526061da546Spatrick if (section_name == g_sect_name_cfstring)
1527061da546Spatrick return eSectionTypeDataObjCCFStrings;
1528061da546Spatrick if (section_name == g_sect_name_go_symtab)
1529061da546Spatrick return eSectionTypeGoSymtab;
1530061da546Spatrick if (section_name == g_sect_name_objc_data ||
1531061da546Spatrick section_name == g_sect_name_objc_classrefs ||
1532061da546Spatrick section_name == g_sect_name_objc_superrefs ||
1533061da546Spatrick section_name == g_sect_name_objc_const ||
1534061da546Spatrick section_name == g_sect_name_objc_classlist) {
1535061da546Spatrick return eSectionTypeDataPointers;
1536061da546Spatrick }
1537061da546Spatrick
1538061da546Spatrick switch (mach_sect_type) {
1539061da546Spatrick // TODO: categorize sections by other flags for regular sections
1540061da546Spatrick case S_REGULAR:
1541061da546Spatrick if (section_name == g_sect_name_text)
1542061da546Spatrick return eSectionTypeCode;
1543061da546Spatrick if (section_name == g_sect_name_data)
1544061da546Spatrick return eSectionTypeData;
1545061da546Spatrick return eSectionTypeOther;
1546061da546Spatrick case S_ZEROFILL:
1547061da546Spatrick return eSectionTypeZeroFill;
1548061da546Spatrick case S_CSTRING_LITERALS: // section with only literal C strings
1549061da546Spatrick return eSectionTypeDataCString;
1550061da546Spatrick case S_4BYTE_LITERALS: // section with only 4 byte literals
1551061da546Spatrick return eSectionTypeData4;
1552061da546Spatrick case S_8BYTE_LITERALS: // section with only 8 byte literals
1553061da546Spatrick return eSectionTypeData8;
1554061da546Spatrick case S_LITERAL_POINTERS: // section with only pointers to literals
1555061da546Spatrick return eSectionTypeDataPointers;
1556061da546Spatrick case S_NON_LAZY_SYMBOL_POINTERS: // section with only non-lazy symbol pointers
1557061da546Spatrick return eSectionTypeDataPointers;
1558061da546Spatrick case S_LAZY_SYMBOL_POINTERS: // section with only lazy symbol pointers
1559061da546Spatrick return eSectionTypeDataPointers;
1560061da546Spatrick case S_SYMBOL_STUBS: // section with only symbol stubs, byte size of stub in
1561061da546Spatrick // the reserved2 field
1562061da546Spatrick return eSectionTypeCode;
1563061da546Spatrick case S_MOD_INIT_FUNC_POINTERS: // section with only function pointers for
1564061da546Spatrick // initialization
1565061da546Spatrick return eSectionTypeDataPointers;
1566061da546Spatrick case S_MOD_TERM_FUNC_POINTERS: // section with only function pointers for
1567061da546Spatrick // termination
1568061da546Spatrick return eSectionTypeDataPointers;
1569061da546Spatrick case S_COALESCED:
1570061da546Spatrick return eSectionTypeOther;
1571061da546Spatrick case S_GB_ZEROFILL:
1572061da546Spatrick return eSectionTypeZeroFill;
1573061da546Spatrick case S_INTERPOSING: // section with only pairs of function pointers for
1574061da546Spatrick // interposing
1575061da546Spatrick return eSectionTypeCode;
1576061da546Spatrick case S_16BYTE_LITERALS: // section with only 16 byte literals
1577061da546Spatrick return eSectionTypeData16;
1578061da546Spatrick case S_DTRACE_DOF:
1579061da546Spatrick return eSectionTypeDebug;
1580061da546Spatrick case S_LAZY_DYLIB_SYMBOL_POINTERS:
1581061da546Spatrick return eSectionTypeDataPointers;
1582061da546Spatrick default:
1583061da546Spatrick return eSectionTypeOther;
1584061da546Spatrick }
1585061da546Spatrick }
1586061da546Spatrick
1587061da546Spatrick struct ObjectFileMachO::SegmentParsingContext {
1588061da546Spatrick const EncryptedFileRanges EncryptedRanges;
1589061da546Spatrick lldb_private::SectionList &UnifiedList;
1590061da546Spatrick uint32_t NextSegmentIdx = 0;
1591061da546Spatrick uint32_t NextSectionIdx = 0;
1592061da546Spatrick bool FileAddressesChanged = false;
1593061da546Spatrick
SegmentParsingContextObjectFileMachO::SegmentParsingContext1594061da546Spatrick SegmentParsingContext(EncryptedFileRanges EncryptedRanges,
1595061da546Spatrick lldb_private::SectionList &UnifiedList)
1596061da546Spatrick : EncryptedRanges(std::move(EncryptedRanges)), UnifiedList(UnifiedList) {}
1597061da546Spatrick };
1598061da546Spatrick
ProcessSegmentCommand(const llvm::MachO::load_command & load_cmd_,lldb::offset_t offset,uint32_t cmd_idx,SegmentParsingContext & context)1599be691f3bSpatrick void ObjectFileMachO::ProcessSegmentCommand(
1600be691f3bSpatrick const llvm::MachO::load_command &load_cmd_, lldb::offset_t offset,
1601be691f3bSpatrick uint32_t cmd_idx, SegmentParsingContext &context) {
1602be691f3bSpatrick llvm::MachO::segment_command_64 load_cmd;
1603061da546Spatrick memcpy(&load_cmd, &load_cmd_, sizeof(load_cmd_));
1604061da546Spatrick
1605061da546Spatrick if (!m_data.GetU8(&offset, (uint8_t *)load_cmd.segname, 16))
1606061da546Spatrick return;
1607061da546Spatrick
1608061da546Spatrick ModuleSP module_sp = GetModule();
1609061da546Spatrick const bool is_core = GetType() == eTypeCoreFile;
1610061da546Spatrick const bool is_dsym = (m_header.filetype == MH_DSYM);
1611061da546Spatrick bool add_section = true;
1612061da546Spatrick bool add_to_unified = true;
1613061da546Spatrick ConstString const_segname(
1614061da546Spatrick load_cmd.segname, strnlen(load_cmd.segname, sizeof(load_cmd.segname)));
1615061da546Spatrick
1616061da546Spatrick SectionSP unified_section_sp(
1617061da546Spatrick context.UnifiedList.FindSectionByName(const_segname));
1618061da546Spatrick if (is_dsym && unified_section_sp) {
1619061da546Spatrick if (const_segname == GetSegmentNameLINKEDIT()) {
1620061da546Spatrick // We need to keep the __LINKEDIT segment private to this object file
1621061da546Spatrick // only
1622061da546Spatrick add_to_unified = false;
1623061da546Spatrick } else {
1624061da546Spatrick // This is the dSYM file and this section has already been created by the
1625061da546Spatrick // object file, no need to create it.
1626061da546Spatrick add_section = false;
1627061da546Spatrick }
1628061da546Spatrick }
1629061da546Spatrick load_cmd.vmaddr = m_data.GetAddress(&offset);
1630061da546Spatrick load_cmd.vmsize = m_data.GetAddress(&offset);
1631061da546Spatrick load_cmd.fileoff = m_data.GetAddress(&offset);
1632061da546Spatrick load_cmd.filesize = m_data.GetAddress(&offset);
1633061da546Spatrick if (!m_data.GetU32(&offset, &load_cmd.maxprot, 4))
1634061da546Spatrick return;
1635061da546Spatrick
1636061da546Spatrick SanitizeSegmentCommand(load_cmd, cmd_idx);
1637061da546Spatrick
1638061da546Spatrick const uint32_t segment_permissions = GetSegmentPermissions(load_cmd);
1639061da546Spatrick const bool segment_is_encrypted =
1640061da546Spatrick (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
1641061da546Spatrick
1642061da546Spatrick // Keep a list of mach segments around in case we need to get at data that
1643061da546Spatrick // isn't stored in the abstracted Sections.
1644061da546Spatrick m_mach_segments.push_back(load_cmd);
1645061da546Spatrick
1646061da546Spatrick // Use a segment ID of the segment index shifted left by 8 so they never
1647061da546Spatrick // conflict with any of the sections.
1648061da546Spatrick SectionSP segment_sp;
1649061da546Spatrick if (add_section && (const_segname || is_core)) {
1650061da546Spatrick segment_sp = std::make_shared<Section>(
1651061da546Spatrick module_sp, // Module to which this section belongs
1652061da546Spatrick this, // Object file to which this sections belongs
1653061da546Spatrick ++context.NextSegmentIdx
1654061da546Spatrick << 8, // Section ID is the 1 based segment index
1655061da546Spatrick // shifted right by 8 bits as not to collide with any of the 256
1656061da546Spatrick // section IDs that are possible
1657061da546Spatrick const_segname, // Name of this section
1658061da546Spatrick eSectionTypeContainer, // This section is a container of other
1659061da546Spatrick // sections.
1660061da546Spatrick load_cmd.vmaddr, // File VM address == addresses as they are
1661061da546Spatrick // found in the object file
1662061da546Spatrick load_cmd.vmsize, // VM size in bytes of this section
1663061da546Spatrick load_cmd.fileoff, // Offset to the data for this section in
1664061da546Spatrick // the file
1665061da546Spatrick load_cmd.filesize, // Size in bytes of this section as found
1666061da546Spatrick // in the file
1667061da546Spatrick 0, // Segments have no alignment information
1668061da546Spatrick load_cmd.flags); // Flags for this section
1669061da546Spatrick
1670061da546Spatrick segment_sp->SetIsEncrypted(segment_is_encrypted);
1671061da546Spatrick m_sections_up->AddSection(segment_sp);
1672061da546Spatrick segment_sp->SetPermissions(segment_permissions);
1673061da546Spatrick if (add_to_unified)
1674061da546Spatrick context.UnifiedList.AddSection(segment_sp);
1675061da546Spatrick } else if (unified_section_sp) {
1676*f6aab3d8Srobert // If this is a dSYM and the file addresses in the dSYM differ from the
1677*f6aab3d8Srobert // file addresses in the ObjectFile, we must use the file base address for
1678*f6aab3d8Srobert // the Section from the dSYM for the DWARF to resolve correctly.
1679*f6aab3d8Srobert // This only happens with binaries in the shared cache in practice;
1680*f6aab3d8Srobert // normally a mismatch like this would give a binary & dSYM that do not
1681*f6aab3d8Srobert // match UUIDs. When a binary is included in the shared cache, its
1682*f6aab3d8Srobert // segments are rearranged to optimize the shared cache, so its file
1683*f6aab3d8Srobert // addresses will differ from what the ObjectFile had originally,
1684*f6aab3d8Srobert // and what the dSYM has.
1685061da546Spatrick if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
1686*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Symbols);
1687*f6aab3d8Srobert if (log) {
1688*f6aab3d8Srobert log->Printf(
1689*f6aab3d8Srobert "Installing dSYM's %s segment file address over ObjectFile's "
1690*f6aab3d8Srobert "so symbol table/debug info resolves correctly for %s",
1691*f6aab3d8Srobert const_segname.AsCString(),
1692*f6aab3d8Srobert module_sp->GetFileSpec().GetFilename().AsCString());
1693*f6aab3d8Srobert }
1694061da546Spatrick
1695061da546Spatrick // Make sure we've parsed the symbol table from the ObjectFile before
1696061da546Spatrick // we go around changing its Sections.
1697061da546Spatrick module_sp->GetObjectFile()->GetSymtab();
1698061da546Spatrick // eh_frame would present the same problems but we parse that on a per-
1699061da546Spatrick // function basis as-needed so it's more difficult to remove its use of
1700061da546Spatrick // the Sections. Realistically, the environments where this code path
1701061da546Spatrick // will be taken will not have eh_frame sections.
1702061da546Spatrick
1703061da546Spatrick unified_section_sp->SetFileAddress(load_cmd.vmaddr);
1704061da546Spatrick
1705061da546Spatrick // Notify the module that the section addresses have been changed once
1706061da546Spatrick // we're done so any file-address caches can be updated.
1707061da546Spatrick context.FileAddressesChanged = true;
1708061da546Spatrick }
1709061da546Spatrick m_sections_up->AddSection(unified_section_sp);
1710061da546Spatrick }
1711061da546Spatrick
1712be691f3bSpatrick llvm::MachO::section_64 sect64;
1713061da546Spatrick ::memset(§64, 0, sizeof(sect64));
1714061da546Spatrick // Push a section into our mach sections for the section at index zero
1715061da546Spatrick // (NO_SECT) if we don't have any mach sections yet...
1716061da546Spatrick if (m_mach_sections.empty())
1717061da546Spatrick m_mach_sections.push_back(sect64);
1718061da546Spatrick uint32_t segment_sect_idx;
1719061da546Spatrick const lldb::user_id_t first_segment_sectID = context.NextSectionIdx + 1;
1720061da546Spatrick
1721061da546Spatrick const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
1722061da546Spatrick for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
1723061da546Spatrick ++segment_sect_idx) {
1724061da546Spatrick if (m_data.GetU8(&offset, (uint8_t *)sect64.sectname,
1725061da546Spatrick sizeof(sect64.sectname)) == nullptr)
1726061da546Spatrick break;
1727061da546Spatrick if (m_data.GetU8(&offset, (uint8_t *)sect64.segname,
1728061da546Spatrick sizeof(sect64.segname)) == nullptr)
1729061da546Spatrick break;
1730061da546Spatrick sect64.addr = m_data.GetAddress(&offset);
1731061da546Spatrick sect64.size = m_data.GetAddress(&offset);
1732061da546Spatrick
1733061da546Spatrick if (m_data.GetU32(&offset, §64.offset, num_u32s) == nullptr)
1734061da546Spatrick break;
1735061da546Spatrick
1736*f6aab3d8Srobert if (IsSharedCacheBinary() && !IsInMemory()) {
1737be691f3bSpatrick sect64.offset = sect64.addr - m_text_address;
1738be691f3bSpatrick }
1739be691f3bSpatrick
1740061da546Spatrick // Keep a list of mach sections around in case we need to get at data that
1741061da546Spatrick // isn't stored in the abstracted Sections.
1742061da546Spatrick m_mach_sections.push_back(sect64);
1743061da546Spatrick
1744061da546Spatrick if (add_section) {
1745061da546Spatrick ConstString section_name(
1746061da546Spatrick sect64.sectname, strnlen(sect64.sectname, sizeof(sect64.sectname)));
1747061da546Spatrick if (!const_segname) {
1748061da546Spatrick // We have a segment with no name so we need to conjure up segments
1749061da546Spatrick // that correspond to the section's segname if there isn't already such
1750061da546Spatrick // a section. If there is such a section, we resize the section so that
1751061da546Spatrick // it spans all sections. We also mark these sections as fake so
1752061da546Spatrick // address matches don't hit if they land in the gaps between the child
1753061da546Spatrick // sections.
1754061da546Spatrick const_segname.SetTrimmedCStringWithLength(sect64.segname,
1755061da546Spatrick sizeof(sect64.segname));
1756061da546Spatrick segment_sp = context.UnifiedList.FindSectionByName(const_segname);
1757061da546Spatrick if (segment_sp.get()) {
1758061da546Spatrick Section *segment = segment_sp.get();
1759061da546Spatrick // Grow the section size as needed.
1760061da546Spatrick const lldb::addr_t sect64_min_addr = sect64.addr;
1761061da546Spatrick const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
1762061da546Spatrick const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
1763061da546Spatrick const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
1764061da546Spatrick const lldb::addr_t curr_seg_max_addr =
1765061da546Spatrick curr_seg_min_addr + curr_seg_byte_size;
1766061da546Spatrick if (sect64_min_addr >= curr_seg_min_addr) {
1767061da546Spatrick const lldb::addr_t new_seg_byte_size =
1768061da546Spatrick sect64_max_addr - curr_seg_min_addr;
1769061da546Spatrick // Only grow the section size if needed
1770061da546Spatrick if (new_seg_byte_size > curr_seg_byte_size)
1771061da546Spatrick segment->SetByteSize(new_seg_byte_size);
1772061da546Spatrick } else {
1773061da546Spatrick // We need to change the base address of the segment and adjust the
1774061da546Spatrick // child section offsets for all existing children.
1775061da546Spatrick const lldb::addr_t slide_amount =
1776061da546Spatrick sect64_min_addr - curr_seg_min_addr;
1777061da546Spatrick segment->Slide(slide_amount, false);
1778061da546Spatrick segment->GetChildren().Slide(-slide_amount, false);
1779061da546Spatrick segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
1780061da546Spatrick }
1781061da546Spatrick
1782061da546Spatrick // Grow the section size as needed.
1783061da546Spatrick if (sect64.offset) {
1784061da546Spatrick const lldb::addr_t segment_min_file_offset =
1785061da546Spatrick segment->GetFileOffset();
1786061da546Spatrick const lldb::addr_t segment_max_file_offset =
1787061da546Spatrick segment_min_file_offset + segment->GetFileSize();
1788061da546Spatrick
1789061da546Spatrick const lldb::addr_t section_min_file_offset = sect64.offset;
1790061da546Spatrick const lldb::addr_t section_max_file_offset =
1791061da546Spatrick section_min_file_offset + sect64.size;
1792061da546Spatrick const lldb::addr_t new_file_offset =
1793061da546Spatrick std::min(section_min_file_offset, segment_min_file_offset);
1794061da546Spatrick const lldb::addr_t new_file_size =
1795061da546Spatrick std::max(section_max_file_offset, segment_max_file_offset) -
1796061da546Spatrick new_file_offset;
1797061da546Spatrick segment->SetFileOffset(new_file_offset);
1798061da546Spatrick segment->SetFileSize(new_file_size);
1799061da546Spatrick }
1800061da546Spatrick } else {
1801061da546Spatrick // Create a fake section for the section's named segment
1802061da546Spatrick segment_sp = std::make_shared<Section>(
1803061da546Spatrick segment_sp, // Parent section
1804061da546Spatrick module_sp, // Module to which this section belongs
1805061da546Spatrick this, // Object file to which this section belongs
1806061da546Spatrick ++context.NextSegmentIdx
1807061da546Spatrick << 8, // Section ID is the 1 based segment index
1808061da546Spatrick // shifted right by 8 bits as not to
1809061da546Spatrick // collide with any of the 256 section IDs
1810061da546Spatrick // that are possible
1811061da546Spatrick const_segname, // Name of this section
1812061da546Spatrick eSectionTypeContainer, // This section is a container of
1813061da546Spatrick // other sections.
1814061da546Spatrick sect64.addr, // File VM address == addresses as they are
1815061da546Spatrick // found in the object file
1816061da546Spatrick sect64.size, // VM size in bytes of this section
1817061da546Spatrick sect64.offset, // Offset to the data for this section in
1818061da546Spatrick // the file
1819061da546Spatrick sect64.offset ? sect64.size : 0, // Size in bytes of
1820061da546Spatrick // this section as
1821061da546Spatrick // found in the file
1822061da546Spatrick sect64.align,
1823061da546Spatrick load_cmd.flags); // Flags for this section
1824061da546Spatrick segment_sp->SetIsFake(true);
1825061da546Spatrick segment_sp->SetPermissions(segment_permissions);
1826061da546Spatrick m_sections_up->AddSection(segment_sp);
1827061da546Spatrick if (add_to_unified)
1828061da546Spatrick context.UnifiedList.AddSection(segment_sp);
1829061da546Spatrick segment_sp->SetIsEncrypted(segment_is_encrypted);
1830061da546Spatrick }
1831061da546Spatrick }
1832061da546Spatrick assert(segment_sp.get());
1833061da546Spatrick
1834061da546Spatrick lldb::SectionType sect_type = GetSectionType(sect64.flags, section_name);
1835061da546Spatrick
1836061da546Spatrick SectionSP section_sp(new Section(
1837061da546Spatrick segment_sp, module_sp, this, ++context.NextSectionIdx, section_name,
1838061da546Spatrick sect_type, sect64.addr - segment_sp->GetFileAddress(), sect64.size,
1839061da546Spatrick sect64.offset, sect64.offset == 0 ? 0 : sect64.size, sect64.align,
1840061da546Spatrick sect64.flags));
1841061da546Spatrick // Set the section to be encrypted to match the segment
1842061da546Spatrick
1843061da546Spatrick bool section_is_encrypted = false;
1844061da546Spatrick if (!segment_is_encrypted && load_cmd.filesize != 0)
1845061da546Spatrick section_is_encrypted = context.EncryptedRanges.FindEntryThatContains(
1846061da546Spatrick sect64.offset) != nullptr;
1847061da546Spatrick
1848061da546Spatrick section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted);
1849061da546Spatrick section_sp->SetPermissions(segment_permissions);
1850061da546Spatrick segment_sp->GetChildren().AddSection(section_sp);
1851061da546Spatrick
1852061da546Spatrick if (segment_sp->IsFake()) {
1853061da546Spatrick segment_sp.reset();
1854061da546Spatrick const_segname.Clear();
1855061da546Spatrick }
1856061da546Spatrick }
1857061da546Spatrick }
1858061da546Spatrick if (segment_sp && is_dsym) {
1859061da546Spatrick if (first_segment_sectID <= context.NextSectionIdx) {
1860061da546Spatrick lldb::user_id_t sect_uid;
1861061da546Spatrick for (sect_uid = first_segment_sectID; sect_uid <= context.NextSectionIdx;
1862061da546Spatrick ++sect_uid) {
1863061da546Spatrick SectionSP curr_section_sp(
1864061da546Spatrick segment_sp->GetChildren().FindSectionByID(sect_uid));
1865061da546Spatrick SectionSP next_section_sp;
1866061da546Spatrick if (sect_uid + 1 <= context.NextSectionIdx)
1867061da546Spatrick next_section_sp =
1868061da546Spatrick segment_sp->GetChildren().FindSectionByID(sect_uid + 1);
1869061da546Spatrick
1870061da546Spatrick if (curr_section_sp.get()) {
1871061da546Spatrick if (curr_section_sp->GetByteSize() == 0) {
1872061da546Spatrick if (next_section_sp.get() != nullptr)
1873061da546Spatrick curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() -
1874061da546Spatrick curr_section_sp->GetFileAddress());
1875061da546Spatrick else
1876061da546Spatrick curr_section_sp->SetByteSize(load_cmd.vmsize);
1877061da546Spatrick }
1878061da546Spatrick }
1879061da546Spatrick }
1880061da546Spatrick }
1881061da546Spatrick }
1882061da546Spatrick }
1883061da546Spatrick
ProcessDysymtabCommand(const llvm::MachO::load_command & load_cmd,lldb::offset_t offset)1884be691f3bSpatrick void ObjectFileMachO::ProcessDysymtabCommand(
1885be691f3bSpatrick const llvm::MachO::load_command &load_cmd, lldb::offset_t offset) {
1886061da546Spatrick m_dysymtab.cmd = load_cmd.cmd;
1887061da546Spatrick m_dysymtab.cmdsize = load_cmd.cmdsize;
1888061da546Spatrick m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1889061da546Spatrick (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1890061da546Spatrick }
1891061da546Spatrick
CreateSections(SectionList & unified_section_list)1892061da546Spatrick void ObjectFileMachO::CreateSections(SectionList &unified_section_list) {
1893061da546Spatrick if (m_sections_up)
1894061da546Spatrick return;
1895061da546Spatrick
1896dda28197Spatrick m_sections_up = std::make_unique<SectionList>();
1897061da546Spatrick
1898061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1899061da546Spatrick // bool dump_sections = false;
1900061da546Spatrick ModuleSP module_sp(GetModule());
1901061da546Spatrick
1902061da546Spatrick offset = MachHeaderSizeFromMagic(m_header.magic);
1903061da546Spatrick
1904061da546Spatrick SegmentParsingContext context(GetEncryptedFileRanges(), unified_section_list);
1905be691f3bSpatrick llvm::MachO::load_command load_cmd;
1906061da546Spatrick for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1907061da546Spatrick const lldb::offset_t load_cmd_offset = offset;
1908061da546Spatrick if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
1909061da546Spatrick break;
1910061da546Spatrick
1911061da546Spatrick if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
1912061da546Spatrick ProcessSegmentCommand(load_cmd, offset, i, context);
1913061da546Spatrick else if (load_cmd.cmd == LC_DYSYMTAB)
1914061da546Spatrick ProcessDysymtabCommand(load_cmd, offset);
1915061da546Spatrick
1916061da546Spatrick offset = load_cmd_offset + load_cmd.cmdsize;
1917061da546Spatrick }
1918061da546Spatrick
1919061da546Spatrick if (context.FileAddressesChanged && module_sp)
1920061da546Spatrick module_sp->SectionFileAddressesChanged();
1921061da546Spatrick }
1922061da546Spatrick
1923061da546Spatrick class MachSymtabSectionInfo {
1924061da546Spatrick public:
MachSymtabSectionInfo(SectionList * section_list)1925061da546Spatrick MachSymtabSectionInfo(SectionList *section_list)
1926061da546Spatrick : m_section_list(section_list), m_section_infos() {
1927061da546Spatrick // Get the number of sections down to a depth of 1 to include all segments
1928061da546Spatrick // and their sections, but no other sections that may be added for debug
1929061da546Spatrick // map or
1930061da546Spatrick m_section_infos.resize(section_list->GetNumSections(1));
1931061da546Spatrick }
1932061da546Spatrick
GetSection(uint8_t n_sect,addr_t file_addr)1933061da546Spatrick SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
1934061da546Spatrick if (n_sect == 0)
1935061da546Spatrick return SectionSP();
1936061da546Spatrick if (n_sect < m_section_infos.size()) {
1937061da546Spatrick if (!m_section_infos[n_sect].section_sp) {
1938061da546Spatrick SectionSP section_sp(m_section_list->FindSectionByID(n_sect));
1939061da546Spatrick m_section_infos[n_sect].section_sp = section_sp;
1940061da546Spatrick if (section_sp) {
1941061da546Spatrick m_section_infos[n_sect].vm_range.SetBaseAddress(
1942061da546Spatrick section_sp->GetFileAddress());
1943061da546Spatrick m_section_infos[n_sect].vm_range.SetByteSize(
1944061da546Spatrick section_sp->GetByteSize());
1945061da546Spatrick } else {
1946be691f3bSpatrick std::string filename = "<unknown>";
1947061da546Spatrick SectionSP first_section_sp(m_section_list->GetSectionAtIndex(0));
1948061da546Spatrick if (first_section_sp)
1949be691f3bSpatrick filename = first_section_sp->GetObjectFile()->GetFileSpec().GetPath();
1950061da546Spatrick
1951*f6aab3d8Srobert Debugger::ReportError(
1952*f6aab3d8Srobert llvm::formatv("unable to find section {0} for a symbol in "
1953*f6aab3d8Srobert "{1}, corrupt file?",
1954*f6aab3d8Srobert n_sect, filename));
1955061da546Spatrick }
1956061da546Spatrick }
1957061da546Spatrick if (m_section_infos[n_sect].vm_range.Contains(file_addr)) {
1958061da546Spatrick // Symbol is in section.
1959061da546Spatrick return m_section_infos[n_sect].section_sp;
1960061da546Spatrick } else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
1961061da546Spatrick m_section_infos[n_sect].vm_range.GetBaseAddress() ==
1962061da546Spatrick file_addr) {
1963061da546Spatrick // Symbol is in section with zero size, but has the same start address
1964061da546Spatrick // as the section. This can happen with linker symbols (symbols that
1965061da546Spatrick // start with the letter 'l' or 'L'.
1966061da546Spatrick return m_section_infos[n_sect].section_sp;
1967061da546Spatrick }
1968061da546Spatrick }
1969061da546Spatrick return m_section_list->FindSectionContainingFileAddress(file_addr);
1970061da546Spatrick }
1971061da546Spatrick
1972061da546Spatrick protected:
1973061da546Spatrick struct SectionInfo {
SectionInfoMachSymtabSectionInfo::SectionInfo1974061da546Spatrick SectionInfo() : vm_range(), section_sp() {}
1975061da546Spatrick
1976061da546Spatrick VMRange vm_range;
1977061da546Spatrick SectionSP section_sp;
1978061da546Spatrick };
1979061da546Spatrick SectionList *m_section_list;
1980061da546Spatrick std::vector<SectionInfo> m_section_infos;
1981061da546Spatrick };
1982061da546Spatrick
1983dda28197Spatrick #define TRIE_SYMBOL_IS_THUMB (1ULL << 63)
1984061da546Spatrick struct TrieEntry {
DumpTrieEntry1985061da546Spatrick void Dump() const {
1986061da546Spatrick printf("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"",
1987061da546Spatrick static_cast<unsigned long long>(address),
1988061da546Spatrick static_cast<unsigned long long>(flags),
1989061da546Spatrick static_cast<unsigned long long>(other), name.GetCString());
1990061da546Spatrick if (import_name)
1991061da546Spatrick printf(" -> \"%s\"\n", import_name.GetCString());
1992061da546Spatrick else
1993061da546Spatrick printf("\n");
1994061da546Spatrick }
1995061da546Spatrick ConstString name;
1996061da546Spatrick uint64_t address = LLDB_INVALID_ADDRESS;
1997dda28197Spatrick uint64_t flags =
1998dda28197Spatrick 0; // EXPORT_SYMBOL_FLAGS_REEXPORT, EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER,
1999dda28197Spatrick // TRIE_SYMBOL_IS_THUMB
2000061da546Spatrick uint64_t other = 0;
2001061da546Spatrick ConstString import_name;
2002061da546Spatrick };
2003061da546Spatrick
2004061da546Spatrick struct TrieEntryWithOffset {
2005061da546Spatrick lldb::offset_t nodeOffset;
2006061da546Spatrick TrieEntry entry;
2007061da546Spatrick
TrieEntryWithOffsetTrieEntryWithOffset2008061da546Spatrick TrieEntryWithOffset(lldb::offset_t offset) : nodeOffset(offset), entry() {}
2009061da546Spatrick
DumpTrieEntryWithOffset2010061da546Spatrick void Dump(uint32_t idx) const {
2011061da546Spatrick printf("[%3u] 0x%16.16llx: ", idx,
2012061da546Spatrick static_cast<unsigned long long>(nodeOffset));
2013061da546Spatrick entry.Dump();
2014061da546Spatrick }
2015061da546Spatrick
operator <TrieEntryWithOffset2016061da546Spatrick bool operator<(const TrieEntryWithOffset &other) const {
2017061da546Spatrick return (nodeOffset < other.nodeOffset);
2018061da546Spatrick }
2019061da546Spatrick };
2020061da546Spatrick
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)2021061da546Spatrick static bool ParseTrieEntries(DataExtractor &data, lldb::offset_t offset,
2022dda28197Spatrick const bool is_arm, addr_t text_seg_base_addr,
2023061da546Spatrick std::vector<llvm::StringRef> &nameSlices,
2024061da546Spatrick std::set<lldb::addr_t> &resolver_addresses,
2025dda28197Spatrick std::vector<TrieEntryWithOffset> &reexports,
2026dda28197Spatrick std::vector<TrieEntryWithOffset> &ext_symbols) {
2027061da546Spatrick if (!data.ValidOffset(offset))
2028061da546Spatrick return true;
2029061da546Spatrick
2030dda28197Spatrick // Terminal node -- end of a branch, possibly add this to
2031dda28197Spatrick // the symbol table or resolver table.
2032061da546Spatrick const uint64_t terminalSize = data.GetULEB128(&offset);
2033061da546Spatrick lldb::offset_t children_offset = offset + terminalSize;
2034061da546Spatrick if (terminalSize != 0) {
2035061da546Spatrick TrieEntryWithOffset e(offset);
2036061da546Spatrick e.entry.flags = data.GetULEB128(&offset);
2037061da546Spatrick const char *import_name = nullptr;
2038061da546Spatrick if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
2039061da546Spatrick e.entry.address = 0;
2040061da546Spatrick e.entry.other = data.GetULEB128(&offset); // dylib ordinal
2041061da546Spatrick import_name = data.GetCStr(&offset);
2042061da546Spatrick } else {
2043061da546Spatrick e.entry.address = data.GetULEB128(&offset);
2044dda28197Spatrick if (text_seg_base_addr != LLDB_INVALID_ADDRESS)
2045dda28197Spatrick e.entry.address += text_seg_base_addr;
2046061da546Spatrick if (e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2047061da546Spatrick e.entry.other = data.GetULEB128(&offset);
2048061da546Spatrick uint64_t resolver_addr = e.entry.other;
2049be691f3bSpatrick if (text_seg_base_addr != LLDB_INVALID_ADDRESS)
2050be691f3bSpatrick resolver_addr += text_seg_base_addr;
2051061da546Spatrick if (is_arm)
2052061da546Spatrick resolver_addr &= THUMB_ADDRESS_BIT_MASK;
2053061da546Spatrick resolver_addresses.insert(resolver_addr);
2054061da546Spatrick } else
2055061da546Spatrick e.entry.other = 0;
2056061da546Spatrick }
2057dda28197Spatrick bool add_this_entry = false;
2058dda28197Spatrick if (Flags(e.entry.flags).Test(EXPORT_SYMBOL_FLAGS_REEXPORT) &&
2059dda28197Spatrick import_name && import_name[0]) {
2060dda28197Spatrick // add symbols that are reexport symbols with a valid import name.
2061dda28197Spatrick add_this_entry = true;
2062dda28197Spatrick } else if (e.entry.flags == 0 &&
2063dda28197Spatrick (import_name == nullptr || import_name[0] == '\0')) {
2064dda28197Spatrick // add externally visible symbols, in case the nlist record has
2065dda28197Spatrick // been stripped/omitted.
2066dda28197Spatrick add_this_entry = true;
2067dda28197Spatrick }
2068dda28197Spatrick if (add_this_entry) {
2069061da546Spatrick std::string name;
2070061da546Spatrick if (!nameSlices.empty()) {
2071061da546Spatrick for (auto name_slice : nameSlices)
2072061da546Spatrick name.append(name_slice.data(), name_slice.size());
2073061da546Spatrick }
2074061da546Spatrick if (name.size() > 1) {
2075061da546Spatrick // Skip the leading '_'
2076061da546Spatrick e.entry.name.SetCStringWithLength(name.c_str() + 1, name.size() - 1);
2077061da546Spatrick }
2078061da546Spatrick if (import_name) {
2079061da546Spatrick // Skip the leading '_'
2080061da546Spatrick e.entry.import_name.SetCString(import_name + 1);
2081061da546Spatrick }
2082dda28197Spatrick if (Flags(e.entry.flags).Test(EXPORT_SYMBOL_FLAGS_REEXPORT)) {
2083dda28197Spatrick reexports.push_back(e);
2084dda28197Spatrick } else {
2085dda28197Spatrick if (is_arm && (e.entry.address & 1)) {
2086dda28197Spatrick e.entry.flags |= TRIE_SYMBOL_IS_THUMB;
2087dda28197Spatrick e.entry.address &= THUMB_ADDRESS_BIT_MASK;
2088dda28197Spatrick }
2089dda28197Spatrick ext_symbols.push_back(e);
2090dda28197Spatrick }
2091061da546Spatrick }
2092061da546Spatrick }
2093061da546Spatrick
2094061da546Spatrick const uint8_t childrenCount = data.GetU8(&children_offset);
2095061da546Spatrick for (uint8_t i = 0; i < childrenCount; ++i) {
2096061da546Spatrick const char *cstr = data.GetCStr(&children_offset);
2097061da546Spatrick if (cstr)
2098061da546Spatrick nameSlices.push_back(llvm::StringRef(cstr));
2099061da546Spatrick else
2100061da546Spatrick return false; // Corrupt data
2101061da546Spatrick lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset);
2102061da546Spatrick if (childNodeOffset) {
2103dda28197Spatrick if (!ParseTrieEntries(data, childNodeOffset, is_arm, text_seg_base_addr,
2104dda28197Spatrick nameSlices, resolver_addresses, reexports,
2105dda28197Spatrick ext_symbols)) {
2106061da546Spatrick return false;
2107061da546Spatrick }
2108061da546Spatrick }
2109061da546Spatrick nameSlices.pop_back();
2110061da546Spatrick }
2111061da546Spatrick return true;
2112061da546Spatrick }
2113061da546Spatrick
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)2114dda28197Spatrick static SymbolType GetSymbolType(const char *&symbol_name,
2115dda28197Spatrick bool &demangled_is_synthesized,
2116dda28197Spatrick const SectionSP &text_section_sp,
2117dda28197Spatrick const SectionSP &data_section_sp,
2118dda28197Spatrick const SectionSP &data_dirty_section_sp,
2119dda28197Spatrick const SectionSP &data_const_section_sp,
2120dda28197Spatrick const SectionSP &symbol_section) {
2121dda28197Spatrick SymbolType type = eSymbolTypeInvalid;
2122dda28197Spatrick
2123dda28197Spatrick const char *symbol_sect_name = symbol_section->GetName().AsCString();
2124dda28197Spatrick if (symbol_section->IsDescendant(text_section_sp.get())) {
2125dda28197Spatrick if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
2126dda28197Spatrick S_ATTR_SELF_MODIFYING_CODE |
2127dda28197Spatrick S_ATTR_SOME_INSTRUCTIONS))
2128dda28197Spatrick type = eSymbolTypeData;
2129dda28197Spatrick else
2130dda28197Spatrick type = eSymbolTypeCode;
2131dda28197Spatrick } else if (symbol_section->IsDescendant(data_section_sp.get()) ||
2132dda28197Spatrick symbol_section->IsDescendant(data_dirty_section_sp.get()) ||
2133dda28197Spatrick symbol_section->IsDescendant(data_const_section_sp.get())) {
2134dda28197Spatrick if (symbol_sect_name &&
2135dda28197Spatrick ::strstr(symbol_sect_name, "__objc") == symbol_sect_name) {
2136dda28197Spatrick type = eSymbolTypeRuntime;
2137dda28197Spatrick
2138dda28197Spatrick if (symbol_name) {
2139dda28197Spatrick llvm::StringRef symbol_name_ref(symbol_name);
2140dda28197Spatrick if (symbol_name_ref.startswith("OBJC_")) {
2141dda28197Spatrick static const llvm::StringRef g_objc_v2_prefix_class("OBJC_CLASS_$_");
2142dda28197Spatrick static const llvm::StringRef g_objc_v2_prefix_metaclass(
2143dda28197Spatrick "OBJC_METACLASS_$_");
2144dda28197Spatrick static const llvm::StringRef g_objc_v2_prefix_ivar("OBJC_IVAR_$_");
2145dda28197Spatrick if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
2146dda28197Spatrick symbol_name = symbol_name + g_objc_v2_prefix_class.size();
2147dda28197Spatrick type = eSymbolTypeObjCClass;
2148dda28197Spatrick demangled_is_synthesized = true;
2149dda28197Spatrick } else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass)) {
2150dda28197Spatrick symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
2151dda28197Spatrick type = eSymbolTypeObjCMetaClass;
2152dda28197Spatrick demangled_is_synthesized = true;
2153dda28197Spatrick } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
2154dda28197Spatrick symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
2155dda28197Spatrick type = eSymbolTypeObjCIVar;
2156dda28197Spatrick demangled_is_synthesized = true;
2157dda28197Spatrick }
2158dda28197Spatrick }
2159dda28197Spatrick }
2160dda28197Spatrick } else if (symbol_sect_name &&
2161dda28197Spatrick ::strstr(symbol_sect_name, "__gcc_except_tab") ==
2162dda28197Spatrick symbol_sect_name) {
2163dda28197Spatrick type = eSymbolTypeException;
2164dda28197Spatrick } else {
2165dda28197Spatrick type = eSymbolTypeData;
2166dda28197Spatrick }
2167dda28197Spatrick } else if (symbol_sect_name &&
2168dda28197Spatrick ::strstr(symbol_sect_name, "__IMPORT") == symbol_sect_name) {
2169dda28197Spatrick type = eSymbolTypeTrampoline;
2170dda28197Spatrick }
2171dda28197Spatrick return type;
2172dda28197Spatrick }
2173dda28197Spatrick
2174061da546Spatrick // Read the UUID out of a dyld_shared_cache file on-disk.
GetSharedCacheUUID(FileSpec dyld_shared_cache,const ByteOrder byte_order,const uint32_t addr_byte_size)2175061da546Spatrick UUID ObjectFileMachO::GetSharedCacheUUID(FileSpec dyld_shared_cache,
2176061da546Spatrick const ByteOrder byte_order,
2177061da546Spatrick const uint32_t addr_byte_size) {
2178061da546Spatrick UUID dsc_uuid;
2179061da546Spatrick DataBufferSP DscData = MapFileData(
2180061da546Spatrick dyld_shared_cache, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
2181061da546Spatrick if (!DscData)
2182061da546Spatrick return dsc_uuid;
2183061da546Spatrick DataExtractor dsc_header_data(DscData, byte_order, addr_byte_size);
2184061da546Spatrick
2185061da546Spatrick char version_str[7];
2186061da546Spatrick lldb::offset_t offset = 0;
2187061da546Spatrick memcpy(version_str, dsc_header_data.GetData(&offset, 6), 6);
2188061da546Spatrick version_str[6] = '\0';
2189061da546Spatrick if (strcmp(version_str, "dyld_v") == 0) {
2190061da546Spatrick offset = offsetof(struct lldb_copy_dyld_cache_header_v1, uuid);
2191*f6aab3d8Srobert dsc_uuid =
2192*f6aab3d8Srobert UUID(dsc_header_data.GetData(&offset, sizeof(uuid_t)), sizeof(uuid_t));
2193061da546Spatrick }
2194*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Symbols);
2195061da546Spatrick if (log && dsc_uuid.IsValid()) {
2196061da546Spatrick LLDB_LOGF(log, "Shared cache %s has UUID %s",
2197061da546Spatrick dyld_shared_cache.GetPath().c_str(),
2198061da546Spatrick dsc_uuid.GetAsString().c_str());
2199061da546Spatrick }
2200061da546Spatrick return dsc_uuid;
2201061da546Spatrick }
2202061da546Spatrick
2203*f6aab3d8Srobert static std::optional<struct nlist_64>
ParseNList(DataExtractor & nlist_data,lldb::offset_t & nlist_data_offset,size_t nlist_byte_size)2204061da546Spatrick ParseNList(DataExtractor &nlist_data, lldb::offset_t &nlist_data_offset,
2205061da546Spatrick size_t nlist_byte_size) {
2206061da546Spatrick struct nlist_64 nlist;
2207061da546Spatrick if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size))
2208061da546Spatrick return {};
2209061da546Spatrick nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
2210061da546Spatrick nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
2211061da546Spatrick nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
2212061da546Spatrick nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
2213061da546Spatrick nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
2214061da546Spatrick return nlist;
2215061da546Spatrick }
2216061da546Spatrick
2217061da546Spatrick enum { DebugSymbols = true, NonDebugSymbols = false };
2218061da546Spatrick
ParseSymtab(Symtab & symtab)2219*f6aab3d8Srobert void ObjectFileMachO::ParseSymtab(Symtab &symtab) {
2220061da546Spatrick ModuleSP module_sp(GetModule());
2221061da546Spatrick if (!module_sp)
2222*f6aab3d8Srobert return;
2223061da546Spatrick
2224*f6aab3d8Srobert const FileSpec &file = m_file ? m_file : module_sp->GetFileSpec();
2225*f6aab3d8Srobert const char *file_name = file.GetFilename().AsCString("<Unknown>");
2226*f6aab3d8Srobert LLDB_SCOPED_TIMERF("ObjectFileMachO::ParseSymtab () module = %s", file_name);
2227*f6aab3d8Srobert Progress progress(llvm::formatv("Parsing symbol table for {0}", file_name));
2228be691f3bSpatrick
2229be691f3bSpatrick llvm::MachO::symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
2230be691f3bSpatrick llvm::MachO::linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
2231*f6aab3d8Srobert llvm::MachO::linkedit_data_command exports_trie_load_command = {0, 0, 0, 0};
2232be691f3bSpatrick llvm::MachO::dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2233*f6aab3d8Srobert llvm::MachO::dysymtab_command dysymtab = m_dysymtab;
2234dda28197Spatrick // The data element of type bool indicates that this entry is thumb
2235dda28197Spatrick // code.
2236061da546Spatrick typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2237dda28197Spatrick
2238dda28197Spatrick // Record the address of every function/data that we add to the symtab.
2239dda28197Spatrick // We add symbols to the table in the order of most information (nlist
2240dda28197Spatrick // records) to least (function starts), and avoid duplicating symbols
2241dda28197Spatrick // via this set.
2242be691f3bSpatrick llvm::DenseSet<addr_t> symbols_added;
2243be691f3bSpatrick
2244be691f3bSpatrick // We are using a llvm::DenseSet for "symbols_added" so we must be sure we
2245be691f3bSpatrick // do not add the tombstone or empty keys to the set.
2246be691f3bSpatrick auto add_symbol_addr = [&symbols_added](lldb::addr_t file_addr) {
2247be691f3bSpatrick // Don't add the tombstone or empty keys.
2248be691f3bSpatrick if (file_addr == UINT64_MAX || file_addr == UINT64_MAX - 1)
2249be691f3bSpatrick return;
2250be691f3bSpatrick symbols_added.insert(file_addr);
2251be691f3bSpatrick };
2252061da546Spatrick FunctionStarts function_starts;
2253061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
2254061da546Spatrick uint32_t i;
2255061da546Spatrick FileSpecList dylib_files;
2256*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Symbols);
2257061da546Spatrick llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2258061da546Spatrick llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
2259061da546Spatrick llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2260*f6aab3d8Srobert UUID image_uuid;
2261061da546Spatrick
2262061da546Spatrick for (i = 0; i < m_header.ncmds; ++i) {
2263061da546Spatrick const lldb::offset_t cmd_offset = offset;
2264061da546Spatrick // Read in the load command and load command size
2265be691f3bSpatrick llvm::MachO::load_command lc;
2266061da546Spatrick if (m_data.GetU32(&offset, &lc, 2) == nullptr)
2267061da546Spatrick break;
2268061da546Spatrick // Watch for the symbol table load command
2269061da546Spatrick switch (lc.cmd) {
2270061da546Spatrick case LC_SYMTAB:
2271061da546Spatrick symtab_load_command.cmd = lc.cmd;
2272061da546Spatrick symtab_load_command.cmdsize = lc.cmdsize;
2273061da546Spatrick // Read in the rest of the symtab load command
2274061da546Spatrick if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
2275061da546Spatrick nullptr) // fill in symoff, nsyms, stroff, strsize fields
2276*f6aab3d8Srobert return;
2277061da546Spatrick break;
2278061da546Spatrick
2279061da546Spatrick case LC_DYLD_INFO:
2280061da546Spatrick case LC_DYLD_INFO_ONLY:
2281061da546Spatrick if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
2282061da546Spatrick dyld_info.cmd = lc.cmd;
2283061da546Spatrick dyld_info.cmdsize = lc.cmdsize;
2284061da546Spatrick } else {
2285061da546Spatrick memset(&dyld_info, 0, sizeof(dyld_info));
2286061da546Spatrick }
2287061da546Spatrick break;
2288061da546Spatrick
2289061da546Spatrick case LC_LOAD_DYLIB:
2290061da546Spatrick case LC_LOAD_WEAK_DYLIB:
2291061da546Spatrick case LC_REEXPORT_DYLIB:
2292061da546Spatrick case LC_LOADFVMLIB:
2293061da546Spatrick case LC_LOAD_UPWARD_DYLIB: {
2294061da546Spatrick uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
2295061da546Spatrick const char *path = m_data.PeekCStr(name_offset);
2296061da546Spatrick if (path) {
2297061da546Spatrick FileSpec file_spec(path);
2298061da546Spatrick // Strip the path if there is @rpath, @executable, etc so we just use
2299061da546Spatrick // the basename
2300061da546Spatrick if (path[0] == '@')
2301*f6aab3d8Srobert file_spec.ClearDirectory();
2302061da546Spatrick
2303061da546Spatrick if (lc.cmd == LC_REEXPORT_DYLIB) {
2304061da546Spatrick m_reexported_dylibs.AppendIfUnique(file_spec);
2305061da546Spatrick }
2306061da546Spatrick
2307061da546Spatrick dylib_files.Append(file_spec);
2308061da546Spatrick }
2309061da546Spatrick } break;
2310061da546Spatrick
2311*f6aab3d8Srobert case LC_DYLD_EXPORTS_TRIE:
2312*f6aab3d8Srobert exports_trie_load_command.cmd = lc.cmd;
2313*f6aab3d8Srobert exports_trie_load_command.cmdsize = lc.cmdsize;
2314*f6aab3d8Srobert if (m_data.GetU32(&offset, &exports_trie_load_command.dataoff, 2) ==
2315*f6aab3d8Srobert nullptr) // fill in offset and size fields
2316*f6aab3d8Srobert memset(&exports_trie_load_command, 0,
2317*f6aab3d8Srobert sizeof(exports_trie_load_command));
2318*f6aab3d8Srobert break;
2319061da546Spatrick case LC_FUNCTION_STARTS:
2320061da546Spatrick function_starts_load_command.cmd = lc.cmd;
2321061da546Spatrick function_starts_load_command.cmdsize = lc.cmdsize;
2322061da546Spatrick if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
2323*f6aab3d8Srobert nullptr) // fill in data offset and size fields
2324061da546Spatrick memset(&function_starts_load_command, 0,
2325061da546Spatrick sizeof(function_starts_load_command));
2326061da546Spatrick break;
2327061da546Spatrick
2328*f6aab3d8Srobert case LC_UUID: {
2329*f6aab3d8Srobert const uint8_t *uuid_bytes = m_data.PeekData(offset, 16);
2330*f6aab3d8Srobert
2331*f6aab3d8Srobert if (uuid_bytes)
2332*f6aab3d8Srobert image_uuid = UUID(uuid_bytes, 16);
2333*f6aab3d8Srobert break;
2334*f6aab3d8Srobert }
2335*f6aab3d8Srobert
2336061da546Spatrick default:
2337061da546Spatrick break;
2338061da546Spatrick }
2339061da546Spatrick offset = cmd_offset + lc.cmdsize;
2340061da546Spatrick }
2341061da546Spatrick
2342061da546Spatrick if (!symtab_load_command.cmd)
2343*f6aab3d8Srobert return;
2344061da546Spatrick
2345061da546Spatrick SectionList *section_list = GetSectionList();
2346061da546Spatrick if (section_list == nullptr)
2347*f6aab3d8Srobert return;
2348061da546Spatrick
2349061da546Spatrick const uint32_t addr_byte_size = m_data.GetAddressByteSize();
2350061da546Spatrick const ByteOrder byte_order = m_data.GetByteOrder();
2351061da546Spatrick bool bit_width_32 = addr_byte_size == 4;
2352061da546Spatrick const size_t nlist_byte_size =
2353061da546Spatrick bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2354061da546Spatrick
2355061da546Spatrick DataExtractor nlist_data(nullptr, 0, byte_order, addr_byte_size);
2356061da546Spatrick DataExtractor strtab_data(nullptr, 0, byte_order, addr_byte_size);
2357061da546Spatrick DataExtractor function_starts_data(nullptr, 0, byte_order, addr_byte_size);
2358061da546Spatrick DataExtractor indirect_symbol_index_data(nullptr, 0, byte_order,
2359061da546Spatrick addr_byte_size);
2360061da546Spatrick DataExtractor dyld_trie_data(nullptr, 0, byte_order, addr_byte_size);
2361061da546Spatrick
2362061da546Spatrick const addr_t nlist_data_byte_size =
2363061da546Spatrick symtab_load_command.nsyms * nlist_byte_size;
2364061da546Spatrick const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2365061da546Spatrick addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2366061da546Spatrick
2367061da546Spatrick ProcessSP process_sp(m_process_wp.lock());
2368061da546Spatrick Process *process = process_sp.get();
2369061da546Spatrick
2370061da546Spatrick uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2371*f6aab3d8Srobert bool is_shared_cache_image = IsSharedCacheBinary();
2372be691f3bSpatrick bool is_local_shared_cache_image = is_shared_cache_image && !IsInMemory();
2373be691f3bSpatrick SectionSP linkedit_section_sp(
2374be691f3bSpatrick section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
2375061da546Spatrick
2376be691f3bSpatrick if (process && m_header.filetype != llvm::MachO::MH_OBJECT &&
2377be691f3bSpatrick !is_local_shared_cache_image) {
2378061da546Spatrick Target &target = process->GetTarget();
2379061da546Spatrick
2380061da546Spatrick memory_module_load_level = target.GetMemoryModuleLoadLevel();
2381061da546Spatrick
2382061da546Spatrick // Reading mach file from memory in a process or core file...
2383061da546Spatrick
2384061da546Spatrick if (linkedit_section_sp) {
2385061da546Spatrick addr_t linkedit_load_addr =
2386061da546Spatrick linkedit_section_sp->GetLoadBaseAddress(&target);
2387061da546Spatrick if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2388061da546Spatrick // We might be trying to access the symbol table before the
2389061da546Spatrick // __LINKEDIT's load address has been set in the target. We can't
2390061da546Spatrick // fail to read the symbol table, so calculate the right address
2391061da546Spatrick // manually
2392061da546Spatrick linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2393061da546Spatrick m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2394061da546Spatrick }
2395061da546Spatrick
2396061da546Spatrick const addr_t linkedit_file_offset = linkedit_section_sp->GetFileOffset();
2397061da546Spatrick const addr_t symoff_addr = linkedit_load_addr +
2398061da546Spatrick symtab_load_command.symoff -
2399061da546Spatrick linkedit_file_offset;
2400061da546Spatrick strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2401061da546Spatrick linkedit_file_offset;
2402061da546Spatrick
2403061da546Spatrick // Always load dyld - the dynamic linker - from memory if we didn't
2404061da546Spatrick // find a binary anywhere else. lldb will not register
2405061da546Spatrick // dylib/framework/bundle loads/unloads if we don't have the dyld
2406061da546Spatrick // symbols, we force dyld to load from memory despite the user's
2407061da546Spatrick // target.memory-module-load-level setting.
2408061da546Spatrick if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2409061da546Spatrick m_header.filetype == llvm::MachO::MH_DYLINKER) {
2410061da546Spatrick DataBufferSP nlist_data_sp(
2411061da546Spatrick ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
2412061da546Spatrick if (nlist_data_sp)
2413061da546Spatrick nlist_data.SetData(nlist_data_sp, 0, nlist_data_sp->GetByteSize());
2414*f6aab3d8Srobert if (dysymtab.nindirectsyms != 0) {
2415061da546Spatrick const addr_t indirect_syms_addr = linkedit_load_addr +
2416*f6aab3d8Srobert dysymtab.indirectsymoff -
2417061da546Spatrick linkedit_file_offset;
2418061da546Spatrick DataBufferSP indirect_syms_data_sp(ReadMemory(
2419*f6aab3d8Srobert process_sp, indirect_syms_addr, dysymtab.nindirectsyms * 4));
2420061da546Spatrick if (indirect_syms_data_sp)
2421061da546Spatrick indirect_symbol_index_data.SetData(
2422061da546Spatrick indirect_syms_data_sp, 0,
2423061da546Spatrick indirect_syms_data_sp->GetByteSize());
2424061da546Spatrick // If this binary is outside the shared cache,
2425061da546Spatrick // cache the string table.
2426061da546Spatrick // Binaries in the shared cache all share a giant string table,
2427061da546Spatrick // and we can't share the string tables across multiple
2428061da546Spatrick // ObjectFileMachO's, so we'd end up re-reading this mega-strtab
2429061da546Spatrick // for every binary in the shared cache - it would be a big perf
2430061da546Spatrick // problem. For binaries outside the shared cache, it's faster to
2431061da546Spatrick // read the entire strtab at once instead of piece-by-piece as we
2432061da546Spatrick // process the nlist records.
2433be691f3bSpatrick if (!is_shared_cache_image) {
2434061da546Spatrick DataBufferSP strtab_data_sp(
2435061da546Spatrick ReadMemory(process_sp, strtab_addr, strtab_data_byte_size));
2436061da546Spatrick if (strtab_data_sp) {
2437061da546Spatrick strtab_data.SetData(strtab_data_sp, 0,
2438061da546Spatrick strtab_data_sp->GetByteSize());
2439061da546Spatrick }
2440061da546Spatrick }
2441061da546Spatrick }
2442061da546Spatrick if (memory_module_load_level >= eMemoryModuleLoadLevelPartial) {
2443061da546Spatrick if (function_starts_load_command.cmd) {
2444061da546Spatrick const addr_t func_start_addr =
2445061da546Spatrick linkedit_load_addr + function_starts_load_command.dataoff -
2446061da546Spatrick linkedit_file_offset;
2447061da546Spatrick DataBufferSP func_start_data_sp(
2448061da546Spatrick ReadMemory(process_sp, func_start_addr,
2449061da546Spatrick function_starts_load_command.datasize));
2450061da546Spatrick if (func_start_data_sp)
2451061da546Spatrick function_starts_data.SetData(func_start_data_sp, 0,
2452061da546Spatrick func_start_data_sp->GetByteSize());
2453061da546Spatrick }
2454061da546Spatrick }
2455061da546Spatrick }
2456061da546Spatrick }
2457061da546Spatrick } else {
2458be691f3bSpatrick if (is_local_shared_cache_image) {
2459be691f3bSpatrick // The load commands in shared cache images are relative to the
2460be691f3bSpatrick // beginning of the shared cache, not the library image. The
2461be691f3bSpatrick // data we get handed when creating the ObjectFileMachO starts
2462be691f3bSpatrick // at the beginning of a specific library and spans to the end
2463be691f3bSpatrick // of the cache to be able to reach the shared LINKEDIT
2464be691f3bSpatrick // segments. We need to convert the load command offsets to be
2465be691f3bSpatrick // relative to the beginning of our specific image.
2466be691f3bSpatrick lldb::addr_t linkedit_offset = linkedit_section_sp->GetFileOffset();
2467be691f3bSpatrick lldb::offset_t linkedit_slide =
2468be691f3bSpatrick linkedit_offset - m_linkedit_original_offset;
2469be691f3bSpatrick symtab_load_command.symoff += linkedit_slide;
2470be691f3bSpatrick symtab_load_command.stroff += linkedit_slide;
2471be691f3bSpatrick dyld_info.export_off += linkedit_slide;
2472*f6aab3d8Srobert dysymtab.indirectsymoff += linkedit_slide;
2473be691f3bSpatrick function_starts_load_command.dataoff += linkedit_slide;
2474*f6aab3d8Srobert exports_trie_load_command.dataoff += linkedit_slide;
2475be691f3bSpatrick }
2476be691f3bSpatrick
2477061da546Spatrick nlist_data.SetData(m_data, symtab_load_command.symoff,
2478061da546Spatrick nlist_data_byte_size);
2479061da546Spatrick strtab_data.SetData(m_data, symtab_load_command.stroff,
2480061da546Spatrick strtab_data_byte_size);
2481061da546Spatrick
2482*f6aab3d8Srobert // We shouldn't have exports data from both the LC_DYLD_INFO command
2483*f6aab3d8Srobert // AND the LC_DYLD_EXPORTS_TRIE command in the same binary:
2484*f6aab3d8Srobert lldbassert(!((dyld_info.export_size > 0)
2485*f6aab3d8Srobert && (exports_trie_load_command.datasize > 0)));
2486061da546Spatrick if (dyld_info.export_size > 0) {
2487061da546Spatrick dyld_trie_data.SetData(m_data, dyld_info.export_off,
2488061da546Spatrick dyld_info.export_size);
2489*f6aab3d8Srobert } else if (exports_trie_load_command.datasize > 0) {
2490*f6aab3d8Srobert dyld_trie_data.SetData(m_data, exports_trie_load_command.dataoff,
2491*f6aab3d8Srobert exports_trie_load_command.datasize);
2492061da546Spatrick }
2493061da546Spatrick
2494*f6aab3d8Srobert if (dysymtab.nindirectsyms != 0) {
2495*f6aab3d8Srobert indirect_symbol_index_data.SetData(m_data, dysymtab.indirectsymoff,
2496*f6aab3d8Srobert dysymtab.nindirectsyms * 4);
2497061da546Spatrick }
2498061da546Spatrick if (function_starts_load_command.cmd) {
2499061da546Spatrick function_starts_data.SetData(m_data, function_starts_load_command.dataoff,
2500061da546Spatrick function_starts_load_command.datasize);
2501061da546Spatrick }
2502061da546Spatrick }
2503061da546Spatrick
2504061da546Spatrick const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2505061da546Spatrick
2506061da546Spatrick ConstString g_segment_name_TEXT = GetSegmentNameTEXT();
2507061da546Spatrick ConstString g_segment_name_DATA = GetSegmentNameDATA();
2508061da546Spatrick ConstString g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
2509061da546Spatrick ConstString g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
2510061da546Spatrick ConstString g_segment_name_OBJC = GetSegmentNameOBJC();
2511061da546Spatrick ConstString g_section_name_eh_frame = GetSectionNameEHFrame();
2512061da546Spatrick SectionSP text_section_sp(
2513061da546Spatrick section_list->FindSectionByName(g_segment_name_TEXT));
2514061da546Spatrick SectionSP data_section_sp(
2515061da546Spatrick section_list->FindSectionByName(g_segment_name_DATA));
2516061da546Spatrick SectionSP data_dirty_section_sp(
2517061da546Spatrick section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
2518061da546Spatrick SectionSP data_const_section_sp(
2519061da546Spatrick section_list->FindSectionByName(g_segment_name_DATA_CONST));
2520061da546Spatrick SectionSP objc_section_sp(
2521061da546Spatrick section_list->FindSectionByName(g_segment_name_OBJC));
2522061da546Spatrick SectionSP eh_frame_section_sp;
2523061da546Spatrick if (text_section_sp.get())
2524061da546Spatrick eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2525061da546Spatrick g_section_name_eh_frame);
2526061da546Spatrick else
2527061da546Spatrick eh_frame_section_sp =
2528061da546Spatrick section_list->FindSectionByName(g_section_name_eh_frame);
2529061da546Spatrick
2530061da546Spatrick const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
2531dda28197Spatrick const bool always_thumb = GetArchitecture().IsAlwaysThumbInstructions();
2532061da546Spatrick
2533061da546Spatrick // lldb works best if it knows the start address of all functions in a
2534061da546Spatrick // module. Linker symbols or debug info are normally the best source of
2535061da546Spatrick // information for start addr / size but they may be stripped in a released
2536061da546Spatrick // binary. Two additional sources of information exist in Mach-O binaries:
2537061da546Spatrick // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2538061da546Spatrick // function's start address in the
2539061da546Spatrick // binary, relative to the text section.
2540061da546Spatrick // eh_frame - the eh_frame FDEs have the start addr & size of
2541061da546Spatrick // each function
2542061da546Spatrick // LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2543061da546Spatrick // all modern binaries.
2544061da546Spatrick // Binaries built to run on older releases may need to use eh_frame
2545061da546Spatrick // information.
2546061da546Spatrick
2547061da546Spatrick if (text_section_sp && function_starts_data.GetByteSize()) {
2548061da546Spatrick FunctionStarts::Entry function_start_entry;
2549061da546Spatrick function_start_entry.data = false;
2550061da546Spatrick lldb::offset_t function_start_offset = 0;
2551061da546Spatrick function_start_entry.addr = text_section_sp->GetFileAddress();
2552061da546Spatrick uint64_t delta;
2553061da546Spatrick while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
2554061da546Spatrick 0) {
2555061da546Spatrick // Now append the current entry
2556061da546Spatrick function_start_entry.addr += delta;
2557dda28197Spatrick if (is_arm) {
2558dda28197Spatrick if (function_start_entry.addr & 1) {
2559dda28197Spatrick function_start_entry.addr &= THUMB_ADDRESS_BIT_MASK;
2560dda28197Spatrick function_start_entry.data = true;
2561dda28197Spatrick } else if (always_thumb) {
2562dda28197Spatrick function_start_entry.data = true;
2563dda28197Spatrick }
2564dda28197Spatrick }
2565061da546Spatrick function_starts.Append(function_start_entry);
2566061da546Spatrick }
2567061da546Spatrick } else {
2568061da546Spatrick // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
2569061da546Spatrick // load command claiming an eh_frame but it doesn't actually have the
2570061da546Spatrick // eh_frame content. And if we have a dSYM, we don't need to do any of
2571061da546Spatrick // this fill-in-the-missing-symbols works anyway - the debug info should
2572061da546Spatrick // give us all the functions in the module.
2573061da546Spatrick if (text_section_sp.get() && eh_frame_section_sp.get() &&
2574061da546Spatrick m_type != eTypeDebugInfo) {
2575061da546Spatrick DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
2576061da546Spatrick DWARFCallFrameInfo::EH);
2577061da546Spatrick DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2578061da546Spatrick eh_frame.GetFunctionAddressAndSizeVector(functions);
2579061da546Spatrick addr_t text_base_addr = text_section_sp->GetFileAddress();
2580061da546Spatrick size_t count = functions.GetSize();
2581061da546Spatrick for (size_t i = 0; i < count; ++i) {
2582061da546Spatrick const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
2583061da546Spatrick functions.GetEntryAtIndex(i);
2584061da546Spatrick if (func) {
2585061da546Spatrick FunctionStarts::Entry function_start_entry;
2586061da546Spatrick function_start_entry.addr = func->base - text_base_addr;
2587dda28197Spatrick if (is_arm) {
2588dda28197Spatrick if (function_start_entry.addr & 1) {
2589dda28197Spatrick function_start_entry.addr &= THUMB_ADDRESS_BIT_MASK;
2590dda28197Spatrick function_start_entry.data = true;
2591dda28197Spatrick } else if (always_thumb) {
2592dda28197Spatrick function_start_entry.data = true;
2593dda28197Spatrick }
2594dda28197Spatrick }
2595061da546Spatrick function_starts.Append(function_start_entry);
2596061da546Spatrick }
2597061da546Spatrick }
2598061da546Spatrick }
2599061da546Spatrick }
2600061da546Spatrick
2601061da546Spatrick const size_t function_starts_count = function_starts.GetSize();
2602061da546Spatrick
2603061da546Spatrick // For user process binaries (executables, dylibs, frameworks, bundles), if
2604061da546Spatrick // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
2605061da546Spatrick // going to assume the binary has been stripped. Don't allow assembly
2606061da546Spatrick // language instruction emulation because we don't know proper function
2607061da546Spatrick // start boundaries.
2608061da546Spatrick //
2609061da546Spatrick // For all other types of binaries (kernels, stand-alone bare board
2610061da546Spatrick // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
2611061da546Spatrick // sections - we should not make any assumptions about them based on that.
2612061da546Spatrick if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2613061da546Spatrick m_allow_assembly_emulation_unwind_plans = false;
2614*f6aab3d8Srobert Log *unwind_or_symbol_log(GetLog(LLDBLog::Symbols | LLDBLog::Unwind));
2615061da546Spatrick
2616061da546Spatrick if (unwind_or_symbol_log)
2617061da546Spatrick module_sp->LogMessage(
2618061da546Spatrick unwind_or_symbol_log,
2619061da546Spatrick "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2620061da546Spatrick }
2621061da546Spatrick
2622061da546Spatrick const user_id_t TEXT_eh_frame_sectID = eh_frame_section_sp.get()
2623061da546Spatrick ? eh_frame_section_sp->GetID()
2624061da546Spatrick : static_cast<user_id_t>(NO_SECT);
2625061da546Spatrick
2626061da546Spatrick uint32_t N_SO_index = UINT32_MAX;
2627061da546Spatrick
2628061da546Spatrick MachSymtabSectionInfo section_info(section_list);
2629061da546Spatrick std::vector<uint32_t> N_FUN_indexes;
2630061da546Spatrick std::vector<uint32_t> N_NSYM_indexes;
2631061da546Spatrick std::vector<uint32_t> N_INCL_indexes;
2632061da546Spatrick std::vector<uint32_t> N_BRAC_indexes;
2633061da546Spatrick std::vector<uint32_t> N_COMM_indexes;
2634061da546Spatrick typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2635061da546Spatrick typedef llvm::DenseMap<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2636061da546Spatrick typedef llvm::DenseMap<const char *, uint32_t> ConstNameToSymbolIndexMap;
2637061da546Spatrick ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2638061da546Spatrick ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2639061da546Spatrick ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
2640061da546Spatrick // Any symbols that get merged into another will get an entry in this map
2641061da546Spatrick // so we know
2642061da546Spatrick NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2643061da546Spatrick uint32_t nlist_idx = 0;
2644061da546Spatrick Symbol *symbol_ptr = nullptr;
2645061da546Spatrick
2646061da546Spatrick uint32_t sym_idx = 0;
2647061da546Spatrick Symbol *sym = nullptr;
2648061da546Spatrick size_t num_syms = 0;
2649061da546Spatrick std::string memory_symbol_name;
2650061da546Spatrick uint32_t unmapped_local_symbols_found = 0;
2651061da546Spatrick
2652dda28197Spatrick std::vector<TrieEntryWithOffset> reexport_trie_entries;
2653dda28197Spatrick std::vector<TrieEntryWithOffset> external_sym_trie_entries;
2654061da546Spatrick std::set<lldb::addr_t> resolver_addresses;
2655061da546Spatrick
2656061da546Spatrick if (dyld_trie_data.GetByteSize() > 0) {
2657061da546Spatrick ConstString text_segment_name("__TEXT");
2658061da546Spatrick SectionSP text_segment_sp =
2659061da546Spatrick GetSectionList()->FindSectionByName(text_segment_name);
2660dda28197Spatrick lldb::addr_t text_segment_file_addr = LLDB_INVALID_ADDRESS;
2661dda28197Spatrick if (text_segment_sp)
2662dda28197Spatrick text_segment_file_addr = text_segment_sp->GetFileAddress();
2663dda28197Spatrick std::vector<llvm::StringRef> nameSlices;
2664dda28197Spatrick ParseTrieEntries(dyld_trie_data, 0, is_arm, text_segment_file_addr,
2665dda28197Spatrick nameSlices, resolver_addresses, reexport_trie_entries,
2666dda28197Spatrick external_sym_trie_entries);
2667061da546Spatrick }
2668061da546Spatrick
2669061da546Spatrick typedef std::set<ConstString> IndirectSymbols;
2670061da546Spatrick IndirectSymbols indirect_symbol_names;
2671061da546Spatrick
2672be691f3bSpatrick #if TARGET_OS_IPHONE
2673061da546Spatrick
2674061da546Spatrick // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
2675061da546Spatrick // optimized by moving LOCAL symbols out of the memory mapped portion of
2676061da546Spatrick // the DSC. The symbol information has all been retained, but it isn't
2677061da546Spatrick // available in the normal nlist data. However, there *are* duplicate
2678061da546Spatrick // entries of *some*
2679061da546Spatrick // LOCAL symbols in the normal nlist data. To handle this situation
2680061da546Spatrick // correctly, we must first attempt
2681061da546Spatrick // to parse any DSC unmapped symbol information. If we find any, we set a
2682061da546Spatrick // flag that tells the normal nlist parser to ignore all LOCAL symbols.
2683061da546Spatrick
2684*f6aab3d8Srobert if (IsSharedCacheBinary()) {
2685061da546Spatrick // Before we can start mapping the DSC, we need to make certain the
2686061da546Spatrick // target process is actually using the cache we can find.
2687061da546Spatrick
2688061da546Spatrick // Next we need to determine the correct path for the dyld shared cache.
2689061da546Spatrick
2690061da546Spatrick ArchSpec header_arch = GetArchitecture();
2691061da546Spatrick
2692061da546Spatrick UUID dsc_uuid;
2693061da546Spatrick UUID process_shared_cache_uuid;
2694061da546Spatrick addr_t process_shared_cache_base_addr;
2695061da546Spatrick
2696061da546Spatrick if (process) {
2697061da546Spatrick GetProcessSharedCacheUUID(process, process_shared_cache_base_addr,
2698061da546Spatrick process_shared_cache_uuid);
2699061da546Spatrick }
2700061da546Spatrick
2701*f6aab3d8Srobert __block bool found_image = false;
2702*f6aab3d8Srobert __block void *nlist_buffer = nullptr;
2703*f6aab3d8Srobert __block unsigned nlist_count = 0;
2704*f6aab3d8Srobert __block char *string_table = nullptr;
2705*f6aab3d8Srobert __block vm_offset_t vm_nlist_memory = 0;
2706*f6aab3d8Srobert __block mach_msg_type_number_t vm_nlist_bytes_read = 0;
2707*f6aab3d8Srobert __block vm_offset_t vm_string_memory = 0;
2708*f6aab3d8Srobert __block mach_msg_type_number_t vm_string_bytes_read = 0;
2709061da546Spatrick
2710*f6aab3d8Srobert auto _ = llvm::make_scope_exit(^{
2711*f6aab3d8Srobert if (vm_nlist_memory)
2712*f6aab3d8Srobert vm_deallocate(mach_task_self(), vm_nlist_memory, vm_nlist_bytes_read);
2713*f6aab3d8Srobert if (vm_string_memory)
2714*f6aab3d8Srobert vm_deallocate(mach_task_self(), vm_string_memory, vm_string_bytes_read);
2715*f6aab3d8Srobert });
2716061da546Spatrick
2717061da546Spatrick typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
2718061da546Spatrick typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
2719061da546Spatrick UndefinedNameToDescMap undefined_name_to_desc;
2720061da546Spatrick SymbolIndexToName reexport_shlib_needs_fixup;
2721061da546Spatrick
2722*f6aab3d8Srobert dyld_for_each_installed_shared_cache(^(dyld_shared_cache_t shared_cache) {
2723*f6aab3d8Srobert uuid_t cache_uuid;
2724*f6aab3d8Srobert dyld_shared_cache_copy_uuid(shared_cache, &cache_uuid);
2725*f6aab3d8Srobert if (found_image)
2726*f6aab3d8Srobert return;
2727061da546Spatrick
2728*f6aab3d8Srobert if (process_shared_cache_uuid.IsValid() &&
2729*f6aab3d8Srobert process_shared_cache_uuid != UUID::fromData(&cache_uuid, 16))
2730*f6aab3d8Srobert return;
2731061da546Spatrick
2732*f6aab3d8Srobert dyld_shared_cache_for_each_image(shared_cache, ^(dyld_image_t image) {
2733*f6aab3d8Srobert uuid_t dsc_image_uuid;
2734*f6aab3d8Srobert if (found_image)
2735*f6aab3d8Srobert return;
2736061da546Spatrick
2737*f6aab3d8Srobert dyld_image_copy_uuid(image, &dsc_image_uuid);
2738*f6aab3d8Srobert if (image_uuid != UUID::fromData(dsc_image_uuid, 16))
2739*f6aab3d8Srobert return;
2740061da546Spatrick
2741*f6aab3d8Srobert found_image = true;
2742*f6aab3d8Srobert
2743*f6aab3d8Srobert // Compute the size of the string table. We need to ask dyld for a
2744*f6aab3d8Srobert // new SPI to avoid this step.
2745*f6aab3d8Srobert dyld_image_local_nlist_content_4Symbolication(
2746*f6aab3d8Srobert image, ^(const void *nlistStart, uint64_t nlistCount,
2747*f6aab3d8Srobert const char *stringTable) {
2748*f6aab3d8Srobert if (!nlistStart || !nlistCount)
2749*f6aab3d8Srobert return;
2750*f6aab3d8Srobert
2751*f6aab3d8Srobert // The buffers passed here are valid only inside the block.
2752*f6aab3d8Srobert // Use vm_read to make a cheap copy of them available for our
2753*f6aab3d8Srobert // processing later.
2754*f6aab3d8Srobert kern_return_t ret =
2755*f6aab3d8Srobert vm_read(mach_task_self(), (vm_address_t)nlistStart,
2756*f6aab3d8Srobert nlist_byte_size * nlistCount, &vm_nlist_memory,
2757*f6aab3d8Srobert &vm_nlist_bytes_read);
2758*f6aab3d8Srobert if (ret != KERN_SUCCESS)
2759*f6aab3d8Srobert return;
2760*f6aab3d8Srobert assert(vm_nlist_bytes_read == nlist_byte_size * nlistCount);
2761*f6aab3d8Srobert
2762*f6aab3d8Srobert // We don't know the size of the string table. It's cheaper
2763*f6aab3d8Srobert // to map the whol VM region than to determine the size by
2764*f6aab3d8Srobert // parsing all teh nlist entries.
2765*f6aab3d8Srobert vm_address_t string_address = (vm_address_t)stringTable;
2766*f6aab3d8Srobert vm_size_t region_size;
2767*f6aab3d8Srobert mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT_64;
2768*f6aab3d8Srobert vm_region_basic_info_data_t info;
2769*f6aab3d8Srobert memory_object_name_t object;
2770*f6aab3d8Srobert ret = vm_region_64(mach_task_self(), &string_address,
2771*f6aab3d8Srobert ®ion_size, VM_REGION_BASIC_INFO_64,
2772*f6aab3d8Srobert (vm_region_info_t)&info, &info_count, &object);
2773*f6aab3d8Srobert if (ret != KERN_SUCCESS)
2774*f6aab3d8Srobert return;
2775*f6aab3d8Srobert
2776*f6aab3d8Srobert ret = vm_read(mach_task_self(), (vm_address_t)stringTable,
2777*f6aab3d8Srobert region_size -
2778*f6aab3d8Srobert ((vm_address_t)stringTable - string_address),
2779*f6aab3d8Srobert &vm_string_memory, &vm_string_bytes_read);
2780*f6aab3d8Srobert if (ret != KERN_SUCCESS)
2781*f6aab3d8Srobert return;
2782*f6aab3d8Srobert
2783*f6aab3d8Srobert nlist_buffer = (void *)vm_nlist_memory;
2784*f6aab3d8Srobert string_table = (char *)vm_string_memory;
2785*f6aab3d8Srobert nlist_count = nlistCount;
2786*f6aab3d8Srobert });
2787*f6aab3d8Srobert });
2788*f6aab3d8Srobert });
2789*f6aab3d8Srobert if (nlist_buffer) {
2790*f6aab3d8Srobert DataExtractor dsc_local_symbols_data(nlist_buffer,
2791*f6aab3d8Srobert nlist_count * nlist_byte_size,
2792*f6aab3d8Srobert byte_order, addr_byte_size);
2793*f6aab3d8Srobert unmapped_local_symbols_found = nlist_count;
2794061da546Spatrick
2795061da546Spatrick // The normal nlist code cannot correctly size the Symbols
2796061da546Spatrick // array, we need to allocate it here.
2797*f6aab3d8Srobert sym = symtab.Resize(
2798061da546Spatrick symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2799061da546Spatrick unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2800*f6aab3d8Srobert num_syms = symtab.GetNumSymbols();
2801061da546Spatrick
2802*f6aab3d8Srobert lldb::offset_t nlist_data_offset = 0;
2803061da546Spatrick
2804061da546Spatrick for (uint32_t nlist_index = 0;
2805*f6aab3d8Srobert nlist_index < nlist_count;
2806061da546Spatrick nlist_index++) {
2807061da546Spatrick /////////////////////////////
2808061da546Spatrick {
2809*f6aab3d8Srobert std::optional<struct nlist_64> nlist_maybe =
2810061da546Spatrick ParseNList(dsc_local_symbols_data, nlist_data_offset,
2811061da546Spatrick nlist_byte_size);
2812061da546Spatrick if (!nlist_maybe)
2813061da546Spatrick break;
2814061da546Spatrick struct nlist_64 nlist = *nlist_maybe;
2815061da546Spatrick
2816061da546Spatrick SymbolType type = eSymbolTypeInvalid;
2817*f6aab3d8Srobert const char *symbol_name = string_table + nlist.n_strx;
2818061da546Spatrick
2819061da546Spatrick if (symbol_name == NULL) {
2820061da546Spatrick // No symbol should be NULL, even the symbols with no
2821061da546Spatrick // string values should have an offset zero which
2822061da546Spatrick // points to an empty C-string
2823*f6aab3d8Srobert Debugger::ReportError(llvm::formatv(
2824*f6aab3d8Srobert "DSC unmapped local symbol[{0}] has invalid "
2825*f6aab3d8Srobert "string table offset {1:x} in {2}, ignoring symbol",
2826*f6aab3d8Srobert nlist_index, nlist.n_strx,
2827*f6aab3d8Srobert module_sp->GetFileSpec().GetPath());
2828061da546Spatrick continue;
2829061da546Spatrick }
2830061da546Spatrick if (symbol_name[0] == '\0')
2831061da546Spatrick symbol_name = NULL;
2832061da546Spatrick
2833061da546Spatrick const char *symbol_name_non_abi_mangled = NULL;
2834061da546Spatrick
2835061da546Spatrick SectionSP symbol_section;
2836061da546Spatrick uint32_t symbol_byte_size = 0;
2837061da546Spatrick bool add_nlist = true;
2838061da546Spatrick bool is_debug = ((nlist.n_type & N_STAB) != 0);
2839061da546Spatrick bool demangled_is_synthesized = false;
2840061da546Spatrick bool is_gsym = false;
2841061da546Spatrick bool set_value = true;
2842061da546Spatrick
2843061da546Spatrick assert(sym_idx < num_syms);
2844061da546Spatrick
2845061da546Spatrick sym[sym_idx].SetDebug(is_debug);
2846061da546Spatrick
2847061da546Spatrick if (is_debug) {
2848061da546Spatrick switch (nlist.n_type) {
2849061da546Spatrick case N_GSYM:
2850061da546Spatrick // global symbol: name,,NO_SECT,type,0
2851061da546Spatrick // Sometimes the N_GSYM value contains the address.
2852061da546Spatrick
2853061da546Spatrick // FIXME: In the .o files, we have a GSYM and a debug
2854061da546Spatrick // symbol for all the ObjC data. They
2855061da546Spatrick // have the same address, but we want to ensure that
2856061da546Spatrick // we always find only the real symbol, 'cause we
2857061da546Spatrick // don't currently correctly attribute the
2858061da546Spatrick // GSYM one to the ObjCClass/Ivar/MetaClass
2859061da546Spatrick // symbol type. This is a temporary hack to make
2860061da546Spatrick // sure the ObjectiveC symbols get treated correctly.
2861061da546Spatrick // To do this right, we should coalesce all the GSYM
2862061da546Spatrick // & global symbols that have the same address.
2863061da546Spatrick
2864061da546Spatrick is_gsym = true;
2865061da546Spatrick sym[sym_idx].SetExternal(true);
2866061da546Spatrick
2867061da546Spatrick if (symbol_name && symbol_name[0] == '_' &&
2868061da546Spatrick symbol_name[1] == 'O') {
2869061da546Spatrick llvm::StringRef symbol_name_ref(symbol_name);
2870061da546Spatrick if (symbol_name_ref.startswith(
2871061da546Spatrick g_objc_v2_prefix_class)) {
2872061da546Spatrick symbol_name_non_abi_mangled = symbol_name + 1;
2873061da546Spatrick symbol_name =
2874061da546Spatrick symbol_name + g_objc_v2_prefix_class.size();
2875061da546Spatrick type = eSymbolTypeObjCClass;
2876061da546Spatrick demangled_is_synthesized = true;
2877061da546Spatrick
2878061da546Spatrick } else if (symbol_name_ref.startswith(
2879061da546Spatrick g_objc_v2_prefix_metaclass)) {
2880061da546Spatrick symbol_name_non_abi_mangled = symbol_name + 1;
2881061da546Spatrick symbol_name =
2882061da546Spatrick symbol_name + g_objc_v2_prefix_metaclass.size();
2883061da546Spatrick type = eSymbolTypeObjCMetaClass;
2884061da546Spatrick demangled_is_synthesized = true;
2885061da546Spatrick } else if (symbol_name_ref.startswith(
2886061da546Spatrick g_objc_v2_prefix_ivar)) {
2887061da546Spatrick symbol_name_non_abi_mangled = symbol_name + 1;
2888061da546Spatrick symbol_name =
2889061da546Spatrick symbol_name + g_objc_v2_prefix_ivar.size();
2890061da546Spatrick type = eSymbolTypeObjCIVar;
2891061da546Spatrick demangled_is_synthesized = true;
2892061da546Spatrick }
2893061da546Spatrick } else {
2894061da546Spatrick if (nlist.n_value != 0)
2895061da546Spatrick symbol_section = section_info.GetSection(
2896061da546Spatrick nlist.n_sect, nlist.n_value);
2897061da546Spatrick type = eSymbolTypeData;
2898061da546Spatrick }
2899061da546Spatrick break;
2900061da546Spatrick
2901061da546Spatrick case N_FNAME:
2902061da546Spatrick // procedure name (f77 kludge): name,,NO_SECT,0,0
2903061da546Spatrick type = eSymbolTypeCompiler;
2904061da546Spatrick break;
2905061da546Spatrick
2906061da546Spatrick case N_FUN:
2907061da546Spatrick // procedure: name,,n_sect,linenumber,address
2908061da546Spatrick if (symbol_name) {
2909061da546Spatrick type = eSymbolTypeCode;
2910061da546Spatrick symbol_section = section_info.GetSection(
2911061da546Spatrick nlist.n_sect, nlist.n_value);
2912061da546Spatrick
2913061da546Spatrick N_FUN_addr_to_sym_idx.insert(
2914061da546Spatrick std::make_pair(nlist.n_value, sym_idx));
2915061da546Spatrick // We use the current number of symbols in the
2916061da546Spatrick // symbol table in lieu of using nlist_idx in case
2917061da546Spatrick // we ever start trimming entries out
2918061da546Spatrick N_FUN_indexes.push_back(sym_idx);
2919061da546Spatrick } else {
2920061da546Spatrick type = eSymbolTypeCompiler;
2921061da546Spatrick
2922061da546Spatrick if (!N_FUN_indexes.empty()) {
2923061da546Spatrick // Copy the size of the function into the
2924061da546Spatrick // original
2925061da546Spatrick // STAB entry so we don't have
2926061da546Spatrick // to hunt for it later
2927*f6aab3d8Srobert symtab.SymbolAtIndex(N_FUN_indexes.back())
2928061da546Spatrick ->SetByteSize(nlist.n_value);
2929061da546Spatrick N_FUN_indexes.pop_back();
2930061da546Spatrick // We don't really need the end function STAB as
2931061da546Spatrick // it contains the size which we already placed
2932061da546Spatrick // with the original symbol, so don't add it if
2933061da546Spatrick // we want a minimal symbol table
2934061da546Spatrick add_nlist = false;
2935061da546Spatrick }
2936061da546Spatrick }
2937061da546Spatrick break;
2938061da546Spatrick
2939061da546Spatrick case N_STSYM:
2940061da546Spatrick // static symbol: name,,n_sect,type,address
2941061da546Spatrick N_STSYM_addr_to_sym_idx.insert(
2942061da546Spatrick std::make_pair(nlist.n_value, sym_idx));
2943061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect,
2944061da546Spatrick nlist.n_value);
2945061da546Spatrick if (symbol_name && symbol_name[0]) {
2946061da546Spatrick type = ObjectFile::GetSymbolTypeFromName(
2947061da546Spatrick symbol_name + 1, eSymbolTypeData);
2948061da546Spatrick }
2949061da546Spatrick break;
2950061da546Spatrick
2951061da546Spatrick case N_LCSYM:
2952061da546Spatrick // .lcomm symbol: name,,n_sect,type,address
2953061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect,
2954061da546Spatrick nlist.n_value);
2955061da546Spatrick type = eSymbolTypeCommonBlock;
2956061da546Spatrick break;
2957061da546Spatrick
2958061da546Spatrick case N_BNSYM:
2959061da546Spatrick // We use the current number of symbols in the symbol
2960061da546Spatrick // table in lieu of using nlist_idx in case we ever
2961061da546Spatrick // start trimming entries out Skip these if we want
2962061da546Spatrick // minimal symbol tables
2963061da546Spatrick add_nlist = false;
2964061da546Spatrick break;
2965061da546Spatrick
2966061da546Spatrick case N_ENSYM:
2967061da546Spatrick // Set the size of the N_BNSYM to the terminating
2968061da546Spatrick // index of this N_ENSYM so that we can always skip
2969061da546Spatrick // the entire symbol if we need to navigate more
2970061da546Spatrick // quickly at the source level when parsing STABS
2971061da546Spatrick // Skip these if we want minimal symbol tables
2972061da546Spatrick add_nlist = false;
2973061da546Spatrick break;
2974061da546Spatrick
2975061da546Spatrick case N_OPT:
2976061da546Spatrick // emitted with gcc2_compiled and in gcc source
2977061da546Spatrick type = eSymbolTypeCompiler;
2978061da546Spatrick break;
2979061da546Spatrick
2980061da546Spatrick case N_RSYM:
2981061da546Spatrick // register sym: name,,NO_SECT,type,register
2982061da546Spatrick type = eSymbolTypeVariable;
2983061da546Spatrick break;
2984061da546Spatrick
2985061da546Spatrick case N_SLINE:
2986061da546Spatrick // src line: 0,,n_sect,linenumber,address
2987061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect,
2988061da546Spatrick nlist.n_value);
2989061da546Spatrick type = eSymbolTypeLineEntry;
2990061da546Spatrick break;
2991061da546Spatrick
2992061da546Spatrick case N_SSYM:
2993061da546Spatrick // structure elt: name,,NO_SECT,type,struct_offset
2994061da546Spatrick type = eSymbolTypeVariableType;
2995061da546Spatrick break;
2996061da546Spatrick
2997061da546Spatrick case N_SO:
2998061da546Spatrick // source file name
2999061da546Spatrick type = eSymbolTypeSourceFile;
3000061da546Spatrick if (symbol_name == NULL) {
3001061da546Spatrick add_nlist = false;
3002061da546Spatrick if (N_SO_index != UINT32_MAX) {
3003061da546Spatrick // Set the size of the N_SO to the terminating
3004061da546Spatrick // index of this N_SO so that we can always skip
3005061da546Spatrick // the entire N_SO if we need to navigate more
3006061da546Spatrick // quickly at the source level when parsing STABS
3007*f6aab3d8Srobert symbol_ptr = symtab.SymbolAtIndex(N_SO_index);
3008061da546Spatrick symbol_ptr->SetByteSize(sym_idx);
3009061da546Spatrick symbol_ptr->SetSizeIsSibling(true);
3010061da546Spatrick }
3011061da546Spatrick N_NSYM_indexes.clear();
3012061da546Spatrick N_INCL_indexes.clear();
3013061da546Spatrick N_BRAC_indexes.clear();
3014061da546Spatrick N_COMM_indexes.clear();
3015061da546Spatrick N_FUN_indexes.clear();
3016061da546Spatrick N_SO_index = UINT32_MAX;
3017061da546Spatrick } else {
3018061da546Spatrick // We use the current number of symbols in the
3019061da546Spatrick // symbol table in lieu of using nlist_idx in case
3020061da546Spatrick // we ever start trimming entries out
3021061da546Spatrick const bool N_SO_has_full_path = symbol_name[0] == '/';
3022061da546Spatrick if (N_SO_has_full_path) {
3023061da546Spatrick if ((N_SO_index == sym_idx - 1) &&
3024061da546Spatrick ((sym_idx - 1) < num_syms)) {
3025061da546Spatrick // We have two consecutive N_SO entries where
3026061da546Spatrick // the first contains a directory and the
3027061da546Spatrick // second contains a full path.
3028061da546Spatrick sym[sym_idx - 1].GetMangled().SetValue(
3029061da546Spatrick ConstString(symbol_name), false);
3030061da546Spatrick m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3031061da546Spatrick add_nlist = false;
3032061da546Spatrick } else {
3033061da546Spatrick // This is the first entry in a N_SO that
3034061da546Spatrick // contains a directory or
3035061da546Spatrick // a full path to the source file
3036061da546Spatrick N_SO_index = sym_idx;
3037061da546Spatrick }
3038061da546Spatrick } else if ((N_SO_index == sym_idx - 1) &&
3039061da546Spatrick ((sym_idx - 1) < num_syms)) {
3040061da546Spatrick // This is usually the second N_SO entry that
3041061da546Spatrick // contains just the filename, so here we combine
3042061da546Spatrick // it with the first one if we are minimizing the
3043061da546Spatrick // symbol table
3044be691f3bSpatrick const char *so_path = sym[sym_idx - 1]
3045061da546Spatrick .GetMangled()
3046be691f3bSpatrick .GetDemangledName()
3047061da546Spatrick .AsCString();
3048061da546Spatrick if (so_path && so_path[0]) {
3049061da546Spatrick std::string full_so_path(so_path);
3050061da546Spatrick const size_t double_slash_pos =
3051061da546Spatrick full_so_path.find("//");
3052061da546Spatrick if (double_slash_pos != std::string::npos) {
3053061da546Spatrick // The linker has been generating bad N_SO
3054061da546Spatrick // entries with doubled up paths
3055061da546Spatrick // in the format "%s%s" where the first
3056061da546Spatrick // string in the DW_AT_comp_dir, and the
3057061da546Spatrick // second is the directory for the source
3058061da546Spatrick // file so you end up with a path that looks
3059061da546Spatrick // like "/tmp/src//tmp/src/"
3060061da546Spatrick FileSpec so_dir(so_path);
3061061da546Spatrick if (!FileSystem::Instance().Exists(so_dir)) {
3062061da546Spatrick so_dir.SetFile(
3063061da546Spatrick &full_so_path[double_slash_pos + 1],
3064061da546Spatrick FileSpec::Style::native);
3065061da546Spatrick if (FileSystem::Instance().Exists(so_dir)) {
3066061da546Spatrick // Trim off the incorrect path
3067061da546Spatrick full_so_path.erase(0, double_slash_pos + 1);
3068061da546Spatrick }
3069061da546Spatrick }
3070061da546Spatrick }
3071061da546Spatrick if (*full_so_path.rbegin() != '/')
3072061da546Spatrick full_so_path += '/';
3073061da546Spatrick full_so_path += symbol_name;
3074061da546Spatrick sym[sym_idx - 1].GetMangled().SetValue(
3075061da546Spatrick ConstString(full_so_path.c_str()), false);
3076061da546Spatrick add_nlist = false;
3077061da546Spatrick m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3078061da546Spatrick }
3079061da546Spatrick } else {
3080061da546Spatrick // This could be a relative path to a N_SO
3081061da546Spatrick N_SO_index = sym_idx;
3082061da546Spatrick }
3083061da546Spatrick }
3084061da546Spatrick break;
3085061da546Spatrick
3086061da546Spatrick case N_OSO:
3087061da546Spatrick // object file name: name,,0,0,st_mtime
3088061da546Spatrick type = eSymbolTypeObjectFile;
3089061da546Spatrick break;
3090061da546Spatrick
3091061da546Spatrick case N_LSYM:
3092061da546Spatrick // local sym: name,,NO_SECT,type,offset
3093061da546Spatrick type = eSymbolTypeLocal;
3094061da546Spatrick break;
3095061da546Spatrick
3096061da546Spatrick // INCL scopes
3097061da546Spatrick case N_BINCL:
3098061da546Spatrick // include file beginning: name,,NO_SECT,0,sum We use
3099061da546Spatrick // the current number of symbols in the symbol table
3100061da546Spatrick // in lieu of using nlist_idx in case we ever start
3101061da546Spatrick // trimming entries out
3102061da546Spatrick N_INCL_indexes.push_back(sym_idx);
3103061da546Spatrick type = eSymbolTypeScopeBegin;
3104061da546Spatrick break;
3105061da546Spatrick
3106061da546Spatrick case N_EINCL:
3107061da546Spatrick // include file end: name,,NO_SECT,0,0
3108061da546Spatrick // Set the size of the N_BINCL to the terminating
3109061da546Spatrick // index of this N_EINCL so that we can always skip
3110061da546Spatrick // the entire symbol if we need to navigate more
3111061da546Spatrick // quickly at the source level when parsing STABS
3112061da546Spatrick if (!N_INCL_indexes.empty()) {
3113061da546Spatrick symbol_ptr =
3114*f6aab3d8Srobert symtab.SymbolAtIndex(N_INCL_indexes.back());
3115061da546Spatrick symbol_ptr->SetByteSize(sym_idx + 1);
3116061da546Spatrick symbol_ptr->SetSizeIsSibling(true);
3117061da546Spatrick N_INCL_indexes.pop_back();
3118061da546Spatrick }
3119061da546Spatrick type = eSymbolTypeScopeEnd;
3120061da546Spatrick break;
3121061da546Spatrick
3122061da546Spatrick case N_SOL:
3123061da546Spatrick // #included file name: name,,n_sect,0,address
3124061da546Spatrick type = eSymbolTypeHeaderFile;
3125061da546Spatrick
3126061da546Spatrick // We currently don't use the header files on darwin
3127061da546Spatrick add_nlist = false;
3128061da546Spatrick break;
3129061da546Spatrick
3130061da546Spatrick case N_PARAMS:
3131061da546Spatrick // compiler parameters: name,,NO_SECT,0,0
3132061da546Spatrick type = eSymbolTypeCompiler;
3133061da546Spatrick break;
3134061da546Spatrick
3135061da546Spatrick case N_VERSION:
3136061da546Spatrick // compiler version: name,,NO_SECT,0,0
3137061da546Spatrick type = eSymbolTypeCompiler;
3138061da546Spatrick break;
3139061da546Spatrick
3140061da546Spatrick case N_OLEVEL:
3141061da546Spatrick // compiler -O level: name,,NO_SECT,0,0
3142061da546Spatrick type = eSymbolTypeCompiler;
3143061da546Spatrick break;
3144061da546Spatrick
3145061da546Spatrick case N_PSYM:
3146061da546Spatrick // parameter: name,,NO_SECT,type,offset
3147061da546Spatrick type = eSymbolTypeVariable;
3148061da546Spatrick break;
3149061da546Spatrick
3150061da546Spatrick case N_ENTRY:
3151061da546Spatrick // alternate entry: name,,n_sect,linenumber,address
3152061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect,
3153061da546Spatrick nlist.n_value);
3154061da546Spatrick type = eSymbolTypeLineEntry;
3155061da546Spatrick break;
3156061da546Spatrick
3157061da546Spatrick // Left and Right Braces
3158061da546Spatrick case N_LBRAC:
3159061da546Spatrick // left bracket: 0,,NO_SECT,nesting level,address We
3160061da546Spatrick // use the current number of symbols in the symbol
3161061da546Spatrick // table in lieu of using nlist_idx in case we ever
3162061da546Spatrick // start trimming entries out
3163061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect,
3164061da546Spatrick nlist.n_value);
3165061da546Spatrick N_BRAC_indexes.push_back(sym_idx);
3166061da546Spatrick type = eSymbolTypeScopeBegin;
3167061da546Spatrick break;
3168061da546Spatrick
3169061da546Spatrick case N_RBRAC:
3170061da546Spatrick // right bracket: 0,,NO_SECT,nesting level,address
3171061da546Spatrick // Set the size of the N_LBRAC to the terminating
3172061da546Spatrick // index of this N_RBRAC so that we can always skip
3173061da546Spatrick // the entire symbol if we need to navigate more
3174061da546Spatrick // quickly at the source level when parsing STABS
3175061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect,
3176061da546Spatrick nlist.n_value);
3177061da546Spatrick if (!N_BRAC_indexes.empty()) {
3178061da546Spatrick symbol_ptr =
3179*f6aab3d8Srobert symtab.SymbolAtIndex(N_BRAC_indexes.back());
3180061da546Spatrick symbol_ptr->SetByteSize(sym_idx + 1);
3181061da546Spatrick symbol_ptr->SetSizeIsSibling(true);
3182061da546Spatrick N_BRAC_indexes.pop_back();
3183061da546Spatrick }
3184061da546Spatrick type = eSymbolTypeScopeEnd;
3185061da546Spatrick break;
3186061da546Spatrick
3187061da546Spatrick case N_EXCL:
3188061da546Spatrick // deleted include file: name,,NO_SECT,0,sum
3189061da546Spatrick type = eSymbolTypeHeaderFile;
3190061da546Spatrick break;
3191061da546Spatrick
3192061da546Spatrick // COMM scopes
3193061da546Spatrick case N_BCOMM:
3194061da546Spatrick // begin common: name,,NO_SECT,0,0
3195061da546Spatrick // We use the current number of symbols in the symbol
3196061da546Spatrick // table in lieu of using nlist_idx in case we ever
3197061da546Spatrick // start trimming entries out
3198061da546Spatrick type = eSymbolTypeScopeBegin;
3199061da546Spatrick N_COMM_indexes.push_back(sym_idx);
3200061da546Spatrick break;
3201061da546Spatrick
3202061da546Spatrick case N_ECOML:
3203061da546Spatrick // end common (local name): 0,,n_sect,0,address
3204061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect,
3205061da546Spatrick nlist.n_value);
3206061da546Spatrick // Fall through
3207061da546Spatrick
3208061da546Spatrick case N_ECOMM:
3209061da546Spatrick // end common: name,,n_sect,0,0
3210061da546Spatrick // Set the size of the N_BCOMM to the terminating
3211061da546Spatrick // index of this N_ECOMM/N_ECOML so that we can
3212061da546Spatrick // always skip the entire symbol if we need to
3213061da546Spatrick // navigate more quickly at the source level when
3214061da546Spatrick // parsing STABS
3215061da546Spatrick if (!N_COMM_indexes.empty()) {
3216061da546Spatrick symbol_ptr =
3217*f6aab3d8Srobert symtab.SymbolAtIndex(N_COMM_indexes.back());
3218061da546Spatrick symbol_ptr->SetByteSize(sym_idx + 1);
3219061da546Spatrick symbol_ptr->SetSizeIsSibling(true);
3220061da546Spatrick N_COMM_indexes.pop_back();
3221061da546Spatrick }
3222061da546Spatrick type = eSymbolTypeScopeEnd;
3223061da546Spatrick break;
3224061da546Spatrick
3225061da546Spatrick case N_LENG:
3226061da546Spatrick // second stab entry with length information
3227061da546Spatrick type = eSymbolTypeAdditional;
3228061da546Spatrick break;
3229061da546Spatrick
3230061da546Spatrick default:
3231061da546Spatrick break;
3232061da546Spatrick }
3233061da546Spatrick } else {
3234061da546Spatrick // uint8_t n_pext = N_PEXT & nlist.n_type;
3235061da546Spatrick uint8_t n_type = N_TYPE & nlist.n_type;
3236061da546Spatrick sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
3237061da546Spatrick
3238061da546Spatrick switch (n_type) {
3239061da546Spatrick case N_INDR: {
3240061da546Spatrick const char *reexport_name_cstr =
3241061da546Spatrick strtab_data.PeekCStr(nlist.n_value);
3242061da546Spatrick if (reexport_name_cstr && reexport_name_cstr[0]) {
3243061da546Spatrick type = eSymbolTypeReExported;
3244061da546Spatrick ConstString reexport_name(
3245061da546Spatrick reexport_name_cstr +
3246061da546Spatrick ((reexport_name_cstr[0] == '_') ? 1 : 0));
3247061da546Spatrick sym[sym_idx].SetReExportedSymbolName(reexport_name);
3248061da546Spatrick set_value = false;
3249061da546Spatrick reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3250061da546Spatrick indirect_symbol_names.insert(ConstString(
3251061da546Spatrick symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
3252061da546Spatrick } else
3253061da546Spatrick type = eSymbolTypeUndefined;
3254061da546Spatrick } break;
3255061da546Spatrick
3256061da546Spatrick case N_UNDF:
3257061da546Spatrick if (symbol_name && symbol_name[0]) {
3258061da546Spatrick ConstString undefined_name(
3259061da546Spatrick symbol_name + ((symbol_name[0] == '_') ? 1 : 0));
3260061da546Spatrick undefined_name_to_desc[undefined_name] = nlist.n_desc;
3261061da546Spatrick }
3262061da546Spatrick // Fall through
3263061da546Spatrick case N_PBUD:
3264061da546Spatrick type = eSymbolTypeUndefined;
3265061da546Spatrick break;
3266061da546Spatrick
3267061da546Spatrick case N_ABS:
3268061da546Spatrick type = eSymbolTypeAbsolute;
3269061da546Spatrick break;
3270061da546Spatrick
3271061da546Spatrick case N_SECT: {
3272061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect,
3273061da546Spatrick nlist.n_value);
3274061da546Spatrick
3275061da546Spatrick if (symbol_section == NULL) {
3276061da546Spatrick // TODO: warn about this?
3277061da546Spatrick add_nlist = false;
3278061da546Spatrick break;
3279061da546Spatrick }
3280061da546Spatrick
3281061da546Spatrick if (TEXT_eh_frame_sectID == nlist.n_sect) {
3282061da546Spatrick type = eSymbolTypeException;
3283061da546Spatrick } else {
3284061da546Spatrick uint32_t section_type =
3285061da546Spatrick symbol_section->Get() & SECTION_TYPE;
3286061da546Spatrick
3287061da546Spatrick switch (section_type) {
3288061da546Spatrick case S_CSTRING_LITERALS:
3289061da546Spatrick type = eSymbolTypeData;
3290061da546Spatrick break; // section with only literal C strings
3291061da546Spatrick case S_4BYTE_LITERALS:
3292061da546Spatrick type = eSymbolTypeData;
3293061da546Spatrick break; // section with only 4 byte literals
3294061da546Spatrick case S_8BYTE_LITERALS:
3295061da546Spatrick type = eSymbolTypeData;
3296061da546Spatrick break; // section with only 8 byte literals
3297061da546Spatrick case S_LITERAL_POINTERS:
3298061da546Spatrick type = eSymbolTypeTrampoline;
3299061da546Spatrick break; // section with only pointers to literals
3300061da546Spatrick case S_NON_LAZY_SYMBOL_POINTERS:
3301061da546Spatrick type = eSymbolTypeTrampoline;
3302061da546Spatrick break; // section with only non-lazy symbol
3303061da546Spatrick // pointers
3304061da546Spatrick case S_LAZY_SYMBOL_POINTERS:
3305061da546Spatrick type = eSymbolTypeTrampoline;
3306061da546Spatrick break; // section with only lazy symbol pointers
3307061da546Spatrick case S_SYMBOL_STUBS:
3308061da546Spatrick type = eSymbolTypeTrampoline;
3309061da546Spatrick break; // section with only symbol stubs, byte
3310061da546Spatrick // size of stub in the reserved2 field
3311061da546Spatrick case S_MOD_INIT_FUNC_POINTERS:
3312061da546Spatrick type = eSymbolTypeCode;
3313061da546Spatrick break; // section with only function pointers for
3314061da546Spatrick // initialization
3315061da546Spatrick case S_MOD_TERM_FUNC_POINTERS:
3316061da546Spatrick type = eSymbolTypeCode;
3317061da546Spatrick break; // section with only function pointers for
3318061da546Spatrick // termination
3319061da546Spatrick case S_INTERPOSING:
3320061da546Spatrick type = eSymbolTypeTrampoline;
3321061da546Spatrick break; // section with only pairs of function
3322061da546Spatrick // pointers for interposing
3323061da546Spatrick case S_16BYTE_LITERALS:
3324061da546Spatrick type = eSymbolTypeData;
3325061da546Spatrick break; // section with only 16 byte literals
3326061da546Spatrick case S_DTRACE_DOF:
3327061da546Spatrick type = eSymbolTypeInstrumentation;
3328061da546Spatrick break;
3329061da546Spatrick case S_LAZY_DYLIB_SYMBOL_POINTERS:
3330061da546Spatrick type = eSymbolTypeTrampoline;
3331061da546Spatrick break;
3332061da546Spatrick default:
3333061da546Spatrick switch (symbol_section->GetType()) {
3334061da546Spatrick case lldb::eSectionTypeCode:
3335061da546Spatrick type = eSymbolTypeCode;
3336061da546Spatrick break;
3337061da546Spatrick case eSectionTypeData:
3338061da546Spatrick case eSectionTypeDataCString: // Inlined C string
3339061da546Spatrick // data
3340061da546Spatrick case eSectionTypeDataCStringPointers: // Pointers
3341061da546Spatrick // to C
3342061da546Spatrick // string
3343061da546Spatrick // data
3344061da546Spatrick case eSectionTypeDataSymbolAddress: // Address of
3345061da546Spatrick // a symbol in
3346061da546Spatrick // the symbol
3347061da546Spatrick // table
3348061da546Spatrick case eSectionTypeData4:
3349061da546Spatrick case eSectionTypeData8:
3350061da546Spatrick case eSectionTypeData16:
3351061da546Spatrick type = eSymbolTypeData;
3352061da546Spatrick break;
3353061da546Spatrick default:
3354061da546Spatrick break;
3355061da546Spatrick }
3356061da546Spatrick break;
3357061da546Spatrick }
3358061da546Spatrick
3359061da546Spatrick if (type == eSymbolTypeInvalid) {
3360061da546Spatrick const char *symbol_sect_name =
3361061da546Spatrick symbol_section->GetName().AsCString();
3362061da546Spatrick if (symbol_section->IsDescendant(
3363061da546Spatrick text_section_sp.get())) {
3364061da546Spatrick if (symbol_section->IsClear(
3365061da546Spatrick S_ATTR_PURE_INSTRUCTIONS |
3366061da546Spatrick S_ATTR_SELF_MODIFYING_CODE |
3367061da546Spatrick S_ATTR_SOME_INSTRUCTIONS))
3368061da546Spatrick type = eSymbolTypeData;
3369061da546Spatrick else
3370061da546Spatrick type = eSymbolTypeCode;
3371061da546Spatrick } else if (symbol_section->IsDescendant(
3372061da546Spatrick data_section_sp.get()) ||
3373061da546Spatrick symbol_section->IsDescendant(
3374061da546Spatrick data_dirty_section_sp.get()) ||
3375061da546Spatrick symbol_section->IsDescendant(
3376061da546Spatrick data_const_section_sp.get())) {
3377061da546Spatrick if (symbol_sect_name &&
3378061da546Spatrick ::strstr(symbol_sect_name, "__objc") ==
3379061da546Spatrick symbol_sect_name) {
3380061da546Spatrick type = eSymbolTypeRuntime;
3381061da546Spatrick
3382061da546Spatrick if (symbol_name) {
3383061da546Spatrick llvm::StringRef symbol_name_ref(symbol_name);
3384061da546Spatrick if (symbol_name_ref.startswith("_OBJC_")) {
3385061da546Spatrick llvm::StringRef
3386061da546Spatrick g_objc_v2_prefix_class(
3387061da546Spatrick "_OBJC_CLASS_$_");
3388061da546Spatrick llvm::StringRef
3389061da546Spatrick g_objc_v2_prefix_metaclass(
3390061da546Spatrick "_OBJC_METACLASS_$_");
3391061da546Spatrick llvm::StringRef
3392061da546Spatrick g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
3393061da546Spatrick if (symbol_name_ref.startswith(
3394061da546Spatrick g_objc_v2_prefix_class)) {
3395061da546Spatrick symbol_name_non_abi_mangled =
3396061da546Spatrick symbol_name + 1;
3397061da546Spatrick symbol_name =
3398061da546Spatrick symbol_name +
3399061da546Spatrick g_objc_v2_prefix_class.size();
3400061da546Spatrick type = eSymbolTypeObjCClass;
3401061da546Spatrick demangled_is_synthesized = true;
3402061da546Spatrick } else if (
3403061da546Spatrick symbol_name_ref.startswith(
3404061da546Spatrick g_objc_v2_prefix_metaclass)) {
3405061da546Spatrick symbol_name_non_abi_mangled =
3406061da546Spatrick symbol_name + 1;
3407061da546Spatrick symbol_name =
3408061da546Spatrick symbol_name +
3409061da546Spatrick g_objc_v2_prefix_metaclass.size();
3410061da546Spatrick type = eSymbolTypeObjCMetaClass;
3411061da546Spatrick demangled_is_synthesized = true;
3412061da546Spatrick } else if (symbol_name_ref.startswith(
3413061da546Spatrick g_objc_v2_prefix_ivar)) {
3414061da546Spatrick symbol_name_non_abi_mangled =
3415061da546Spatrick symbol_name + 1;
3416061da546Spatrick symbol_name =
3417061da546Spatrick symbol_name +
3418061da546Spatrick g_objc_v2_prefix_ivar.size();
3419061da546Spatrick type = eSymbolTypeObjCIVar;
3420061da546Spatrick demangled_is_synthesized = true;
3421061da546Spatrick }
3422061da546Spatrick }
3423061da546Spatrick }
3424061da546Spatrick } else if (symbol_sect_name &&
3425061da546Spatrick ::strstr(symbol_sect_name,
3426061da546Spatrick "__gcc_except_tab") ==
3427061da546Spatrick symbol_sect_name) {
3428061da546Spatrick type = eSymbolTypeException;
3429061da546Spatrick } else {
3430061da546Spatrick type = eSymbolTypeData;
3431061da546Spatrick }
3432061da546Spatrick } else if (symbol_sect_name &&
3433061da546Spatrick ::strstr(symbol_sect_name, "__IMPORT") ==
3434061da546Spatrick symbol_sect_name) {
3435061da546Spatrick type = eSymbolTypeTrampoline;
3436061da546Spatrick } else if (symbol_section->IsDescendant(
3437061da546Spatrick objc_section_sp.get())) {
3438061da546Spatrick type = eSymbolTypeRuntime;
3439061da546Spatrick if (symbol_name && symbol_name[0] == '.') {
3440061da546Spatrick llvm::StringRef symbol_name_ref(symbol_name);
3441061da546Spatrick llvm::StringRef
3442061da546Spatrick g_objc_v1_prefix_class(".objc_class_name_");
3443061da546Spatrick if (symbol_name_ref.startswith(
3444061da546Spatrick g_objc_v1_prefix_class)) {
3445061da546Spatrick symbol_name_non_abi_mangled = symbol_name;
3446061da546Spatrick symbol_name = symbol_name +
3447061da546Spatrick g_objc_v1_prefix_class.size();
3448061da546Spatrick type = eSymbolTypeObjCClass;
3449061da546Spatrick demangled_is_synthesized = true;
3450061da546Spatrick }
3451061da546Spatrick }
3452061da546Spatrick }
3453061da546Spatrick }
3454061da546Spatrick }
3455061da546Spatrick } break;
3456061da546Spatrick }
3457061da546Spatrick }
3458061da546Spatrick
3459061da546Spatrick if (add_nlist) {
3460061da546Spatrick uint64_t symbol_value = nlist.n_value;
3461061da546Spatrick if (symbol_name_non_abi_mangled) {
3462061da546Spatrick sym[sym_idx].GetMangled().SetMangledName(
3463061da546Spatrick ConstString(symbol_name_non_abi_mangled));
3464061da546Spatrick sym[sym_idx].GetMangled().SetDemangledName(
3465061da546Spatrick ConstString(symbol_name));
3466061da546Spatrick } else {
3467061da546Spatrick bool symbol_name_is_mangled = false;
3468061da546Spatrick
3469061da546Spatrick if (symbol_name && symbol_name[0] == '_') {
3470061da546Spatrick symbol_name_is_mangled = symbol_name[1] == '_';
3471061da546Spatrick symbol_name++; // Skip the leading underscore
3472061da546Spatrick }
3473061da546Spatrick
3474061da546Spatrick if (symbol_name) {
3475061da546Spatrick ConstString const_symbol_name(symbol_name);
3476061da546Spatrick sym[sym_idx].GetMangled().SetValue(
3477061da546Spatrick const_symbol_name, symbol_name_is_mangled);
3478061da546Spatrick if (is_gsym && is_debug) {
3479061da546Spatrick const char *gsym_name =
3480061da546Spatrick sym[sym_idx]
3481061da546Spatrick .GetMangled()
3482be691f3bSpatrick .GetName(Mangled::ePreferMangled)
3483061da546Spatrick .GetCString();
3484061da546Spatrick if (gsym_name)
3485061da546Spatrick N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3486061da546Spatrick }
3487061da546Spatrick }
3488061da546Spatrick }
3489061da546Spatrick if (symbol_section) {
3490061da546Spatrick const addr_t section_file_addr =
3491061da546Spatrick symbol_section->GetFileAddress();
3492061da546Spatrick if (symbol_byte_size == 0 &&
3493061da546Spatrick function_starts_count > 0) {
3494061da546Spatrick addr_t symbol_lookup_file_addr = nlist.n_value;
3495061da546Spatrick // Do an exact address match for non-ARM addresses,
3496061da546Spatrick // else get the closest since the symbol might be a
3497061da546Spatrick // thumb symbol which has an address with bit zero
3498061da546Spatrick // set
3499061da546Spatrick FunctionStarts::Entry *func_start_entry =
3500061da546Spatrick function_starts.FindEntry(symbol_lookup_file_addr,
3501061da546Spatrick !is_arm);
3502061da546Spatrick if (is_arm && func_start_entry) {
3503061da546Spatrick // Verify that the function start address is the
3504061da546Spatrick // symbol address (ARM) or the symbol address + 1
3505061da546Spatrick // (thumb)
3506061da546Spatrick if (func_start_entry->addr !=
3507061da546Spatrick symbol_lookup_file_addr &&
3508061da546Spatrick func_start_entry->addr !=
3509061da546Spatrick (symbol_lookup_file_addr + 1)) {
3510061da546Spatrick // Not the right entry, NULL it out...
3511061da546Spatrick func_start_entry = NULL;
3512061da546Spatrick }
3513061da546Spatrick }
3514061da546Spatrick if (func_start_entry) {
3515061da546Spatrick func_start_entry->data = true;
3516061da546Spatrick
3517061da546Spatrick addr_t symbol_file_addr = func_start_entry->addr;
3518061da546Spatrick uint32_t symbol_flags = 0;
3519061da546Spatrick if (is_arm) {
3520061da546Spatrick if (symbol_file_addr & 1)
3521061da546Spatrick symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3522061da546Spatrick symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3523061da546Spatrick }
3524061da546Spatrick
3525061da546Spatrick const FunctionStarts::Entry *next_func_start_entry =
3526061da546Spatrick function_starts.FindNextEntry(func_start_entry);
3527061da546Spatrick const addr_t section_end_file_addr =
3528061da546Spatrick section_file_addr +
3529061da546Spatrick symbol_section->GetByteSize();
3530061da546Spatrick if (next_func_start_entry) {
3531061da546Spatrick addr_t next_symbol_file_addr =
3532061da546Spatrick next_func_start_entry->addr;
3533061da546Spatrick // Be sure the clear the Thumb address bit when
3534061da546Spatrick // we calculate the size from the current and
3535061da546Spatrick // next address
3536061da546Spatrick if (is_arm)
3537061da546Spatrick next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3538061da546Spatrick symbol_byte_size = std::min<lldb::addr_t>(
3539061da546Spatrick next_symbol_file_addr - symbol_file_addr,
3540061da546Spatrick section_end_file_addr - symbol_file_addr);
3541061da546Spatrick } else {
3542061da546Spatrick symbol_byte_size =
3543061da546Spatrick section_end_file_addr - symbol_file_addr;
3544061da546Spatrick }
3545061da546Spatrick }
3546061da546Spatrick }
3547061da546Spatrick symbol_value -= section_file_addr;
3548061da546Spatrick }
3549061da546Spatrick
3550061da546Spatrick if (is_debug == false) {
3551061da546Spatrick if (type == eSymbolTypeCode) {
3552061da546Spatrick // See if we can find a N_FUN entry for any code
3553061da546Spatrick // symbols. If we do find a match, and the name
3554061da546Spatrick // matches, then we can merge the two into just the
3555061da546Spatrick // function symbol to avoid duplicate entries in
3556061da546Spatrick // the symbol table
3557061da546Spatrick auto range =
3558061da546Spatrick N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
3559061da546Spatrick if (range.first != range.second) {
3560061da546Spatrick bool found_it = false;
3561dda28197Spatrick for (auto pos = range.first; pos != range.second;
3562dda28197Spatrick ++pos) {
3563061da546Spatrick if (sym[sym_idx].GetMangled().GetName(
3564061da546Spatrick Mangled::ePreferMangled) ==
3565061da546Spatrick sym[pos->second].GetMangled().GetName(
3566061da546Spatrick Mangled::ePreferMangled)) {
3567061da546Spatrick m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3568061da546Spatrick // We just need the flags from the linker
3569061da546Spatrick // symbol, so put these flags
3570061da546Spatrick // into the N_FUN flags to avoid duplicate
3571061da546Spatrick // symbols in the symbol table
3572061da546Spatrick sym[pos->second].SetExternal(
3573061da546Spatrick sym[sym_idx].IsExternal());
3574061da546Spatrick sym[pos->second].SetFlags(nlist.n_type << 16 |
3575061da546Spatrick nlist.n_desc);
3576061da546Spatrick if (resolver_addresses.find(nlist.n_value) !=
3577061da546Spatrick resolver_addresses.end())
3578061da546Spatrick sym[pos->second].SetType(eSymbolTypeResolver);
3579061da546Spatrick sym[sym_idx].Clear();
3580061da546Spatrick found_it = true;
3581061da546Spatrick break;
3582061da546Spatrick }
3583061da546Spatrick }
3584061da546Spatrick if (found_it)
3585061da546Spatrick continue;
3586061da546Spatrick } else {
3587061da546Spatrick if (resolver_addresses.find(nlist.n_value) !=
3588061da546Spatrick resolver_addresses.end())
3589061da546Spatrick type = eSymbolTypeResolver;
3590061da546Spatrick }
3591061da546Spatrick } else if (type == eSymbolTypeData ||
3592061da546Spatrick type == eSymbolTypeObjCClass ||
3593061da546Spatrick type == eSymbolTypeObjCMetaClass ||
3594061da546Spatrick type == eSymbolTypeObjCIVar) {
3595061da546Spatrick // See if we can find a N_STSYM entry for any data
3596061da546Spatrick // symbols. If we do find a match, and the name
3597061da546Spatrick // matches, then we can merge the two into just the
3598061da546Spatrick // Static symbol to avoid duplicate entries in the
3599061da546Spatrick // symbol table
3600061da546Spatrick auto range = N_STSYM_addr_to_sym_idx.equal_range(
3601061da546Spatrick nlist.n_value);
3602061da546Spatrick if (range.first != range.second) {
3603061da546Spatrick bool found_it = false;
3604dda28197Spatrick for (auto pos = range.first; pos != range.second;
3605dda28197Spatrick ++pos) {
3606061da546Spatrick if (sym[sym_idx].GetMangled().GetName(
3607061da546Spatrick Mangled::ePreferMangled) ==
3608061da546Spatrick sym[pos->second].GetMangled().GetName(
3609061da546Spatrick Mangled::ePreferMangled)) {
3610061da546Spatrick m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3611061da546Spatrick // We just need the flags from the linker
3612061da546Spatrick // symbol, so put these flags
3613061da546Spatrick // into the N_STSYM flags to avoid duplicate
3614061da546Spatrick // symbols in the symbol table
3615061da546Spatrick sym[pos->second].SetExternal(
3616061da546Spatrick sym[sym_idx].IsExternal());
3617061da546Spatrick sym[pos->second].SetFlags(nlist.n_type << 16 |
3618061da546Spatrick nlist.n_desc);
3619061da546Spatrick sym[sym_idx].Clear();
3620061da546Spatrick found_it = true;
3621061da546Spatrick break;
3622061da546Spatrick }
3623061da546Spatrick }
3624061da546Spatrick if (found_it)
3625061da546Spatrick continue;
3626061da546Spatrick } else {
3627061da546Spatrick const char *gsym_name =
3628061da546Spatrick sym[sym_idx]
3629061da546Spatrick .GetMangled()
3630be691f3bSpatrick .GetName(Mangled::ePreferMangled)
3631061da546Spatrick .GetCString();
3632061da546Spatrick if (gsym_name) {
3633061da546Spatrick // Combine N_GSYM stab entries with the non
3634061da546Spatrick // stab symbol
3635061da546Spatrick ConstNameToSymbolIndexMap::const_iterator pos =
3636061da546Spatrick N_GSYM_name_to_sym_idx.find(gsym_name);
3637061da546Spatrick if (pos != N_GSYM_name_to_sym_idx.end()) {
3638061da546Spatrick const uint32_t GSYM_sym_idx = pos->second;
3639061da546Spatrick m_nlist_idx_to_sym_idx[nlist_idx] =
3640061da546Spatrick GSYM_sym_idx;
3641061da546Spatrick // Copy the address, because often the N_GSYM
3642061da546Spatrick // address has an invalid address of zero
3643061da546Spatrick // when the global is a common symbol
3644061da546Spatrick sym[GSYM_sym_idx].GetAddressRef().SetSection(
3645061da546Spatrick symbol_section);
3646061da546Spatrick sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3647061da546Spatrick symbol_value);
3648be691f3bSpatrick add_symbol_addr(sym[GSYM_sym_idx]
3649dda28197Spatrick .GetAddress()
3650dda28197Spatrick .GetFileAddress());
3651061da546Spatrick // We just need the flags from the linker
3652061da546Spatrick // symbol, so put these flags
3653061da546Spatrick // into the N_GSYM flags to avoid duplicate
3654061da546Spatrick // symbols in the symbol table
3655061da546Spatrick sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
3656061da546Spatrick nlist.n_desc);
3657061da546Spatrick sym[sym_idx].Clear();
3658061da546Spatrick continue;
3659061da546Spatrick }
3660061da546Spatrick }
3661061da546Spatrick }
3662061da546Spatrick }
3663061da546Spatrick }
3664061da546Spatrick
3665061da546Spatrick sym[sym_idx].SetID(nlist_idx);
3666061da546Spatrick sym[sym_idx].SetType(type);
3667061da546Spatrick if (set_value) {
3668061da546Spatrick sym[sym_idx].GetAddressRef().SetSection(symbol_section);
3669061da546Spatrick sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
3670be691f3bSpatrick add_symbol_addr(
3671dda28197Spatrick sym[sym_idx].GetAddress().GetFileAddress());
3672061da546Spatrick }
3673061da546Spatrick sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
3674061da546Spatrick
3675061da546Spatrick if (symbol_byte_size > 0)
3676061da546Spatrick sym[sym_idx].SetByteSize(symbol_byte_size);
3677061da546Spatrick
3678061da546Spatrick if (demangled_is_synthesized)
3679061da546Spatrick sym[sym_idx].SetDemangledNameIsSynthesized(true);
3680061da546Spatrick ++sym_idx;
3681061da546Spatrick } else {
3682061da546Spatrick sym[sym_idx].Clear();
3683061da546Spatrick }
3684061da546Spatrick }
3685061da546Spatrick /////////////////////////////
3686061da546Spatrick }
3687061da546Spatrick }
3688061da546Spatrick
3689061da546Spatrick for (const auto &pos : reexport_shlib_needs_fixup) {
3690061da546Spatrick const auto undef_pos = undefined_name_to_desc.find(pos.second);
3691061da546Spatrick if (undef_pos != undefined_name_to_desc.end()) {
3692061da546Spatrick const uint8_t dylib_ordinal =
3693061da546Spatrick llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3694061da546Spatrick if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
3695061da546Spatrick sym[pos.first].SetReExportedSymbolSharedLibrary(
3696061da546Spatrick dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3697061da546Spatrick }
3698061da546Spatrick }
3699061da546Spatrick }
3700061da546Spatrick
3701061da546Spatrick #endif
3702*f6aab3d8Srobert lldb::offset_t nlist_data_offset = 0;
3703061da546Spatrick
3704061da546Spatrick if (nlist_data.GetByteSize() > 0) {
3705061da546Spatrick
3706061da546Spatrick // If the sym array was not created while parsing the DSC unmapped
3707061da546Spatrick // symbols, create it now.
3708061da546Spatrick if (sym == nullptr) {
3709061da546Spatrick sym =
3710*f6aab3d8Srobert symtab.Resize(symtab_load_command.nsyms + m_dysymtab.nindirectsyms);
3711*f6aab3d8Srobert num_syms = symtab.GetNumSymbols();
3712061da546Spatrick }
3713061da546Spatrick
3714061da546Spatrick if (unmapped_local_symbols_found) {
3715061da546Spatrick assert(m_dysymtab.ilocalsym == 0);
3716061da546Spatrick nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3717061da546Spatrick nlist_idx = m_dysymtab.nlocalsym;
3718061da546Spatrick } else {
3719061da546Spatrick nlist_idx = 0;
3720061da546Spatrick }
3721061da546Spatrick
3722061da546Spatrick typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
3723061da546Spatrick typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
3724061da546Spatrick UndefinedNameToDescMap undefined_name_to_desc;
3725061da546Spatrick SymbolIndexToName reexport_shlib_needs_fixup;
3726061da546Spatrick
3727061da546Spatrick // Symtab parsing is a huge mess. Everything is entangled and the code
3728061da546Spatrick // requires access to a ridiculous amount of variables. LLDB depends
3729061da546Spatrick // heavily on the proper merging of symbols and to get that right we need
3730061da546Spatrick // to make sure we have parsed all the debug symbols first. Therefore we
3731061da546Spatrick // invoke the lambda twice, once to parse only the debug symbols and then
3732061da546Spatrick // once more to parse the remaining symbols.
3733061da546Spatrick auto ParseSymbolLambda = [&](struct nlist_64 &nlist, uint32_t nlist_idx,
3734061da546Spatrick bool debug_only) {
3735061da546Spatrick const bool is_debug = ((nlist.n_type & N_STAB) != 0);
3736061da546Spatrick if (is_debug != debug_only)
3737061da546Spatrick return true;
3738061da546Spatrick
3739061da546Spatrick const char *symbol_name_non_abi_mangled = nullptr;
3740061da546Spatrick const char *symbol_name = nullptr;
3741061da546Spatrick
3742061da546Spatrick if (have_strtab_data) {
3743061da546Spatrick symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3744061da546Spatrick
3745061da546Spatrick if (symbol_name == nullptr) {
3746061da546Spatrick // No symbol should be NULL, even the symbols with no string values
3747061da546Spatrick // should have an offset zero which points to an empty C-string
3748*f6aab3d8Srobert Debugger::ReportError(llvm::formatv(
3749*f6aab3d8Srobert "symbol[{0}] has invalid string table offset {1:x} in {2}, "
3750*f6aab3d8Srobert "ignoring symbol",
3751*f6aab3d8Srobert nlist_idx, nlist.n_strx, module_sp->GetFileSpec().GetPath()));
3752061da546Spatrick return true;
3753061da546Spatrick }
3754061da546Spatrick if (symbol_name[0] == '\0')
3755061da546Spatrick symbol_name = nullptr;
3756061da546Spatrick } else {
3757061da546Spatrick const addr_t str_addr = strtab_addr + nlist.n_strx;
3758061da546Spatrick Status str_error;
3759061da546Spatrick if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
3760061da546Spatrick str_error))
3761061da546Spatrick symbol_name = memory_symbol_name.c_str();
3762061da546Spatrick }
3763061da546Spatrick
3764061da546Spatrick SymbolType type = eSymbolTypeInvalid;
3765061da546Spatrick SectionSP symbol_section;
3766061da546Spatrick lldb::addr_t symbol_byte_size = 0;
3767061da546Spatrick bool add_nlist = true;
3768061da546Spatrick bool is_gsym = false;
3769061da546Spatrick bool demangled_is_synthesized = false;
3770061da546Spatrick bool set_value = true;
3771061da546Spatrick
3772061da546Spatrick assert(sym_idx < num_syms);
3773061da546Spatrick sym[sym_idx].SetDebug(is_debug);
3774061da546Spatrick
3775061da546Spatrick if (is_debug) {
3776061da546Spatrick switch (nlist.n_type) {
3777061da546Spatrick case N_GSYM:
3778061da546Spatrick // global symbol: name,,NO_SECT,type,0
3779061da546Spatrick // Sometimes the N_GSYM value contains the address.
3780061da546Spatrick
3781061da546Spatrick // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3782061da546Spatrick // the ObjC data. They
3783061da546Spatrick // have the same address, but we want to ensure that we always find
3784061da546Spatrick // only the real symbol, 'cause we don't currently correctly
3785061da546Spatrick // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3786061da546Spatrick // type. This is a temporary hack to make sure the ObjectiveC
3787061da546Spatrick // symbols get treated correctly. To do this right, we should
3788061da546Spatrick // coalesce all the GSYM & global symbols that have the same
3789061da546Spatrick // address.
3790061da546Spatrick is_gsym = true;
3791061da546Spatrick sym[sym_idx].SetExternal(true);
3792061da546Spatrick
3793061da546Spatrick if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3794061da546Spatrick llvm::StringRef symbol_name_ref(symbol_name);
3795061da546Spatrick if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
3796061da546Spatrick symbol_name_non_abi_mangled = symbol_name + 1;
3797061da546Spatrick symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3798061da546Spatrick type = eSymbolTypeObjCClass;
3799061da546Spatrick demangled_is_synthesized = true;
3800061da546Spatrick
3801061da546Spatrick } else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass)) {
3802061da546Spatrick symbol_name_non_abi_mangled = symbol_name + 1;
3803061da546Spatrick symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3804061da546Spatrick type = eSymbolTypeObjCMetaClass;
3805061da546Spatrick demangled_is_synthesized = true;
3806061da546Spatrick } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
3807061da546Spatrick symbol_name_non_abi_mangled = symbol_name + 1;
3808061da546Spatrick symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3809061da546Spatrick type = eSymbolTypeObjCIVar;
3810061da546Spatrick demangled_is_synthesized = true;
3811061da546Spatrick }
3812061da546Spatrick } else {
3813061da546Spatrick if (nlist.n_value != 0)
3814061da546Spatrick symbol_section =
3815061da546Spatrick section_info.GetSection(nlist.n_sect, nlist.n_value);
3816061da546Spatrick type = eSymbolTypeData;
3817061da546Spatrick }
3818061da546Spatrick break;
3819061da546Spatrick
3820061da546Spatrick case N_FNAME:
3821061da546Spatrick // procedure name (f77 kludge): name,,NO_SECT,0,0
3822061da546Spatrick type = eSymbolTypeCompiler;
3823061da546Spatrick break;
3824061da546Spatrick
3825061da546Spatrick case N_FUN:
3826061da546Spatrick // procedure: name,,n_sect,linenumber,address
3827061da546Spatrick if (symbol_name) {
3828061da546Spatrick type = eSymbolTypeCode;
3829061da546Spatrick symbol_section =
3830061da546Spatrick section_info.GetSection(nlist.n_sect, nlist.n_value);
3831061da546Spatrick
3832061da546Spatrick N_FUN_addr_to_sym_idx.insert(
3833061da546Spatrick std::make_pair(nlist.n_value, sym_idx));
3834061da546Spatrick // We use the current number of symbols in the symbol table in
3835061da546Spatrick // lieu of using nlist_idx in case we ever start trimming entries
3836061da546Spatrick // out
3837061da546Spatrick N_FUN_indexes.push_back(sym_idx);
3838061da546Spatrick } else {
3839061da546Spatrick type = eSymbolTypeCompiler;
3840061da546Spatrick
3841061da546Spatrick if (!N_FUN_indexes.empty()) {
3842061da546Spatrick // Copy the size of the function into the original STAB entry
3843061da546Spatrick // so we don't have to hunt for it later
3844*f6aab3d8Srobert symtab.SymbolAtIndex(N_FUN_indexes.back())
3845061da546Spatrick ->SetByteSize(nlist.n_value);
3846061da546Spatrick N_FUN_indexes.pop_back();
3847061da546Spatrick // We don't really need the end function STAB as it contains
3848061da546Spatrick // the size which we already placed with the original symbol,
3849061da546Spatrick // so don't add it if we want a minimal symbol table
3850061da546Spatrick add_nlist = false;
3851061da546Spatrick }
3852061da546Spatrick }
3853061da546Spatrick break;
3854061da546Spatrick
3855061da546Spatrick case N_STSYM:
3856061da546Spatrick // static symbol: name,,n_sect,type,address
3857061da546Spatrick N_STSYM_addr_to_sym_idx.insert(
3858061da546Spatrick std::make_pair(nlist.n_value, sym_idx));
3859061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3860061da546Spatrick if (symbol_name && symbol_name[0]) {
3861061da546Spatrick type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
3862061da546Spatrick eSymbolTypeData);
3863061da546Spatrick }
3864061da546Spatrick break;
3865061da546Spatrick
3866061da546Spatrick case N_LCSYM:
3867061da546Spatrick // .lcomm symbol: name,,n_sect,type,address
3868061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3869061da546Spatrick type = eSymbolTypeCommonBlock;
3870061da546Spatrick break;
3871061da546Spatrick
3872061da546Spatrick case N_BNSYM:
3873061da546Spatrick // We use the current number of symbols in the symbol table in lieu
3874061da546Spatrick // of using nlist_idx in case we ever start trimming entries out
3875061da546Spatrick // Skip these if we want minimal symbol tables
3876061da546Spatrick add_nlist = false;
3877061da546Spatrick break;
3878061da546Spatrick
3879061da546Spatrick case N_ENSYM:
3880061da546Spatrick // Set the size of the N_BNSYM to the terminating index of this
3881061da546Spatrick // N_ENSYM so that we can always skip the entire symbol if we need
3882061da546Spatrick // to navigate more quickly at the source level when parsing STABS
3883061da546Spatrick // Skip these if we want minimal symbol tables
3884061da546Spatrick add_nlist = false;
3885061da546Spatrick break;
3886061da546Spatrick
3887061da546Spatrick case N_OPT:
3888061da546Spatrick // emitted with gcc2_compiled and in gcc source
3889061da546Spatrick type = eSymbolTypeCompiler;
3890061da546Spatrick break;
3891061da546Spatrick
3892061da546Spatrick case N_RSYM:
3893061da546Spatrick // register sym: name,,NO_SECT,type,register
3894061da546Spatrick type = eSymbolTypeVariable;
3895061da546Spatrick break;
3896061da546Spatrick
3897061da546Spatrick case N_SLINE:
3898061da546Spatrick // src line: 0,,n_sect,linenumber,address
3899061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3900061da546Spatrick type = eSymbolTypeLineEntry;
3901061da546Spatrick break;
3902061da546Spatrick
3903061da546Spatrick case N_SSYM:
3904061da546Spatrick // structure elt: name,,NO_SECT,type,struct_offset
3905061da546Spatrick type = eSymbolTypeVariableType;
3906061da546Spatrick break;
3907061da546Spatrick
3908061da546Spatrick case N_SO:
3909061da546Spatrick // source file name
3910061da546Spatrick type = eSymbolTypeSourceFile;
3911061da546Spatrick if (symbol_name == nullptr) {
3912061da546Spatrick add_nlist = false;
3913061da546Spatrick if (N_SO_index != UINT32_MAX) {
3914061da546Spatrick // Set the size of the N_SO to the terminating index of this
3915061da546Spatrick // N_SO so that we can always skip the entire N_SO if we need
3916061da546Spatrick // to navigate more quickly at the source level when parsing
3917061da546Spatrick // STABS
3918*f6aab3d8Srobert symbol_ptr = symtab.SymbolAtIndex(N_SO_index);
3919061da546Spatrick symbol_ptr->SetByteSize(sym_idx);
3920061da546Spatrick symbol_ptr->SetSizeIsSibling(true);
3921061da546Spatrick }
3922061da546Spatrick N_NSYM_indexes.clear();
3923061da546Spatrick N_INCL_indexes.clear();
3924061da546Spatrick N_BRAC_indexes.clear();
3925061da546Spatrick N_COMM_indexes.clear();
3926061da546Spatrick N_FUN_indexes.clear();
3927061da546Spatrick N_SO_index = UINT32_MAX;
3928061da546Spatrick } else {
3929061da546Spatrick // We use the current number of symbols in the symbol table in
3930061da546Spatrick // lieu of using nlist_idx in case we ever start trimming entries
3931061da546Spatrick // out
3932061da546Spatrick const bool N_SO_has_full_path = symbol_name[0] == '/';
3933061da546Spatrick if (N_SO_has_full_path) {
3934061da546Spatrick if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3935061da546Spatrick // We have two consecutive N_SO entries where the first
3936061da546Spatrick // contains a directory and the second contains a full path.
3937061da546Spatrick sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name),
3938061da546Spatrick false);
3939061da546Spatrick m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3940061da546Spatrick add_nlist = false;
3941061da546Spatrick } else {
3942061da546Spatrick // This is the first entry in a N_SO that contains a
3943061da546Spatrick // directory or a full path to the source file
3944061da546Spatrick N_SO_index = sym_idx;
3945061da546Spatrick }
3946061da546Spatrick } else if ((N_SO_index == sym_idx - 1) &&
3947061da546Spatrick ((sym_idx - 1) < num_syms)) {
3948061da546Spatrick // This is usually the second N_SO entry that contains just the
3949061da546Spatrick // filename, so here we combine it with the first one if we are
3950061da546Spatrick // minimizing the symbol table
3951061da546Spatrick const char *so_path =
3952dda28197Spatrick sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString();
3953061da546Spatrick if (so_path && so_path[0]) {
3954061da546Spatrick std::string full_so_path(so_path);
3955061da546Spatrick const size_t double_slash_pos = full_so_path.find("//");
3956061da546Spatrick if (double_slash_pos != std::string::npos) {
3957061da546Spatrick // The linker has been generating bad N_SO entries with
3958061da546Spatrick // doubled up paths in the format "%s%s" where the first
3959061da546Spatrick // string in the DW_AT_comp_dir, and the second is the
3960061da546Spatrick // directory for the source file so you end up with a path
3961061da546Spatrick // that looks like "/tmp/src//tmp/src/"
3962061da546Spatrick FileSpec so_dir(so_path);
3963061da546Spatrick if (!FileSystem::Instance().Exists(so_dir)) {
3964061da546Spatrick so_dir.SetFile(&full_so_path[double_slash_pos + 1],
3965061da546Spatrick FileSpec::Style::native);
3966061da546Spatrick if (FileSystem::Instance().Exists(so_dir)) {
3967061da546Spatrick // Trim off the incorrect path
3968061da546Spatrick full_so_path.erase(0, double_slash_pos + 1);
3969061da546Spatrick }
3970061da546Spatrick }
3971061da546Spatrick }
3972061da546Spatrick if (*full_so_path.rbegin() != '/')
3973061da546Spatrick full_so_path += '/';
3974061da546Spatrick full_so_path += symbol_name;
3975061da546Spatrick sym[sym_idx - 1].GetMangled().SetValue(
3976061da546Spatrick ConstString(full_so_path.c_str()), false);
3977061da546Spatrick add_nlist = false;
3978061da546Spatrick m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3979061da546Spatrick }
3980061da546Spatrick } else {
3981061da546Spatrick // This could be a relative path to a N_SO
3982061da546Spatrick N_SO_index = sym_idx;
3983061da546Spatrick }
3984061da546Spatrick }
3985061da546Spatrick break;
3986061da546Spatrick
3987061da546Spatrick case N_OSO:
3988061da546Spatrick // object file name: name,,0,0,st_mtime
3989061da546Spatrick type = eSymbolTypeObjectFile;
3990061da546Spatrick break;
3991061da546Spatrick
3992061da546Spatrick case N_LSYM:
3993061da546Spatrick // local sym: name,,NO_SECT,type,offset
3994061da546Spatrick type = eSymbolTypeLocal;
3995061da546Spatrick break;
3996061da546Spatrick
3997061da546Spatrick // INCL scopes
3998061da546Spatrick case N_BINCL:
3999061da546Spatrick // include file beginning: name,,NO_SECT,0,sum We use the current
4000061da546Spatrick // number of symbols in the symbol table in lieu of using nlist_idx
4001061da546Spatrick // in case we ever start trimming entries out
4002061da546Spatrick N_INCL_indexes.push_back(sym_idx);
4003061da546Spatrick type = eSymbolTypeScopeBegin;
4004061da546Spatrick break;
4005061da546Spatrick
4006061da546Spatrick case N_EINCL:
4007061da546Spatrick // include file end: name,,NO_SECT,0,0
4008061da546Spatrick // Set the size of the N_BINCL to the terminating index of this
4009061da546Spatrick // N_EINCL so that we can always skip the entire symbol if we need
4010061da546Spatrick // to navigate more quickly at the source level when parsing STABS
4011061da546Spatrick if (!N_INCL_indexes.empty()) {
4012*f6aab3d8Srobert symbol_ptr = symtab.SymbolAtIndex(N_INCL_indexes.back());
4013061da546Spatrick symbol_ptr->SetByteSize(sym_idx + 1);
4014061da546Spatrick symbol_ptr->SetSizeIsSibling(true);
4015061da546Spatrick N_INCL_indexes.pop_back();
4016061da546Spatrick }
4017061da546Spatrick type = eSymbolTypeScopeEnd;
4018061da546Spatrick break;
4019061da546Spatrick
4020061da546Spatrick case N_SOL:
4021061da546Spatrick // #included file name: name,,n_sect,0,address
4022061da546Spatrick type = eSymbolTypeHeaderFile;
4023061da546Spatrick
4024061da546Spatrick // We currently don't use the header files on darwin
4025061da546Spatrick add_nlist = false;
4026061da546Spatrick break;
4027061da546Spatrick
4028061da546Spatrick case N_PARAMS:
4029061da546Spatrick // compiler parameters: name,,NO_SECT,0,0
4030061da546Spatrick type = eSymbolTypeCompiler;
4031061da546Spatrick break;
4032061da546Spatrick
4033061da546Spatrick case N_VERSION:
4034061da546Spatrick // compiler version: name,,NO_SECT,0,0
4035061da546Spatrick type = eSymbolTypeCompiler;
4036061da546Spatrick break;
4037061da546Spatrick
4038061da546Spatrick case N_OLEVEL:
4039061da546Spatrick // compiler -O level: name,,NO_SECT,0,0
4040061da546Spatrick type = eSymbolTypeCompiler;
4041061da546Spatrick break;
4042061da546Spatrick
4043061da546Spatrick case N_PSYM:
4044061da546Spatrick // parameter: name,,NO_SECT,type,offset
4045061da546Spatrick type = eSymbolTypeVariable;
4046061da546Spatrick break;
4047061da546Spatrick
4048061da546Spatrick case N_ENTRY:
4049061da546Spatrick // alternate entry: name,,n_sect,linenumber,address
4050061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4051061da546Spatrick type = eSymbolTypeLineEntry;
4052061da546Spatrick break;
4053061da546Spatrick
4054061da546Spatrick // Left and Right Braces
4055061da546Spatrick case N_LBRAC:
4056061da546Spatrick // left bracket: 0,,NO_SECT,nesting level,address We use the
4057061da546Spatrick // current number of symbols in the symbol table in lieu of using
4058061da546Spatrick // nlist_idx in case we ever start trimming entries out
4059061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4060061da546Spatrick N_BRAC_indexes.push_back(sym_idx);
4061061da546Spatrick type = eSymbolTypeScopeBegin;
4062061da546Spatrick break;
4063061da546Spatrick
4064061da546Spatrick case N_RBRAC:
4065061da546Spatrick // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4066061da546Spatrick // the N_LBRAC to the terminating index of this N_RBRAC so that we
4067061da546Spatrick // can always skip the entire symbol if we need to navigate more
4068061da546Spatrick // quickly at the source level when parsing STABS
4069061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4070061da546Spatrick if (!N_BRAC_indexes.empty()) {
4071*f6aab3d8Srobert symbol_ptr = symtab.SymbolAtIndex(N_BRAC_indexes.back());
4072061da546Spatrick symbol_ptr->SetByteSize(sym_idx + 1);
4073061da546Spatrick symbol_ptr->SetSizeIsSibling(true);
4074061da546Spatrick N_BRAC_indexes.pop_back();
4075061da546Spatrick }
4076061da546Spatrick type = eSymbolTypeScopeEnd;
4077061da546Spatrick break;
4078061da546Spatrick
4079061da546Spatrick case N_EXCL:
4080061da546Spatrick // deleted include file: name,,NO_SECT,0,sum
4081061da546Spatrick type = eSymbolTypeHeaderFile;
4082061da546Spatrick break;
4083061da546Spatrick
4084061da546Spatrick // COMM scopes
4085061da546Spatrick case N_BCOMM:
4086061da546Spatrick // begin common: name,,NO_SECT,0,0
4087061da546Spatrick // We use the current number of symbols in the symbol table in lieu
4088061da546Spatrick // of using nlist_idx in case we ever start trimming entries out
4089061da546Spatrick type = eSymbolTypeScopeBegin;
4090061da546Spatrick N_COMM_indexes.push_back(sym_idx);
4091061da546Spatrick break;
4092061da546Spatrick
4093061da546Spatrick case N_ECOML:
4094061da546Spatrick // end common (local name): 0,,n_sect,0,address
4095061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4096*f6aab3d8Srobert [[fallthrough]];
4097061da546Spatrick
4098061da546Spatrick case N_ECOMM:
4099061da546Spatrick // end common: name,,n_sect,0,0
4100061da546Spatrick // Set the size of the N_BCOMM to the terminating index of this
4101061da546Spatrick // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4102061da546Spatrick // we need to navigate more quickly at the source level when
4103061da546Spatrick // parsing STABS
4104061da546Spatrick if (!N_COMM_indexes.empty()) {
4105*f6aab3d8Srobert symbol_ptr = symtab.SymbolAtIndex(N_COMM_indexes.back());
4106061da546Spatrick symbol_ptr->SetByteSize(sym_idx + 1);
4107061da546Spatrick symbol_ptr->SetSizeIsSibling(true);
4108061da546Spatrick N_COMM_indexes.pop_back();
4109061da546Spatrick }
4110061da546Spatrick type = eSymbolTypeScopeEnd;
4111061da546Spatrick break;
4112061da546Spatrick
4113061da546Spatrick case N_LENG:
4114061da546Spatrick // second stab entry with length information
4115061da546Spatrick type = eSymbolTypeAdditional;
4116061da546Spatrick break;
4117061da546Spatrick
4118061da546Spatrick default:
4119061da546Spatrick break;
4120061da546Spatrick }
4121061da546Spatrick } else {
4122061da546Spatrick uint8_t n_type = N_TYPE & nlist.n_type;
4123061da546Spatrick sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4124061da546Spatrick
4125061da546Spatrick switch (n_type) {
4126061da546Spatrick case N_INDR: {
4127061da546Spatrick const char *reexport_name_cstr = strtab_data.PeekCStr(nlist.n_value);
4128*f6aab3d8Srobert if (reexport_name_cstr && reexport_name_cstr[0] && symbol_name) {
4129061da546Spatrick type = eSymbolTypeReExported;
4130061da546Spatrick ConstString reexport_name(reexport_name_cstr +
4131061da546Spatrick ((reexport_name_cstr[0] == '_') ? 1 : 0));
4132061da546Spatrick sym[sym_idx].SetReExportedSymbolName(reexport_name);
4133061da546Spatrick set_value = false;
4134061da546Spatrick reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4135061da546Spatrick indirect_symbol_names.insert(
4136061da546Spatrick ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4137061da546Spatrick } else
4138061da546Spatrick type = eSymbolTypeUndefined;
4139061da546Spatrick } break;
4140061da546Spatrick
4141061da546Spatrick case N_UNDF:
4142061da546Spatrick if (symbol_name && symbol_name[0]) {
4143061da546Spatrick ConstString undefined_name(symbol_name +
4144061da546Spatrick ((symbol_name[0] == '_') ? 1 : 0));
4145061da546Spatrick undefined_name_to_desc[undefined_name] = nlist.n_desc;
4146061da546Spatrick }
4147*f6aab3d8Srobert [[fallthrough]];
4148061da546Spatrick
4149061da546Spatrick case N_PBUD:
4150061da546Spatrick type = eSymbolTypeUndefined;
4151061da546Spatrick break;
4152061da546Spatrick
4153061da546Spatrick case N_ABS:
4154061da546Spatrick type = eSymbolTypeAbsolute;
4155061da546Spatrick break;
4156061da546Spatrick
4157061da546Spatrick case N_SECT: {
4158061da546Spatrick symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4159061da546Spatrick
4160061da546Spatrick if (!symbol_section) {
4161061da546Spatrick // TODO: warn about this?
4162061da546Spatrick add_nlist = false;
4163061da546Spatrick break;
4164061da546Spatrick }
4165061da546Spatrick
4166061da546Spatrick if (TEXT_eh_frame_sectID == nlist.n_sect) {
4167061da546Spatrick type = eSymbolTypeException;
4168061da546Spatrick } else {
4169061da546Spatrick uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4170061da546Spatrick
4171061da546Spatrick switch (section_type) {
4172061da546Spatrick case S_CSTRING_LITERALS:
4173061da546Spatrick type = eSymbolTypeData;
4174061da546Spatrick break; // section with only literal C strings
4175061da546Spatrick case S_4BYTE_LITERALS:
4176061da546Spatrick type = eSymbolTypeData;
4177061da546Spatrick break; // section with only 4 byte literals
4178061da546Spatrick case S_8BYTE_LITERALS:
4179061da546Spatrick type = eSymbolTypeData;
4180061da546Spatrick break; // section with only 8 byte literals
4181061da546Spatrick case S_LITERAL_POINTERS:
4182061da546Spatrick type = eSymbolTypeTrampoline;
4183061da546Spatrick break; // section with only pointers to literals
4184061da546Spatrick case S_NON_LAZY_SYMBOL_POINTERS:
4185061da546Spatrick type = eSymbolTypeTrampoline;
4186061da546Spatrick break; // section with only non-lazy symbol pointers
4187061da546Spatrick case S_LAZY_SYMBOL_POINTERS:
4188061da546Spatrick type = eSymbolTypeTrampoline;
4189061da546Spatrick break; // section with only lazy symbol pointers
4190061da546Spatrick case S_SYMBOL_STUBS:
4191061da546Spatrick type = eSymbolTypeTrampoline;
4192061da546Spatrick break; // section with only symbol stubs, byte size of stub in
4193061da546Spatrick // the reserved2 field
4194061da546Spatrick case S_MOD_INIT_FUNC_POINTERS:
4195061da546Spatrick type = eSymbolTypeCode;
4196061da546Spatrick break; // section with only function pointers for initialization
4197061da546Spatrick case S_MOD_TERM_FUNC_POINTERS:
4198061da546Spatrick type = eSymbolTypeCode;
4199061da546Spatrick break; // section with only function pointers for termination
4200061da546Spatrick case S_INTERPOSING:
4201061da546Spatrick type = eSymbolTypeTrampoline;
4202061da546Spatrick break; // section with only pairs of function pointers for
4203061da546Spatrick // interposing
4204061da546Spatrick case S_16BYTE_LITERALS:
4205061da546Spatrick type = eSymbolTypeData;
4206061da546Spatrick break; // section with only 16 byte literals
4207061da546Spatrick case S_DTRACE_DOF:
4208061da546Spatrick type = eSymbolTypeInstrumentation;
4209061da546Spatrick break;
4210061da546Spatrick case S_LAZY_DYLIB_SYMBOL_POINTERS:
4211061da546Spatrick type = eSymbolTypeTrampoline;
4212061da546Spatrick break;
4213061da546Spatrick default:
4214061da546Spatrick switch (symbol_section->GetType()) {
4215061da546Spatrick case lldb::eSectionTypeCode:
4216061da546Spatrick type = eSymbolTypeCode;
4217061da546Spatrick break;
4218061da546Spatrick case eSectionTypeData:
4219061da546Spatrick case eSectionTypeDataCString: // Inlined C string data
4220061da546Spatrick case eSectionTypeDataCStringPointers: // Pointers to C string
4221061da546Spatrick // data
4222061da546Spatrick case eSectionTypeDataSymbolAddress: // Address of a symbol in
4223061da546Spatrick // the symbol table
4224061da546Spatrick case eSectionTypeData4:
4225061da546Spatrick case eSectionTypeData8:
4226061da546Spatrick case eSectionTypeData16:
4227061da546Spatrick type = eSymbolTypeData;
4228061da546Spatrick break;
4229061da546Spatrick default:
4230061da546Spatrick break;
4231061da546Spatrick }
4232061da546Spatrick break;
4233061da546Spatrick }
4234061da546Spatrick
4235061da546Spatrick if (type == eSymbolTypeInvalid) {
4236061da546Spatrick const char *symbol_sect_name =
4237061da546Spatrick symbol_section->GetName().AsCString();
4238061da546Spatrick if (symbol_section->IsDescendant(text_section_sp.get())) {
4239061da546Spatrick if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4240061da546Spatrick S_ATTR_SELF_MODIFYING_CODE |
4241061da546Spatrick S_ATTR_SOME_INSTRUCTIONS))
4242061da546Spatrick type = eSymbolTypeData;
4243061da546Spatrick else
4244061da546Spatrick type = eSymbolTypeCode;
4245061da546Spatrick } else if (symbol_section->IsDescendant(data_section_sp.get()) ||
4246061da546Spatrick symbol_section->IsDescendant(
4247061da546Spatrick data_dirty_section_sp.get()) ||
4248061da546Spatrick symbol_section->IsDescendant(
4249061da546Spatrick data_const_section_sp.get())) {
4250061da546Spatrick if (symbol_sect_name &&
4251061da546Spatrick ::strstr(symbol_sect_name, "__objc") == symbol_sect_name) {
4252061da546Spatrick type = eSymbolTypeRuntime;
4253061da546Spatrick
4254061da546Spatrick if (symbol_name) {
4255061da546Spatrick llvm::StringRef symbol_name_ref(symbol_name);
4256061da546Spatrick if (symbol_name_ref.startswith("_OBJC_")) {
4257061da546Spatrick llvm::StringRef g_objc_v2_prefix_class(
4258061da546Spatrick "_OBJC_CLASS_$_");
4259061da546Spatrick llvm::StringRef g_objc_v2_prefix_metaclass(
4260061da546Spatrick "_OBJC_METACLASS_$_");
4261061da546Spatrick llvm::StringRef g_objc_v2_prefix_ivar(
4262061da546Spatrick "_OBJC_IVAR_$_");
4263061da546Spatrick if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
4264061da546Spatrick symbol_name_non_abi_mangled = symbol_name + 1;
4265061da546Spatrick symbol_name =
4266061da546Spatrick symbol_name + g_objc_v2_prefix_class.size();
4267061da546Spatrick type = eSymbolTypeObjCClass;
4268061da546Spatrick demangled_is_synthesized = true;
4269061da546Spatrick } else if (symbol_name_ref.startswith(
4270061da546Spatrick g_objc_v2_prefix_metaclass)) {
4271061da546Spatrick symbol_name_non_abi_mangled = symbol_name + 1;
4272061da546Spatrick symbol_name =
4273061da546Spatrick symbol_name + g_objc_v2_prefix_metaclass.size();
4274061da546Spatrick type = eSymbolTypeObjCMetaClass;
4275061da546Spatrick demangled_is_synthesized = true;
4276061da546Spatrick } else if (symbol_name_ref.startswith(
4277061da546Spatrick g_objc_v2_prefix_ivar)) {
4278061da546Spatrick symbol_name_non_abi_mangled = symbol_name + 1;
4279061da546Spatrick symbol_name =
4280061da546Spatrick symbol_name + g_objc_v2_prefix_ivar.size();
4281061da546Spatrick type = eSymbolTypeObjCIVar;
4282061da546Spatrick demangled_is_synthesized = true;
4283061da546Spatrick }
4284061da546Spatrick }
4285061da546Spatrick }
4286061da546Spatrick } else if (symbol_sect_name &&
4287061da546Spatrick ::strstr(symbol_sect_name, "__gcc_except_tab") ==
4288061da546Spatrick symbol_sect_name) {
4289061da546Spatrick type = eSymbolTypeException;
4290061da546Spatrick } else {
4291061da546Spatrick type = eSymbolTypeData;
4292061da546Spatrick }
4293061da546Spatrick } else if (symbol_sect_name &&
4294061da546Spatrick ::strstr(symbol_sect_name, "__IMPORT") ==
4295061da546Spatrick symbol_sect_name) {
4296061da546Spatrick type = eSymbolTypeTrampoline;
4297061da546Spatrick } else if (symbol_section->IsDescendant(objc_section_sp.get())) {
4298061da546Spatrick type = eSymbolTypeRuntime;
4299061da546Spatrick if (symbol_name && symbol_name[0] == '.') {
4300061da546Spatrick llvm::StringRef symbol_name_ref(symbol_name);
4301061da546Spatrick llvm::StringRef g_objc_v1_prefix_class(
4302061da546Spatrick ".objc_class_name_");
4303061da546Spatrick if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) {
4304061da546Spatrick symbol_name_non_abi_mangled = symbol_name;
4305061da546Spatrick symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4306061da546Spatrick type = eSymbolTypeObjCClass;
4307061da546Spatrick demangled_is_synthesized = true;
4308061da546Spatrick }
4309061da546Spatrick }
4310061da546Spatrick }
4311061da546Spatrick }
4312061da546Spatrick }
4313061da546Spatrick } break;
4314061da546Spatrick }
4315061da546Spatrick }
4316061da546Spatrick
4317061da546Spatrick if (!add_nlist) {
4318061da546Spatrick sym[sym_idx].Clear();
4319061da546Spatrick return true;
4320061da546Spatrick }
4321061da546Spatrick
4322061da546Spatrick uint64_t symbol_value = nlist.n_value;
4323061da546Spatrick
4324061da546Spatrick if (symbol_name_non_abi_mangled) {
4325061da546Spatrick sym[sym_idx].GetMangled().SetMangledName(
4326061da546Spatrick ConstString(symbol_name_non_abi_mangled));
4327061da546Spatrick sym[sym_idx].GetMangled().SetDemangledName(ConstString(symbol_name));
4328061da546Spatrick } else {
4329061da546Spatrick bool symbol_name_is_mangled = false;
4330061da546Spatrick
4331061da546Spatrick if (symbol_name && symbol_name[0] == '_') {
4332061da546Spatrick symbol_name_is_mangled = symbol_name[1] == '_';
4333061da546Spatrick symbol_name++; // Skip the leading underscore
4334061da546Spatrick }
4335061da546Spatrick
4336061da546Spatrick if (symbol_name) {
4337061da546Spatrick ConstString const_symbol_name(symbol_name);
4338061da546Spatrick sym[sym_idx].GetMangled().SetValue(const_symbol_name,
4339061da546Spatrick symbol_name_is_mangled);
4340061da546Spatrick }
4341061da546Spatrick }
4342061da546Spatrick
4343061da546Spatrick if (is_gsym) {
4344dda28197Spatrick const char *gsym_name = sym[sym_idx]
4345061da546Spatrick .GetMangled()
4346dda28197Spatrick .GetName(Mangled::ePreferMangled)
4347061da546Spatrick .GetCString();
4348061da546Spatrick if (gsym_name)
4349061da546Spatrick N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4350061da546Spatrick }
4351061da546Spatrick
4352061da546Spatrick if (symbol_section) {
4353061da546Spatrick const addr_t section_file_addr = symbol_section->GetFileAddress();
4354061da546Spatrick if (symbol_byte_size == 0 && function_starts_count > 0) {
4355061da546Spatrick addr_t symbol_lookup_file_addr = nlist.n_value;
4356061da546Spatrick // Do an exact address match for non-ARM addresses, else get the
4357061da546Spatrick // closest since the symbol might be a thumb symbol which has an
4358061da546Spatrick // address with bit zero set.
4359061da546Spatrick FunctionStarts::Entry *func_start_entry =
4360061da546Spatrick function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
4361061da546Spatrick if (is_arm && func_start_entry) {
4362061da546Spatrick // Verify that the function start address is the symbol address
4363061da546Spatrick // (ARM) or the symbol address + 1 (thumb).
4364061da546Spatrick if (func_start_entry->addr != symbol_lookup_file_addr &&
4365061da546Spatrick func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4366061da546Spatrick // Not the right entry, NULL it out...
4367061da546Spatrick func_start_entry = nullptr;
4368061da546Spatrick }
4369061da546Spatrick }
4370061da546Spatrick if (func_start_entry) {
4371061da546Spatrick func_start_entry->data = true;
4372061da546Spatrick
4373061da546Spatrick addr_t symbol_file_addr = func_start_entry->addr;
4374061da546Spatrick if (is_arm)
4375061da546Spatrick symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4376061da546Spatrick
4377061da546Spatrick const FunctionStarts::Entry *next_func_start_entry =
4378061da546Spatrick function_starts.FindNextEntry(func_start_entry);
4379061da546Spatrick const addr_t section_end_file_addr =
4380061da546Spatrick section_file_addr + symbol_section->GetByteSize();
4381061da546Spatrick if (next_func_start_entry) {
4382061da546Spatrick addr_t next_symbol_file_addr = next_func_start_entry->addr;
4383061da546Spatrick // Be sure the clear the Thumb address bit when we calculate the
4384061da546Spatrick // size from the current and next address
4385061da546Spatrick if (is_arm)
4386061da546Spatrick next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4387061da546Spatrick symbol_byte_size = std::min<lldb::addr_t>(
4388061da546Spatrick next_symbol_file_addr - symbol_file_addr,
4389061da546Spatrick section_end_file_addr - symbol_file_addr);
4390061da546Spatrick } else {
4391061da546Spatrick symbol_byte_size = section_end_file_addr - symbol_file_addr;
4392061da546Spatrick }
4393061da546Spatrick }
4394061da546Spatrick }
4395061da546Spatrick symbol_value -= section_file_addr;
4396061da546Spatrick }
4397061da546Spatrick
4398061da546Spatrick if (!is_debug) {
4399061da546Spatrick if (type == eSymbolTypeCode) {
4400061da546Spatrick // See if we can find a N_FUN entry for any code symbols. If we do
4401061da546Spatrick // find a match, and the name matches, then we can merge the two into
4402061da546Spatrick // just the function symbol to avoid duplicate entries in the symbol
4403061da546Spatrick // table.
4404061da546Spatrick std::pair<ValueToSymbolIndexMap::const_iterator,
4405061da546Spatrick ValueToSymbolIndexMap::const_iterator>
4406061da546Spatrick range;
4407061da546Spatrick range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4408061da546Spatrick if (range.first != range.second) {
4409061da546Spatrick for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4410061da546Spatrick pos != range.second; ++pos) {
4411dda28197Spatrick if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) ==
4412061da546Spatrick sym[pos->second].GetMangled().GetName(
4413dda28197Spatrick Mangled::ePreferMangled)) {
4414061da546Spatrick m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4415061da546Spatrick // We just need the flags from the linker symbol, so put these
4416061da546Spatrick // flags into the N_FUN flags to avoid duplicate symbols in the
4417061da546Spatrick // symbol table.
4418061da546Spatrick sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4419061da546Spatrick sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4420061da546Spatrick if (resolver_addresses.find(nlist.n_value) !=
4421061da546Spatrick resolver_addresses.end())
4422061da546Spatrick sym[pos->second].SetType(eSymbolTypeResolver);
4423061da546Spatrick sym[sym_idx].Clear();
4424061da546Spatrick return true;
4425061da546Spatrick }
4426061da546Spatrick }
4427061da546Spatrick } else {
4428061da546Spatrick if (resolver_addresses.find(nlist.n_value) !=
4429061da546Spatrick resolver_addresses.end())
4430061da546Spatrick type = eSymbolTypeResolver;
4431061da546Spatrick }
4432061da546Spatrick } else if (type == eSymbolTypeData || type == eSymbolTypeObjCClass ||
4433061da546Spatrick type == eSymbolTypeObjCMetaClass ||
4434061da546Spatrick type == eSymbolTypeObjCIVar) {
4435061da546Spatrick // See if we can find a N_STSYM entry for any data symbols. If we do
4436061da546Spatrick // find a match, and the name matches, then we can merge the two into
4437061da546Spatrick // just the Static symbol to avoid duplicate entries in the symbol
4438061da546Spatrick // table.
4439061da546Spatrick std::pair<ValueToSymbolIndexMap::const_iterator,
4440061da546Spatrick ValueToSymbolIndexMap::const_iterator>
4441061da546Spatrick range;
4442061da546Spatrick range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4443061da546Spatrick if (range.first != range.second) {
4444061da546Spatrick for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4445061da546Spatrick pos != range.second; ++pos) {
4446dda28197Spatrick if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) ==
4447061da546Spatrick sym[pos->second].GetMangled().GetName(
4448dda28197Spatrick Mangled::ePreferMangled)) {
4449061da546Spatrick m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4450061da546Spatrick // We just need the flags from the linker symbol, so put these
4451061da546Spatrick // flags into the N_STSYM flags to avoid duplicate symbols in
4452061da546Spatrick // the symbol table.
4453061da546Spatrick sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4454061da546Spatrick sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4455061da546Spatrick sym[sym_idx].Clear();
4456061da546Spatrick return true;
4457061da546Spatrick }
4458061da546Spatrick }
4459061da546Spatrick } else {
4460061da546Spatrick // Combine N_GSYM stab entries with the non stab symbol.
4461061da546Spatrick const char *gsym_name = sym[sym_idx]
4462061da546Spatrick .GetMangled()
4463dda28197Spatrick .GetName(Mangled::ePreferMangled)
4464061da546Spatrick .GetCString();
4465061da546Spatrick if (gsym_name) {
4466061da546Spatrick ConstNameToSymbolIndexMap::const_iterator pos =
4467061da546Spatrick N_GSYM_name_to_sym_idx.find(gsym_name);
4468061da546Spatrick if (pos != N_GSYM_name_to_sym_idx.end()) {
4469061da546Spatrick const uint32_t GSYM_sym_idx = pos->second;
4470061da546Spatrick m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
4471061da546Spatrick // Copy the address, because often the N_GSYM address has an
4472061da546Spatrick // invalid address of zero when the global is a common symbol.
4473061da546Spatrick sym[GSYM_sym_idx].GetAddressRef().SetSection(symbol_section);
4474061da546Spatrick sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4475be691f3bSpatrick add_symbol_addr(
4476dda28197Spatrick sym[GSYM_sym_idx].GetAddress().GetFileAddress());
4477061da546Spatrick // We just need the flags from the linker symbol, so put these
4478061da546Spatrick // flags into the N_GSYM flags to avoid duplicate symbols in
4479061da546Spatrick // the symbol table.
4480061da546Spatrick sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4481061da546Spatrick sym[sym_idx].Clear();
4482061da546Spatrick return true;
4483061da546Spatrick }
4484061da546Spatrick }
4485061da546Spatrick }
4486061da546Spatrick }
4487061da546Spatrick }
4488061da546Spatrick
4489061da546Spatrick sym[sym_idx].SetID(nlist_idx);
4490061da546Spatrick sym[sym_idx].SetType(type);
4491061da546Spatrick if (set_value) {
4492061da546Spatrick sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4493061da546Spatrick sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4494be691f3bSpatrick if (symbol_section)
4495be691f3bSpatrick add_symbol_addr(sym[sym_idx].GetAddress().GetFileAddress());
4496061da546Spatrick }
4497061da546Spatrick sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4498061da546Spatrick if (nlist.n_desc & N_WEAK_REF)
4499061da546Spatrick sym[sym_idx].SetIsWeak(true);
4500061da546Spatrick
4501061da546Spatrick if (symbol_byte_size > 0)
4502061da546Spatrick sym[sym_idx].SetByteSize(symbol_byte_size);
4503061da546Spatrick
4504061da546Spatrick if (demangled_is_synthesized)
4505061da546Spatrick sym[sym_idx].SetDemangledNameIsSynthesized(true);
4506061da546Spatrick
4507061da546Spatrick ++sym_idx;
4508061da546Spatrick return true;
4509061da546Spatrick };
4510061da546Spatrick
4511061da546Spatrick // First parse all the nlists but don't process them yet. See the next
4512061da546Spatrick // comment for an explanation why.
4513061da546Spatrick std::vector<struct nlist_64> nlists;
4514061da546Spatrick nlists.reserve(symtab_load_command.nsyms);
4515061da546Spatrick for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
4516061da546Spatrick if (auto nlist =
4517061da546Spatrick ParseNList(nlist_data, nlist_data_offset, nlist_byte_size))
4518061da546Spatrick nlists.push_back(*nlist);
4519061da546Spatrick else
4520061da546Spatrick break;
4521061da546Spatrick }
4522061da546Spatrick
4523061da546Spatrick // Now parse all the debug symbols. This is needed to merge non-debug
4524061da546Spatrick // symbols in the next step. Non-debug symbols are always coalesced into
4525061da546Spatrick // the debug symbol. Doing this in one step would mean that some symbols
4526061da546Spatrick // won't be merged.
4527061da546Spatrick nlist_idx = 0;
4528061da546Spatrick for (auto &nlist : nlists) {
4529061da546Spatrick if (!ParseSymbolLambda(nlist, nlist_idx++, DebugSymbols))
4530061da546Spatrick break;
4531061da546Spatrick }
4532061da546Spatrick
4533061da546Spatrick // Finally parse all the non debug symbols.
4534061da546Spatrick nlist_idx = 0;
4535061da546Spatrick for (auto &nlist : nlists) {
4536061da546Spatrick if (!ParseSymbolLambda(nlist, nlist_idx++, NonDebugSymbols))
4537061da546Spatrick break;
4538061da546Spatrick }
4539061da546Spatrick
4540061da546Spatrick for (const auto &pos : reexport_shlib_needs_fixup) {
4541061da546Spatrick const auto undef_pos = undefined_name_to_desc.find(pos.second);
4542061da546Spatrick if (undef_pos != undefined_name_to_desc.end()) {
4543061da546Spatrick const uint8_t dylib_ordinal =
4544061da546Spatrick llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4545061da546Spatrick if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4546061da546Spatrick sym[pos.first].SetReExportedSymbolSharedLibrary(
4547061da546Spatrick dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
4548061da546Spatrick }
4549061da546Spatrick }
4550061da546Spatrick }
4551061da546Spatrick
4552dda28197Spatrick // Count how many trie symbols we'll add to the symbol table
4553dda28197Spatrick int trie_symbol_table_augment_count = 0;
4554dda28197Spatrick for (auto &e : external_sym_trie_entries) {
4555dda28197Spatrick if (symbols_added.find(e.entry.address) == symbols_added.end())
4556dda28197Spatrick trie_symbol_table_augment_count++;
4557dda28197Spatrick }
4558dda28197Spatrick
4559dda28197Spatrick if (num_syms < sym_idx + trie_symbol_table_augment_count) {
4560dda28197Spatrick num_syms = sym_idx + trie_symbol_table_augment_count;
4561*f6aab3d8Srobert sym = symtab.Resize(num_syms);
4562dda28197Spatrick }
4563061da546Spatrick uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4564061da546Spatrick
4565dda28197Spatrick // Add symbols from the trie to the symbol table.
4566dda28197Spatrick for (auto &e : external_sym_trie_entries) {
4567*f6aab3d8Srobert if (symbols_added.contains(e.entry.address))
4568dda28197Spatrick continue;
4569dda28197Spatrick
4570dda28197Spatrick // Find the section that this trie address is in, use that to annotate
4571dda28197Spatrick // symbol type as we add the trie address and name to the symbol table.
4572dda28197Spatrick Address symbol_addr;
4573dda28197Spatrick if (module_sp->ResolveFileAddress(e.entry.address, symbol_addr)) {
4574dda28197Spatrick SectionSP symbol_section(symbol_addr.GetSection());
4575dda28197Spatrick const char *symbol_name = e.entry.name.GetCString();
4576dda28197Spatrick bool demangled_is_synthesized = false;
4577dda28197Spatrick SymbolType type =
4578dda28197Spatrick GetSymbolType(symbol_name, demangled_is_synthesized, text_section_sp,
4579dda28197Spatrick data_section_sp, data_dirty_section_sp,
4580dda28197Spatrick data_const_section_sp, symbol_section);
4581dda28197Spatrick
4582dda28197Spatrick sym[sym_idx].SetType(type);
4583dda28197Spatrick if (symbol_section) {
4584dda28197Spatrick sym[sym_idx].SetID(synthetic_sym_id++);
4585dda28197Spatrick sym[sym_idx].GetMangled().SetMangledName(ConstString(symbol_name));
4586dda28197Spatrick if (demangled_is_synthesized)
4587dda28197Spatrick sym[sym_idx].SetDemangledNameIsSynthesized(true);
4588dda28197Spatrick sym[sym_idx].SetIsSynthetic(true);
4589dda28197Spatrick sym[sym_idx].SetExternal(true);
4590dda28197Spatrick sym[sym_idx].GetAddressRef() = symbol_addr;
4591be691f3bSpatrick add_symbol_addr(symbol_addr.GetFileAddress());
4592dda28197Spatrick if (e.entry.flags & TRIE_SYMBOL_IS_THUMB)
4593dda28197Spatrick sym[sym_idx].SetFlags(MACHO_NLIST_ARM_SYMBOL_IS_THUMB);
4594dda28197Spatrick ++sym_idx;
4595dda28197Spatrick }
4596dda28197Spatrick }
4597dda28197Spatrick }
4598dda28197Spatrick
4599061da546Spatrick if (function_starts_count > 0) {
4600061da546Spatrick uint32_t num_synthetic_function_symbols = 0;
4601061da546Spatrick for (i = 0; i < function_starts_count; ++i) {
4602dda28197Spatrick if (symbols_added.find(function_starts.GetEntryRef(i).addr) ==
4603dda28197Spatrick symbols_added.end())
4604061da546Spatrick ++num_synthetic_function_symbols;
4605061da546Spatrick }
4606061da546Spatrick
4607061da546Spatrick if (num_synthetic_function_symbols > 0) {
4608061da546Spatrick if (num_syms < sym_idx + num_synthetic_function_symbols) {
4609061da546Spatrick num_syms = sym_idx + num_synthetic_function_symbols;
4610*f6aab3d8Srobert sym = symtab.Resize(num_syms);
4611061da546Spatrick }
4612061da546Spatrick for (i = 0; i < function_starts_count; ++i) {
4613061da546Spatrick const FunctionStarts::Entry *func_start_entry =
4614061da546Spatrick function_starts.GetEntryAtIndex(i);
4615dda28197Spatrick if (symbols_added.find(func_start_entry->addr) == symbols_added.end()) {
4616061da546Spatrick addr_t symbol_file_addr = func_start_entry->addr;
4617061da546Spatrick uint32_t symbol_flags = 0;
4618dda28197Spatrick if (func_start_entry->data)
4619061da546Spatrick symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4620061da546Spatrick Address symbol_addr;
4621061da546Spatrick if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
4622061da546Spatrick SectionSP symbol_section(symbol_addr.GetSection());
4623061da546Spatrick uint32_t symbol_byte_size = 0;
4624061da546Spatrick if (symbol_section) {
4625061da546Spatrick const addr_t section_file_addr = symbol_section->GetFileAddress();
4626061da546Spatrick const FunctionStarts::Entry *next_func_start_entry =
4627061da546Spatrick function_starts.FindNextEntry(func_start_entry);
4628061da546Spatrick const addr_t section_end_file_addr =
4629061da546Spatrick section_file_addr + symbol_section->GetByteSize();
4630061da546Spatrick if (next_func_start_entry) {
4631061da546Spatrick addr_t next_symbol_file_addr = next_func_start_entry->addr;
4632061da546Spatrick if (is_arm)
4633061da546Spatrick next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4634061da546Spatrick symbol_byte_size = std::min<lldb::addr_t>(
4635061da546Spatrick next_symbol_file_addr - symbol_file_addr,
4636061da546Spatrick section_end_file_addr - symbol_file_addr);
4637061da546Spatrick } else {
4638061da546Spatrick symbol_byte_size = section_end_file_addr - symbol_file_addr;
4639061da546Spatrick }
4640061da546Spatrick sym[sym_idx].SetID(synthetic_sym_id++);
4641be691f3bSpatrick // Don't set the name for any synthetic symbols, the Symbol
4642be691f3bSpatrick // object will generate one if needed when the name is accessed
4643be691f3bSpatrick // via accessors.
4644be691f3bSpatrick sym[sym_idx].GetMangled().SetDemangledName(ConstString());
4645061da546Spatrick sym[sym_idx].SetType(eSymbolTypeCode);
4646061da546Spatrick sym[sym_idx].SetIsSynthetic(true);
4647061da546Spatrick sym[sym_idx].GetAddressRef() = symbol_addr;
4648be691f3bSpatrick add_symbol_addr(symbol_addr.GetFileAddress());
4649061da546Spatrick if (symbol_flags)
4650061da546Spatrick sym[sym_idx].SetFlags(symbol_flags);
4651061da546Spatrick if (symbol_byte_size)
4652061da546Spatrick sym[sym_idx].SetByteSize(symbol_byte_size);
4653061da546Spatrick ++sym_idx;
4654061da546Spatrick }
4655061da546Spatrick }
4656061da546Spatrick }
4657061da546Spatrick }
4658061da546Spatrick }
4659061da546Spatrick }
4660061da546Spatrick
4661061da546Spatrick // Trim our symbols down to just what we ended up with after removing any
4662061da546Spatrick // symbols.
4663061da546Spatrick if (sym_idx < num_syms) {
4664061da546Spatrick num_syms = sym_idx;
4665*f6aab3d8Srobert sym = symtab.Resize(num_syms);
4666061da546Spatrick }
4667061da546Spatrick
4668061da546Spatrick // Now synthesize indirect symbols
4669061da546Spatrick if (m_dysymtab.nindirectsyms != 0) {
4670061da546Spatrick if (indirect_symbol_index_data.GetByteSize()) {
4671061da546Spatrick NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4672061da546Spatrick m_nlist_idx_to_sym_idx.end();
4673061da546Spatrick
4674061da546Spatrick for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4675061da546Spatrick ++sect_idx) {
4676061da546Spatrick if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4677061da546Spatrick S_SYMBOL_STUBS) {
4678061da546Spatrick uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2;
4679061da546Spatrick if (symbol_stub_byte_size == 0)
4680061da546Spatrick continue;
4681061da546Spatrick
4682061da546Spatrick const uint32_t num_symbol_stubs =
4683061da546Spatrick m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4684061da546Spatrick
4685061da546Spatrick if (num_symbol_stubs == 0)
4686061da546Spatrick continue;
4687061da546Spatrick
4688061da546Spatrick const uint32_t symbol_stub_index_offset =
4689061da546Spatrick m_mach_sections[sect_idx].reserved1;
4690061da546Spatrick for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx) {
4691061da546Spatrick const uint32_t symbol_stub_index =
4692061da546Spatrick symbol_stub_index_offset + stub_idx;
4693061da546Spatrick const lldb::addr_t symbol_stub_addr =
4694061da546Spatrick m_mach_sections[sect_idx].addr +
4695061da546Spatrick (stub_idx * symbol_stub_byte_size);
4696061da546Spatrick lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4697061da546Spatrick if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4698061da546Spatrick symbol_stub_offset, 4)) {
4699061da546Spatrick const uint32_t stub_sym_id =
4700061da546Spatrick indirect_symbol_index_data.GetU32(&symbol_stub_offset);
4701061da546Spatrick if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4702061da546Spatrick continue;
4703061da546Spatrick
4704061da546Spatrick NListIndexToSymbolIndexMap::const_iterator index_pos =
4705061da546Spatrick m_nlist_idx_to_sym_idx.find(stub_sym_id);
4706061da546Spatrick Symbol *stub_symbol = nullptr;
4707061da546Spatrick if (index_pos != end_index_pos) {
4708061da546Spatrick // We have a remapping from the original nlist index to a
4709061da546Spatrick // current symbol index, so just look this up by index
4710*f6aab3d8Srobert stub_symbol = symtab.SymbolAtIndex(index_pos->second);
4711061da546Spatrick } else {
4712061da546Spatrick // We need to lookup a symbol using the original nlist symbol
4713061da546Spatrick // index since this index is coming from the S_SYMBOL_STUBS
4714*f6aab3d8Srobert stub_symbol = symtab.FindSymbolByID(stub_sym_id);
4715061da546Spatrick }
4716061da546Spatrick
4717061da546Spatrick if (stub_symbol) {
4718061da546Spatrick Address so_addr(symbol_stub_addr, section_list);
4719061da546Spatrick
4720061da546Spatrick if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4721061da546Spatrick // Change the external symbol into a trampoline that makes
4722061da546Spatrick // sense These symbols were N_UNDF N_EXT, and are useless
4723061da546Spatrick // to us, so we can re-use them so we don't have to make up
4724061da546Spatrick // a synthetic symbol for no good reason.
4725061da546Spatrick if (resolver_addresses.find(symbol_stub_addr) ==
4726061da546Spatrick resolver_addresses.end())
4727061da546Spatrick stub_symbol->SetType(eSymbolTypeTrampoline);
4728061da546Spatrick else
4729061da546Spatrick stub_symbol->SetType(eSymbolTypeResolver);
4730061da546Spatrick stub_symbol->SetExternal(false);
4731061da546Spatrick stub_symbol->GetAddressRef() = so_addr;
4732061da546Spatrick stub_symbol->SetByteSize(symbol_stub_byte_size);
4733061da546Spatrick } else {
4734061da546Spatrick // Make a synthetic symbol to describe the trampoline stub
4735061da546Spatrick Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4736061da546Spatrick if (sym_idx >= num_syms) {
4737*f6aab3d8Srobert sym = symtab.Resize(++num_syms);
4738061da546Spatrick stub_symbol = nullptr; // this pointer no longer valid
4739061da546Spatrick }
4740061da546Spatrick sym[sym_idx].SetID(synthetic_sym_id++);
4741061da546Spatrick sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4742061da546Spatrick if (resolver_addresses.find(symbol_stub_addr) ==
4743061da546Spatrick resolver_addresses.end())
4744061da546Spatrick sym[sym_idx].SetType(eSymbolTypeTrampoline);
4745061da546Spatrick else
4746061da546Spatrick sym[sym_idx].SetType(eSymbolTypeResolver);
4747061da546Spatrick sym[sym_idx].SetIsSynthetic(true);
4748061da546Spatrick sym[sym_idx].GetAddressRef() = so_addr;
4749be691f3bSpatrick add_symbol_addr(so_addr.GetFileAddress());
4750061da546Spatrick sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4751061da546Spatrick ++sym_idx;
4752061da546Spatrick }
4753061da546Spatrick } else {
4754061da546Spatrick if (log)
4755061da546Spatrick log->Warning("symbol stub referencing symbol table symbol "
4756061da546Spatrick "%u that isn't in our minimal symbol table, "
4757061da546Spatrick "fix this!!!",
4758061da546Spatrick stub_sym_id);
4759061da546Spatrick }
4760061da546Spatrick }
4761061da546Spatrick }
4762061da546Spatrick }
4763061da546Spatrick }
4764061da546Spatrick }
4765061da546Spatrick }
4766061da546Spatrick
4767dda28197Spatrick if (!reexport_trie_entries.empty()) {
4768dda28197Spatrick for (const auto &e : reexport_trie_entries) {
4769061da546Spatrick if (e.entry.import_name) {
4770061da546Spatrick // Only add indirect symbols from the Trie entries if we didn't have
4771061da546Spatrick // a N_INDR nlist entry for this already
4772061da546Spatrick if (indirect_symbol_names.find(e.entry.name) ==
4773061da546Spatrick indirect_symbol_names.end()) {
4774061da546Spatrick // Make a synthetic symbol to describe re-exported symbol.
4775061da546Spatrick if (sym_idx >= num_syms)
4776*f6aab3d8Srobert sym = symtab.Resize(++num_syms);
4777061da546Spatrick sym[sym_idx].SetID(synthetic_sym_id++);
4778061da546Spatrick sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4779061da546Spatrick sym[sym_idx].SetType(eSymbolTypeReExported);
4780061da546Spatrick sym[sym_idx].SetIsSynthetic(true);
4781061da546Spatrick sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4782061da546Spatrick if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4783061da546Spatrick sym[sym_idx].SetReExportedSymbolSharedLibrary(
4784061da546Spatrick dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
4785061da546Spatrick }
4786061da546Spatrick ++sym_idx;
4787061da546Spatrick }
4788061da546Spatrick }
4789061da546Spatrick }
4790061da546Spatrick }
4791061da546Spatrick }
4792061da546Spatrick
4793061da546Spatrick void ObjectFileMachO::Dump(Stream *s) {
4794061da546Spatrick ModuleSP module_sp(GetModule());
4795061da546Spatrick if (module_sp) {
4796061da546Spatrick std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4797061da546Spatrick s->Printf("%p: ", static_cast<void *>(this));
4798061da546Spatrick s->Indent();
4799061da546Spatrick if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4800061da546Spatrick s->PutCString("ObjectFileMachO64");
4801061da546Spatrick else
4802061da546Spatrick s->PutCString("ObjectFileMachO32");
4803061da546Spatrick
4804061da546Spatrick *s << ", file = '" << m_file;
4805061da546Spatrick ModuleSpecList all_specs;
4806061da546Spatrick ModuleSpec base_spec;
4807061da546Spatrick GetAllArchSpecs(m_header, m_data, MachHeaderSizeFromMagic(m_header.magic),
4808061da546Spatrick base_spec, all_specs);
4809061da546Spatrick for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
4810061da546Spatrick *s << "', triple";
4811061da546Spatrick if (e)
4812061da546Spatrick s->Printf("[%d]", i);
4813061da546Spatrick *s << " = ";
4814061da546Spatrick *s << all_specs.GetModuleSpecRefAtIndex(i)
4815061da546Spatrick .GetArchitecture()
4816061da546Spatrick .GetTriple()
4817061da546Spatrick .getTriple();
4818061da546Spatrick }
4819061da546Spatrick *s << "\n";
4820061da546Spatrick SectionList *sections = GetSectionList();
4821061da546Spatrick if (sections)
4822dda28197Spatrick sections->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
4823dda28197Spatrick UINT32_MAX);
4824061da546Spatrick
4825061da546Spatrick if (m_symtab_up)
4826061da546Spatrick m_symtab_up->Dump(s, nullptr, eSortOrderNone);
4827061da546Spatrick }
4828061da546Spatrick }
4829061da546Spatrick
4830061da546Spatrick UUID ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4831061da546Spatrick const lldb_private::DataExtractor &data,
4832061da546Spatrick lldb::offset_t lc_offset) {
4833061da546Spatrick uint32_t i;
4834be691f3bSpatrick llvm::MachO::uuid_command load_cmd;
4835061da546Spatrick
4836061da546Spatrick lldb::offset_t offset = lc_offset;
4837061da546Spatrick for (i = 0; i < header.ncmds; ++i) {
4838061da546Spatrick const lldb::offset_t cmd_offset = offset;
4839061da546Spatrick if (data.GetU32(&offset, &load_cmd, 2) == nullptr)
4840061da546Spatrick break;
4841061da546Spatrick
4842061da546Spatrick if (load_cmd.cmd == LC_UUID) {
4843061da546Spatrick const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4844061da546Spatrick
4845061da546Spatrick if (uuid_bytes) {
4846061da546Spatrick // OpenCL on Mac OS X uses the same UUID for each of its object files.
4847061da546Spatrick // We pretend these object files have no UUID to prevent crashing.
4848061da546Spatrick
4849061da546Spatrick const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4850061da546Spatrick 0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4851061da546Spatrick 0xbb, 0x14, 0xf0, 0x0d};
4852061da546Spatrick
4853061da546Spatrick if (!memcmp(uuid_bytes, opencl_uuid, 16))
4854061da546Spatrick return UUID();
4855061da546Spatrick
4856*f6aab3d8Srobert return UUID(uuid_bytes, 16);
4857061da546Spatrick }
4858061da546Spatrick return UUID();
4859061da546Spatrick }
4860061da546Spatrick offset = cmd_offset + load_cmd.cmdsize;
4861061da546Spatrick }
4862061da546Spatrick return UUID();
4863061da546Spatrick }
4864061da546Spatrick
4865061da546Spatrick static llvm::StringRef GetOSName(uint32_t cmd) {
4866061da546Spatrick switch (cmd) {
4867061da546Spatrick case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
4868061da546Spatrick return llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4869061da546Spatrick case llvm::MachO::LC_VERSION_MIN_MACOSX:
4870061da546Spatrick return llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4871061da546Spatrick case llvm::MachO::LC_VERSION_MIN_TVOS:
4872061da546Spatrick return llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4873061da546Spatrick case llvm::MachO::LC_VERSION_MIN_WATCHOS:
4874061da546Spatrick return llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4875061da546Spatrick default:
4876061da546Spatrick llvm_unreachable("unexpected LC_VERSION load command");
4877061da546Spatrick }
4878061da546Spatrick }
4879061da546Spatrick
4880061da546Spatrick namespace {
4881061da546Spatrick struct OSEnv {
4882061da546Spatrick llvm::StringRef os_type;
4883061da546Spatrick llvm::StringRef environment;
4884061da546Spatrick OSEnv(uint32_t cmd) {
4885061da546Spatrick switch (cmd) {
4886061da546Spatrick case llvm::MachO::PLATFORM_MACOS:
4887061da546Spatrick os_type = llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4888061da546Spatrick return;
4889061da546Spatrick case llvm::MachO::PLATFORM_IOS:
4890061da546Spatrick os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4891061da546Spatrick return;
4892061da546Spatrick case llvm::MachO::PLATFORM_TVOS:
4893061da546Spatrick os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4894061da546Spatrick return;
4895061da546Spatrick case llvm::MachO::PLATFORM_WATCHOS:
4896061da546Spatrick os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4897061da546Spatrick return;
4898*f6aab3d8Srobert // TODO: add BridgeOS & DriverKit once in llvm/lib/Support/Triple.cpp
4899*f6aab3d8Srobert // NEED_BRIDGEOS_TRIPLE
4900*f6aab3d8Srobert // case llvm::MachO::PLATFORM_BRIDGEOS:
4901*f6aab3d8Srobert // os_type = llvm::Triple::getOSTypeName(llvm::Triple::BridgeOS);
4902*f6aab3d8Srobert // return;
4903*f6aab3d8Srobert // case llvm::MachO::PLATFORM_DRIVERKIT:
4904*f6aab3d8Srobert // os_type = llvm::Triple::getOSTypeName(llvm::Triple::DriverKit);
4905*f6aab3d8Srobert // return;
4906061da546Spatrick case llvm::MachO::PLATFORM_MACCATALYST:
4907061da546Spatrick os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4908061da546Spatrick environment = llvm::Triple::getEnvironmentTypeName(llvm::Triple::MacABI);
4909061da546Spatrick return;
4910061da546Spatrick case llvm::MachO::PLATFORM_IOSSIMULATOR:
4911061da546Spatrick os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4912061da546Spatrick environment =
4913061da546Spatrick llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4914061da546Spatrick return;
4915061da546Spatrick case llvm::MachO::PLATFORM_TVOSSIMULATOR:
4916061da546Spatrick os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4917061da546Spatrick environment =
4918061da546Spatrick llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4919061da546Spatrick return;
4920061da546Spatrick case llvm::MachO::PLATFORM_WATCHOSSIMULATOR:
4921061da546Spatrick os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4922061da546Spatrick environment =
4923061da546Spatrick llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4924061da546Spatrick return;
4925061da546Spatrick default: {
4926*f6aab3d8Srobert Log *log(GetLog(LLDBLog::Symbols | LLDBLog::Process));
4927061da546Spatrick LLDB_LOGF(log, "unsupported platform in LC_BUILD_VERSION");
4928061da546Spatrick }
4929061da546Spatrick }
4930061da546Spatrick }
4931061da546Spatrick };
4932061da546Spatrick
4933061da546Spatrick struct MinOS {
4934061da546Spatrick uint32_t major_version, minor_version, patch_version;
4935061da546Spatrick MinOS(uint32_t version)
4936061da546Spatrick : major_version(version >> 16), minor_version((version >> 8) & 0xffu),
4937061da546Spatrick patch_version(version & 0xffu) {}
4938061da546Spatrick };
4939061da546Spatrick } // namespace
4940061da546Spatrick
4941061da546Spatrick void ObjectFileMachO::GetAllArchSpecs(const llvm::MachO::mach_header &header,
4942061da546Spatrick const lldb_private::DataExtractor &data,
4943061da546Spatrick lldb::offset_t lc_offset,
4944061da546Spatrick ModuleSpec &base_spec,
4945061da546Spatrick lldb_private::ModuleSpecList &all_specs) {
4946061da546Spatrick auto &base_arch = base_spec.GetArchitecture();
4947061da546Spatrick base_arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
4948061da546Spatrick if (!base_arch.IsValid())
4949061da546Spatrick return;
4950061da546Spatrick
4951061da546Spatrick bool found_any = false;
4952061da546Spatrick auto add_triple = [&](const llvm::Triple &triple) {
4953061da546Spatrick auto spec = base_spec;
4954061da546Spatrick spec.GetArchitecture().GetTriple() = triple;
4955061da546Spatrick if (spec.GetArchitecture().IsValid()) {
4956061da546Spatrick spec.GetUUID() = ObjectFileMachO::GetUUID(header, data, lc_offset);
4957061da546Spatrick all_specs.Append(spec);
4958061da546Spatrick found_any = true;
4959061da546Spatrick }
4960061da546Spatrick };
4961061da546Spatrick
4962061da546Spatrick // Set OS to an unspecified unknown or a "*" so it can match any OS
4963061da546Spatrick llvm::Triple base_triple = base_arch.GetTriple();
4964061da546Spatrick base_triple.setOS(llvm::Triple::UnknownOS);
4965061da546Spatrick base_triple.setOSName(llvm::StringRef());
4966061da546Spatrick
4967061da546Spatrick if (header.filetype == MH_PRELOAD) {
4968061da546Spatrick if (header.cputype == CPU_TYPE_ARM) {
4969061da546Spatrick // If this is a 32-bit arm binary, and it's a standalone binary, force
4970061da546Spatrick // the Vendor to Apple so we don't accidentally pick up the generic
4971061da546Spatrick // armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the
4972061da546Spatrick // frame pointer register; most other armv7 ABIs use a combination of
4973061da546Spatrick // r7 and r11.
4974061da546Spatrick base_triple.setVendor(llvm::Triple::Apple);
4975061da546Spatrick } else {
4976061da546Spatrick // Set vendor to an unspecified unknown or a "*" so it can match any
4977061da546Spatrick // vendor This is required for correct behavior of EFI debugging on
4978061da546Spatrick // x86_64
4979061da546Spatrick base_triple.setVendor(llvm::Triple::UnknownVendor);
4980061da546Spatrick base_triple.setVendorName(llvm::StringRef());
4981061da546Spatrick }
4982061da546Spatrick return add_triple(base_triple);
4983061da546Spatrick }
4984061da546Spatrick
4985be691f3bSpatrick llvm::MachO::load_command load_cmd;
4986061da546Spatrick
4987061da546Spatrick // See if there is an LC_VERSION_MIN_* load command that can give
4988061da546Spatrick // us the OS type.
4989061da546Spatrick lldb::offset_t offset = lc_offset;
4990061da546Spatrick for (uint32_t i = 0; i < header.ncmds; ++i) {
4991061da546Spatrick const lldb::offset_t cmd_offset = offset;
4992*f6aab3d8Srobert if (data.GetU32(&offset, &load_cmd, 2) == nullptr)
4993061da546Spatrick break;
4994061da546Spatrick
4995be691f3bSpatrick llvm::MachO::version_min_command version_min;
4996061da546Spatrick switch (load_cmd.cmd) {
4997061da546Spatrick case llvm::MachO::LC_VERSION_MIN_MACOSX:
4998be691f3bSpatrick case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
4999061da546Spatrick case llvm::MachO::LC_VERSION_MIN_TVOS:
5000061da546Spatrick case llvm::MachO::LC_VERSION_MIN_WATCHOS: {
5001061da546Spatrick if (load_cmd.cmdsize != sizeof(version_min))
5002061da546Spatrick break;
5003061da546Spatrick if (data.ExtractBytes(cmd_offset, sizeof(version_min),
5004061da546Spatrick data.GetByteOrder(), &version_min) == 0)
5005061da546Spatrick break;
5006061da546Spatrick MinOS min_os(version_min.version);
5007061da546Spatrick llvm::SmallString<32> os_name;
5008061da546Spatrick llvm::raw_svector_ostream os(os_name);
5009061da546Spatrick os << GetOSName(load_cmd.cmd) << min_os.major_version << '.'
5010061da546Spatrick << min_os.minor_version << '.' << min_os.patch_version;
5011061da546Spatrick
5012061da546Spatrick auto triple = base_triple;
5013061da546Spatrick triple.setOSName(os.str());
5014be691f3bSpatrick
5015be691f3bSpatrick // Disambiguate legacy simulator platforms.
5016be691f3bSpatrick if (load_cmd.cmd != llvm::MachO::LC_VERSION_MIN_MACOSX &&
5017be691f3bSpatrick (base_triple.getArch() == llvm::Triple::x86_64 ||
5018be691f3bSpatrick base_triple.getArch() == llvm::Triple::x86)) {
5019be691f3bSpatrick // The combination of legacy LC_VERSION_MIN load command and
5020be691f3bSpatrick // x86 architecture always indicates a simulator environment.
5021be691f3bSpatrick // The combination of LC_VERSION_MIN and arm architecture only
5022be691f3bSpatrick // appears for native binaries. Back-deploying simulator
5023be691f3bSpatrick // binaries on Apple Silicon Macs use the modern unambigous
5024be691f3bSpatrick // LC_BUILD_VERSION load commands; no special handling required.
5025be691f3bSpatrick triple.setEnvironment(llvm::Triple::Simulator);
5026be691f3bSpatrick }
5027061da546Spatrick add_triple(triple);
5028061da546Spatrick break;
5029061da546Spatrick }
5030061da546Spatrick default:
5031061da546Spatrick break;
5032061da546Spatrick }
5033061da546Spatrick
5034061da546Spatrick offset = cmd_offset + load_cmd.cmdsize;
5035061da546Spatrick }
5036061da546Spatrick
5037061da546Spatrick // See if there are LC_BUILD_VERSION load commands that can give
5038061da546Spatrick // us the OS type.
5039061da546Spatrick offset = lc_offset;
5040061da546Spatrick for (uint32_t i = 0; i < header.ncmds; ++i) {
5041061da546Spatrick const lldb::offset_t cmd_offset = offset;
5042*f6aab3d8Srobert if (data.GetU32(&offset, &load_cmd, 2) == nullptr)
5043061da546Spatrick break;
5044061da546Spatrick
5045061da546Spatrick do {
5046061da546Spatrick if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) {
5047be691f3bSpatrick llvm::MachO::build_version_command build_version;
5048061da546Spatrick if (load_cmd.cmdsize < sizeof(build_version)) {
5049061da546Spatrick // Malformed load command.
5050061da546Spatrick break;
5051061da546Spatrick }
5052061da546Spatrick if (data.ExtractBytes(cmd_offset, sizeof(build_version),
5053061da546Spatrick data.GetByteOrder(), &build_version) == 0)
5054061da546Spatrick break;
5055061da546Spatrick MinOS min_os(build_version.minos);
5056061da546Spatrick OSEnv os_env(build_version.platform);
5057061da546Spatrick llvm::SmallString<16> os_name;
5058061da546Spatrick llvm::raw_svector_ostream os(os_name);
5059061da546Spatrick os << os_env.os_type << min_os.major_version << '.'
5060061da546Spatrick << min_os.minor_version << '.' << min_os.patch_version;
5061061da546Spatrick auto triple = base_triple;
5062061da546Spatrick triple.setOSName(os.str());
5063061da546Spatrick os_name.clear();
5064061da546Spatrick if (!os_env.environment.empty())
5065061da546Spatrick triple.setEnvironmentName(os_env.environment);
5066061da546Spatrick add_triple(triple);
5067061da546Spatrick }
5068*f6aab3d8Srobert } while (false);
5069061da546Spatrick offset = cmd_offset + load_cmd.cmdsize;
5070061da546Spatrick }
5071061da546Spatrick
5072061da546Spatrick if (!found_any) {
5073061da546Spatrick add_triple(base_triple);
5074061da546Spatrick }
5075061da546Spatrick }
5076061da546Spatrick
5077061da546Spatrick ArchSpec ObjectFileMachO::GetArchitecture(
5078061da546Spatrick ModuleSP module_sp, const llvm::MachO::mach_header &header,
5079061da546Spatrick const lldb_private::DataExtractor &data, lldb::offset_t lc_offset) {
5080061da546Spatrick ModuleSpecList all_specs;
5081061da546Spatrick ModuleSpec base_spec;
5082061da546Spatrick GetAllArchSpecs(header, data, MachHeaderSizeFromMagic(header.magic),
5083061da546Spatrick base_spec, all_specs);
5084061da546Spatrick
5085061da546Spatrick // If the object file offers multiple alternative load commands,
5086061da546Spatrick // pick the one that matches the module.
5087061da546Spatrick if (module_sp) {
5088061da546Spatrick const ArchSpec &module_arch = module_sp->GetArchitecture();
5089061da546Spatrick for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
5090061da546Spatrick ArchSpec mach_arch =
5091061da546Spatrick all_specs.GetModuleSpecRefAtIndex(i).GetArchitecture();
5092061da546Spatrick if (module_arch.IsCompatibleMatch(mach_arch))
5093061da546Spatrick return mach_arch;
5094061da546Spatrick }
5095061da546Spatrick }
5096061da546Spatrick
5097061da546Spatrick // Return the first arch we found.
5098061da546Spatrick if (all_specs.GetSize() == 0)
5099061da546Spatrick return {};
5100061da546Spatrick return all_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
5101061da546Spatrick }
5102061da546Spatrick
5103061da546Spatrick UUID ObjectFileMachO::GetUUID() {
5104061da546Spatrick ModuleSP module_sp(GetModule());
5105061da546Spatrick if (module_sp) {
5106061da546Spatrick std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5107061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5108061da546Spatrick return GetUUID(m_header, m_data, offset);
5109061da546Spatrick }
5110061da546Spatrick return UUID();
5111061da546Spatrick }
5112061da546Spatrick
5113061da546Spatrick uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) {
5114061da546Spatrick uint32_t count = 0;
5115061da546Spatrick ModuleSP module_sp(GetModule());
5116061da546Spatrick if (module_sp) {
5117061da546Spatrick std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5118be691f3bSpatrick llvm::MachO::load_command load_cmd;
5119061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5120061da546Spatrick std::vector<std::string> rpath_paths;
5121061da546Spatrick std::vector<std::string> rpath_relative_paths;
5122061da546Spatrick std::vector<std::string> at_exec_relative_paths;
5123061da546Spatrick uint32_t i;
5124061da546Spatrick for (i = 0; i < m_header.ncmds; ++i) {
5125061da546Spatrick const uint32_t cmd_offset = offset;
5126061da546Spatrick if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
5127061da546Spatrick break;
5128061da546Spatrick
5129061da546Spatrick switch (load_cmd.cmd) {
5130061da546Spatrick case LC_RPATH:
5131061da546Spatrick case LC_LOAD_DYLIB:
5132061da546Spatrick case LC_LOAD_WEAK_DYLIB:
5133061da546Spatrick case LC_REEXPORT_DYLIB:
5134061da546Spatrick case LC_LOAD_DYLINKER:
5135061da546Spatrick case LC_LOADFVMLIB:
5136061da546Spatrick case LC_LOAD_UPWARD_DYLIB: {
5137061da546Spatrick uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
5138061da546Spatrick const char *path = m_data.PeekCStr(name_offset);
5139061da546Spatrick if (path) {
5140061da546Spatrick if (load_cmd.cmd == LC_RPATH)
5141061da546Spatrick rpath_paths.push_back(path);
5142061da546Spatrick else {
5143061da546Spatrick if (path[0] == '@') {
5144061da546Spatrick if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
5145061da546Spatrick rpath_relative_paths.push_back(path + strlen("@rpath"));
5146061da546Spatrick else if (strncmp(path, "@executable_path",
5147061da546Spatrick strlen("@executable_path")) == 0)
5148061da546Spatrick at_exec_relative_paths.push_back(path +
5149061da546Spatrick strlen("@executable_path"));
5150061da546Spatrick } else {
5151061da546Spatrick FileSpec file_spec(path);
5152061da546Spatrick if (files.AppendIfUnique(file_spec))
5153061da546Spatrick count++;
5154061da546Spatrick }
5155061da546Spatrick }
5156061da546Spatrick }
5157061da546Spatrick } break;
5158061da546Spatrick
5159061da546Spatrick default:
5160061da546Spatrick break;
5161061da546Spatrick }
5162061da546Spatrick offset = cmd_offset + load_cmd.cmdsize;
5163061da546Spatrick }
5164061da546Spatrick
5165061da546Spatrick FileSpec this_file_spec(m_file);
5166061da546Spatrick FileSystem::Instance().Resolve(this_file_spec);
5167061da546Spatrick
5168061da546Spatrick if (!rpath_paths.empty()) {
5169061da546Spatrick // Fixup all LC_RPATH values to be absolute paths
5170061da546Spatrick std::string loader_path("@loader_path");
5171061da546Spatrick std::string executable_path("@executable_path");
5172061da546Spatrick for (auto &rpath : rpath_paths) {
5173dda28197Spatrick if (llvm::StringRef(rpath).startswith(loader_path)) {
5174061da546Spatrick rpath.erase(0, loader_path.size());
5175061da546Spatrick rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5176dda28197Spatrick } else if (llvm::StringRef(rpath).startswith(executable_path)) {
5177061da546Spatrick rpath.erase(0, executable_path.size());
5178061da546Spatrick rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5179061da546Spatrick }
5180061da546Spatrick }
5181061da546Spatrick
5182061da546Spatrick for (const auto &rpath_relative_path : rpath_relative_paths) {
5183061da546Spatrick for (const auto &rpath : rpath_paths) {
5184061da546Spatrick std::string path = rpath;
5185061da546Spatrick path += rpath_relative_path;
5186061da546Spatrick // It is OK to resolve this path because we must find a file on disk
5187061da546Spatrick // for us to accept it anyway if it is rpath relative.
5188061da546Spatrick FileSpec file_spec(path);
5189061da546Spatrick FileSystem::Instance().Resolve(file_spec);
5190061da546Spatrick if (FileSystem::Instance().Exists(file_spec) &&
5191061da546Spatrick files.AppendIfUnique(file_spec)) {
5192061da546Spatrick count++;
5193061da546Spatrick break;
5194061da546Spatrick }
5195061da546Spatrick }
5196061da546Spatrick }
5197061da546Spatrick }
5198061da546Spatrick
5199061da546Spatrick // We may have @executable_paths but no RPATHS. Figure those out here.
5200061da546Spatrick // Only do this if this object file is the executable. We have no way to
5201061da546Spatrick // get back to the actual executable otherwise, so we won't get the right
5202061da546Spatrick // path.
5203061da546Spatrick if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
5204061da546Spatrick FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
5205061da546Spatrick for (const auto &at_exec_relative_path : at_exec_relative_paths) {
5206061da546Spatrick FileSpec file_spec =
5207061da546Spatrick exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
5208061da546Spatrick if (FileSystem::Instance().Exists(file_spec) &&
5209061da546Spatrick files.AppendIfUnique(file_spec))
5210061da546Spatrick count++;
5211061da546Spatrick }
5212061da546Spatrick }
5213061da546Spatrick }
5214061da546Spatrick return count;
5215061da546Spatrick }
5216061da546Spatrick
5217061da546Spatrick lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
5218061da546Spatrick // If the object file is not an executable it can't hold the entry point.
5219061da546Spatrick // m_entry_point_address is initialized to an invalid address, so we can just
5220061da546Spatrick // return that. If m_entry_point_address is valid it means we've found it
5221061da546Spatrick // already, so return the cached value.
5222061da546Spatrick
5223061da546Spatrick if ((!IsExecutable() && !IsDynamicLoader()) ||
5224061da546Spatrick m_entry_point_address.IsValid()) {
5225061da546Spatrick return m_entry_point_address;
5226061da546Spatrick }
5227061da546Spatrick
5228061da546Spatrick // Otherwise, look for the UnixThread or Thread command. The data for the
5229061da546Spatrick // Thread command is given in /usr/include/mach-o.h, but it is basically:
5230061da546Spatrick //
5231061da546Spatrick // uint32_t flavor - this is the flavor argument you would pass to
5232061da546Spatrick // thread_get_state
5233061da546Spatrick // uint32_t count - this is the count of longs in the thread state data
5234061da546Spatrick // struct XXX_thread_state state - this is the structure from
5235061da546Spatrick // <machine/thread_status.h> corresponding to the flavor.
5236061da546Spatrick // <repeat this trio>
5237061da546Spatrick //
5238061da546Spatrick // So we just keep reading the various register flavors till we find the GPR
5239061da546Spatrick // one, then read the PC out of there.
5240061da546Spatrick // FIXME: We will need to have a "RegisterContext data provider" class at some
5241061da546Spatrick // point that can get all the registers
5242061da546Spatrick // out of data in this form & attach them to a given thread. That should
5243061da546Spatrick // underlie the MacOS X User process plugin, and we'll also need it for the
5244061da546Spatrick // MacOS X Core File process plugin. When we have that we can also use it
5245061da546Spatrick // here.
5246061da546Spatrick //
5247061da546Spatrick // For now we hard-code the offsets and flavors we need:
5248061da546Spatrick //
5249061da546Spatrick //
5250061da546Spatrick
5251061da546Spatrick ModuleSP module_sp(GetModule());
5252061da546Spatrick if (module_sp) {
5253061da546Spatrick std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5254be691f3bSpatrick llvm::MachO::load_command load_cmd;
5255061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5256061da546Spatrick uint32_t i;
5257061da546Spatrick lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
5258061da546Spatrick bool done = false;
5259061da546Spatrick
5260061da546Spatrick for (i = 0; i < m_header.ncmds; ++i) {
5261061da546Spatrick const lldb::offset_t cmd_offset = offset;
5262061da546Spatrick if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
5263061da546Spatrick break;
5264061da546Spatrick
5265061da546Spatrick switch (load_cmd.cmd) {
5266061da546Spatrick case LC_UNIXTHREAD:
5267061da546Spatrick case LC_THREAD: {
5268061da546Spatrick while (offset < cmd_offset + load_cmd.cmdsize) {
5269061da546Spatrick uint32_t flavor = m_data.GetU32(&offset);
5270061da546Spatrick uint32_t count = m_data.GetU32(&offset);
5271061da546Spatrick if (count == 0) {
5272061da546Spatrick // We've gotten off somehow, log and exit;
5273061da546Spatrick return m_entry_point_address;
5274061da546Spatrick }
5275061da546Spatrick
5276061da546Spatrick switch (m_header.cputype) {
5277061da546Spatrick case llvm::MachO::CPU_TYPE_ARM:
5278061da546Spatrick if (flavor == 1 ||
5279061da546Spatrick flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32
5280061da546Spatrick // from mach/arm/thread_status.h
5281061da546Spatrick {
5282061da546Spatrick offset += 60; // This is the offset of pc in the GPR thread state
5283061da546Spatrick // data structure.
5284061da546Spatrick start_address = m_data.GetU32(&offset);
5285061da546Spatrick done = true;
5286061da546Spatrick }
5287061da546Spatrick break;
5288061da546Spatrick case llvm::MachO::CPU_TYPE_ARM64:
5289061da546Spatrick case llvm::MachO::CPU_TYPE_ARM64_32:
5290061da546Spatrick if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
5291061da546Spatrick {
5292061da546Spatrick offset += 256; // This is the offset of pc in the GPR thread state
5293061da546Spatrick // data structure.
5294061da546Spatrick start_address = m_data.GetU64(&offset);
5295061da546Spatrick done = true;
5296061da546Spatrick }
5297061da546Spatrick break;
5298061da546Spatrick case llvm::MachO::CPU_TYPE_I386:
5299061da546Spatrick if (flavor ==
5300061da546Spatrick 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
5301061da546Spatrick {
5302061da546Spatrick offset += 40; // This is the offset of eip in the GPR thread state
5303061da546Spatrick // data structure.
5304061da546Spatrick start_address = m_data.GetU32(&offset);
5305061da546Spatrick done = true;
5306061da546Spatrick }
5307061da546Spatrick break;
5308061da546Spatrick case llvm::MachO::CPU_TYPE_X86_64:
5309061da546Spatrick if (flavor ==
5310061da546Spatrick 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
5311061da546Spatrick {
5312061da546Spatrick offset += 16 * 8; // This is the offset of rip in the GPR thread
5313061da546Spatrick // state data structure.
5314061da546Spatrick start_address = m_data.GetU64(&offset);
5315061da546Spatrick done = true;
5316061da546Spatrick }
5317061da546Spatrick break;
5318061da546Spatrick default:
5319061da546Spatrick return m_entry_point_address;
5320061da546Spatrick }
5321061da546Spatrick // Haven't found the GPR flavor yet, skip over the data for this
5322061da546Spatrick // flavor:
5323061da546Spatrick if (done)
5324061da546Spatrick break;
5325061da546Spatrick offset += count * 4;
5326061da546Spatrick }
5327061da546Spatrick } break;
5328061da546Spatrick case LC_MAIN: {
5329061da546Spatrick ConstString text_segment_name("__TEXT");
5330061da546Spatrick uint64_t entryoffset = m_data.GetU64(&offset);
5331061da546Spatrick SectionSP text_segment_sp =
5332061da546Spatrick GetSectionList()->FindSectionByName(text_segment_name);
5333061da546Spatrick if (text_segment_sp) {
5334061da546Spatrick done = true;
5335061da546Spatrick start_address = text_segment_sp->GetFileAddress() + entryoffset;
5336061da546Spatrick }
5337061da546Spatrick } break;
5338061da546Spatrick
5339061da546Spatrick default:
5340061da546Spatrick break;
5341061da546Spatrick }
5342061da546Spatrick if (done)
5343061da546Spatrick break;
5344061da546Spatrick
5345061da546Spatrick // Go to the next load command:
5346061da546Spatrick offset = cmd_offset + load_cmd.cmdsize;
5347061da546Spatrick }
5348061da546Spatrick
5349061da546Spatrick if (start_address == LLDB_INVALID_ADDRESS && IsDynamicLoader()) {
5350061da546Spatrick if (GetSymtab()) {
5351061da546Spatrick Symbol *dyld_start_sym = GetSymtab()->FindFirstSymbolWithNameAndType(
5352061da546Spatrick ConstString("_dyld_start"), SymbolType::eSymbolTypeCode,
5353061da546Spatrick Symtab::eDebugAny, Symtab::eVisibilityAny);
5354061da546Spatrick if (dyld_start_sym && dyld_start_sym->GetAddress().IsValid()) {
5355061da546Spatrick start_address = dyld_start_sym->GetAddress().GetFileAddress();
5356061da546Spatrick }
5357061da546Spatrick }
5358061da546Spatrick }
5359061da546Spatrick
5360061da546Spatrick if (start_address != LLDB_INVALID_ADDRESS) {
5361061da546Spatrick // We got the start address from the load commands, so now resolve that
5362061da546Spatrick // address in the sections of this ObjectFile:
5363061da546Spatrick if (!m_entry_point_address.ResolveAddressUsingFileSections(
5364061da546Spatrick start_address, GetSectionList())) {
5365061da546Spatrick m_entry_point_address.Clear();
5366061da546Spatrick }
5367061da546Spatrick } else {
5368061da546Spatrick // We couldn't read the UnixThread load command - maybe it wasn't there.
5369061da546Spatrick // As a fallback look for the "start" symbol in the main executable.
5370061da546Spatrick
5371061da546Spatrick ModuleSP module_sp(GetModule());
5372061da546Spatrick
5373061da546Spatrick if (module_sp) {
5374061da546Spatrick SymbolContextList contexts;
5375061da546Spatrick SymbolContext context;
5376061da546Spatrick module_sp->FindSymbolsWithNameAndType(ConstString("start"),
5377061da546Spatrick eSymbolTypeCode, contexts);
5378061da546Spatrick if (contexts.GetSize()) {
5379061da546Spatrick if (contexts.GetContextAtIndex(0, context))
5380061da546Spatrick m_entry_point_address = context.symbol->GetAddress();
5381061da546Spatrick }
5382061da546Spatrick }
5383061da546Spatrick }
5384061da546Spatrick }
5385061da546Spatrick
5386061da546Spatrick return m_entry_point_address;
5387061da546Spatrick }
5388061da546Spatrick
5389061da546Spatrick lldb_private::Address ObjectFileMachO::GetBaseAddress() {
5390061da546Spatrick lldb_private::Address header_addr;
5391061da546Spatrick SectionList *section_list = GetSectionList();
5392061da546Spatrick if (section_list) {
5393061da546Spatrick SectionSP text_segment_sp(
5394061da546Spatrick section_list->FindSectionByName(GetSegmentNameTEXT()));
5395061da546Spatrick if (text_segment_sp) {
5396061da546Spatrick header_addr.SetSection(text_segment_sp);
5397061da546Spatrick header_addr.SetOffset(0);
5398061da546Spatrick }
5399061da546Spatrick }
5400061da546Spatrick return header_addr;
5401061da546Spatrick }
5402061da546Spatrick
5403061da546Spatrick uint32_t ObjectFileMachO::GetNumThreadContexts() {
5404061da546Spatrick ModuleSP module_sp(GetModule());
5405061da546Spatrick if (module_sp) {
5406061da546Spatrick std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5407061da546Spatrick if (!m_thread_context_offsets_valid) {
5408061da546Spatrick m_thread_context_offsets_valid = true;
5409061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5410061da546Spatrick FileRangeArray::Entry file_range;
5411be691f3bSpatrick llvm::MachO::thread_command thread_cmd;
5412061da546Spatrick for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5413061da546Spatrick const uint32_t cmd_offset = offset;
5414061da546Spatrick if (m_data.GetU32(&offset, &thread_cmd, 2) == nullptr)
5415061da546Spatrick break;
5416061da546Spatrick
5417061da546Spatrick if (thread_cmd.cmd == LC_THREAD) {
5418061da546Spatrick file_range.SetRangeBase(offset);
5419061da546Spatrick file_range.SetByteSize(thread_cmd.cmdsize - 8);
5420061da546Spatrick m_thread_context_offsets.Append(file_range);
5421061da546Spatrick }
5422061da546Spatrick offset = cmd_offset + thread_cmd.cmdsize;
5423061da546Spatrick }
5424061da546Spatrick }
5425061da546Spatrick }
5426061da546Spatrick return m_thread_context_offsets.GetSize();
5427061da546Spatrick }
5428061da546Spatrick
5429061da546Spatrick std::string ObjectFileMachO::GetIdentifierString() {
5430061da546Spatrick std::string result;
5431061da546Spatrick ModuleSP module_sp(GetModule());
5432061da546Spatrick if (module_sp) {
5433061da546Spatrick std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5434061da546Spatrick
5435061da546Spatrick // First, look over the load commands for an LC_NOTE load command with
5436061da546Spatrick // data_owner string "kern ver str" & use that if found.
5437061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5438061da546Spatrick for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5439061da546Spatrick const uint32_t cmd_offset = offset;
5440*f6aab3d8Srobert llvm::MachO::load_command lc = {};
5441061da546Spatrick if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5442061da546Spatrick break;
5443061da546Spatrick if (lc.cmd == LC_NOTE) {
5444061da546Spatrick char data_owner[17];
5445061da546Spatrick m_data.CopyData(offset, 16, data_owner);
5446061da546Spatrick data_owner[16] = '\0';
5447061da546Spatrick offset += 16;
5448061da546Spatrick uint64_t fileoff = m_data.GetU64_unchecked(&offset);
5449061da546Spatrick uint64_t size = m_data.GetU64_unchecked(&offset);
5450061da546Spatrick
5451061da546Spatrick // "kern ver str" has a uint32_t version and then a nul terminated
5452061da546Spatrick // c-string.
5453061da546Spatrick if (strcmp("kern ver str", data_owner) == 0) {
5454061da546Spatrick offset = fileoff;
5455061da546Spatrick uint32_t version;
5456061da546Spatrick if (m_data.GetU32(&offset, &version, 1) != nullptr) {
5457061da546Spatrick if (version == 1) {
5458061da546Spatrick uint32_t strsize = size - sizeof(uint32_t);
5459061da546Spatrick char *buf = (char *)malloc(strsize);
5460061da546Spatrick if (buf) {
5461061da546Spatrick m_data.CopyData(offset, strsize, buf);
5462061da546Spatrick buf[strsize - 1] = '\0';
5463061da546Spatrick result = buf;
5464061da546Spatrick if (buf)
5465061da546Spatrick free(buf);
5466061da546Spatrick return result;
5467061da546Spatrick }
5468061da546Spatrick }
5469061da546Spatrick }
5470061da546Spatrick }
5471061da546Spatrick }
5472061da546Spatrick offset = cmd_offset + lc.cmdsize;
5473061da546Spatrick }
5474061da546Spatrick
5475061da546Spatrick // Second, make a pass over the load commands looking for an obsolete
5476061da546Spatrick // LC_IDENT load command.
5477061da546Spatrick offset = MachHeaderSizeFromMagic(m_header.magic);
5478061da546Spatrick for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5479061da546Spatrick const uint32_t cmd_offset = offset;
5480be691f3bSpatrick llvm::MachO::ident_command ident_command;
5481061da546Spatrick if (m_data.GetU32(&offset, &ident_command, 2) == nullptr)
5482061da546Spatrick break;
5483061da546Spatrick if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
5484061da546Spatrick char *buf = (char *)malloc(ident_command.cmdsize);
5485061da546Spatrick if (buf != nullptr && m_data.CopyData(offset, ident_command.cmdsize,
5486061da546Spatrick buf) == ident_command.cmdsize) {
5487061da546Spatrick buf[ident_command.cmdsize - 1] = '\0';
5488061da546Spatrick result = buf;
5489061da546Spatrick }
5490061da546Spatrick if (buf)
5491061da546Spatrick free(buf);
5492061da546Spatrick }
5493061da546Spatrick offset = cmd_offset + ident_command.cmdsize;
5494061da546Spatrick }
5495061da546Spatrick }
5496061da546Spatrick return result;
5497061da546Spatrick }
5498061da546Spatrick
5499be691f3bSpatrick addr_t ObjectFileMachO::GetAddressMask() {
5500be691f3bSpatrick addr_t mask = 0;
5501be691f3bSpatrick ModuleSP module_sp(GetModule());
5502be691f3bSpatrick if (module_sp) {
5503be691f3bSpatrick std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5504be691f3bSpatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5505be691f3bSpatrick for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5506be691f3bSpatrick const uint32_t cmd_offset = offset;
5507*f6aab3d8Srobert llvm::MachO::load_command lc = {};
5508be691f3bSpatrick if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5509be691f3bSpatrick break;
5510be691f3bSpatrick if (lc.cmd == LC_NOTE) {
5511be691f3bSpatrick char data_owner[17];
5512be691f3bSpatrick m_data.CopyData(offset, 16, data_owner);
5513be691f3bSpatrick data_owner[16] = '\0';
5514be691f3bSpatrick offset += 16;
5515be691f3bSpatrick uint64_t fileoff = m_data.GetU64_unchecked(&offset);
5516be691f3bSpatrick
5517be691f3bSpatrick // "addrable bits" has a uint32_t version and a uint32_t
5518be691f3bSpatrick // number of bits used in addressing.
5519be691f3bSpatrick if (strcmp("addrable bits", data_owner) == 0) {
5520be691f3bSpatrick offset = fileoff;
5521be691f3bSpatrick uint32_t version;
5522be691f3bSpatrick if (m_data.GetU32(&offset, &version, 1) != nullptr) {
5523be691f3bSpatrick if (version == 3) {
5524be691f3bSpatrick uint32_t num_addr_bits = m_data.GetU32_unchecked(&offset);
5525be691f3bSpatrick if (num_addr_bits != 0) {
5526be691f3bSpatrick mask = ~((1ULL << num_addr_bits) - 1);
5527be691f3bSpatrick }
5528be691f3bSpatrick break;
5529be691f3bSpatrick }
5530be691f3bSpatrick }
5531be691f3bSpatrick }
5532be691f3bSpatrick }
5533be691f3bSpatrick offset = cmd_offset + lc.cmdsize;
5534be691f3bSpatrick }
5535be691f3bSpatrick }
5536be691f3bSpatrick return mask;
5537be691f3bSpatrick }
5538be691f3bSpatrick
5539*f6aab3d8Srobert bool ObjectFileMachO::GetCorefileMainBinaryInfo(addr_t &value,
5540*f6aab3d8Srobert bool &value_is_offset,
5541*f6aab3d8Srobert UUID &uuid,
5542be691f3bSpatrick ObjectFile::BinaryType &type) {
5543*f6aab3d8Srobert value = LLDB_INVALID_ADDRESS;
5544*f6aab3d8Srobert value_is_offset = false;
5545061da546Spatrick uuid.Clear();
5546*f6aab3d8Srobert uint32_t log2_pagesize = 0; // not currently passed up to caller
5547*f6aab3d8Srobert uint32_t platform = 0; // not currently passed up to caller
5548061da546Spatrick ModuleSP module_sp(GetModule());
5549061da546Spatrick if (module_sp) {
5550061da546Spatrick std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5551061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5552061da546Spatrick for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5553061da546Spatrick const uint32_t cmd_offset = offset;
5554*f6aab3d8Srobert llvm::MachO::load_command lc = {};
5555061da546Spatrick if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5556061da546Spatrick break;
5557061da546Spatrick if (lc.cmd == LC_NOTE) {
5558061da546Spatrick char data_owner[17];
5559061da546Spatrick memset(data_owner, 0, sizeof(data_owner));
5560061da546Spatrick m_data.CopyData(offset, 16, data_owner);
5561061da546Spatrick offset += 16;
5562061da546Spatrick uint64_t fileoff = m_data.GetU64_unchecked(&offset);
5563061da546Spatrick uint64_t size = m_data.GetU64_unchecked(&offset);
5564061da546Spatrick
5565*f6aab3d8Srobert // struct main_bin_spec
5566*f6aab3d8Srobert // {
5567*f6aab3d8Srobert // uint32_t version; // currently 2
5568*f6aab3d8Srobert // uint32_t type; // 0 == unspecified, 1 == kernel,
5569*f6aab3d8Srobert // // 2 == user process,
5570*f6aab3d8Srobert // // 3 == standalone binary
5571*f6aab3d8Srobert // uint64_t address; // UINT64_MAX if address not specified
5572*f6aab3d8Srobert // uint64_t slide; // slide, UINT64_MAX if unspecified
5573*f6aab3d8Srobert // // 0 if no slide needs to be applied to
5574*f6aab3d8Srobert // // file address
5575*f6aab3d8Srobert // uuid_t uuid; // all zero's if uuid not specified
5576*f6aab3d8Srobert // uint32_t log2_pagesize; // process page size in log base 2,
5577*f6aab3d8Srobert // // e.g. 4k pages are 12.
5578*f6aab3d8Srobert // // 0 for unspecified
5579*f6aab3d8Srobert // uint32_t platform; // The Mach-O platform for this corefile.
5580*f6aab3d8Srobert // // 0 for unspecified.
5581*f6aab3d8Srobert // // The values are defined in
5582*f6aab3d8Srobert // // <mach-o/loader.h>, PLATFORM_*.
5583*f6aab3d8Srobert // } __attribute((packed));
5584*f6aab3d8Srobert
5585061da546Spatrick // "main bin spec" (main binary specification) data payload is
5586061da546Spatrick // formatted:
5587061da546Spatrick // uint32_t version [currently 1]
5588be691f3bSpatrick // uint32_t type [0 == unspecified, 1 == kernel,
5589be691f3bSpatrick // 2 == user process, 3 == firmware ]
5590be691f3bSpatrick // uint64_t address [ UINT64_MAX if address not specified ]
5591be691f3bSpatrick // uuid_t uuid [ all zero's if uuid not specified ]
5592be691f3bSpatrick // uint32_t log2_pagesize [ process page size in log base
5593be691f3bSpatrick // 2, e.g. 4k pages are 12.
5594be691f3bSpatrick // 0 for unspecified ]
5595be691f3bSpatrick // uint32_t unused [ for alignment ]
5596061da546Spatrick
5597061da546Spatrick if (strcmp("main bin spec", data_owner) == 0 && size >= 32) {
5598061da546Spatrick offset = fileoff;
5599061da546Spatrick uint32_t version;
5600*f6aab3d8Srobert if (m_data.GetU32(&offset, &version, 1) != nullptr && version <= 2) {
5601be691f3bSpatrick uint32_t binspec_type = 0;
5602061da546Spatrick uuid_t raw_uuid;
5603061da546Spatrick memset(raw_uuid, 0, sizeof(uuid_t));
5604061da546Spatrick
5605*f6aab3d8Srobert if (!m_data.GetU32(&offset, &binspec_type, 1))
5606*f6aab3d8Srobert return false;
5607*f6aab3d8Srobert if (!m_data.GetU64(&offset, &value, 1))
5608*f6aab3d8Srobert return false;
5609*f6aab3d8Srobert uint64_t slide = LLDB_INVALID_ADDRESS;
5610*f6aab3d8Srobert if (version > 1 && !m_data.GetU64(&offset, &slide, 1))
5611*f6aab3d8Srobert return false;
5612*f6aab3d8Srobert if (value == LLDB_INVALID_ADDRESS &&
5613*f6aab3d8Srobert slide != LLDB_INVALID_ADDRESS) {
5614*f6aab3d8Srobert value = slide;
5615*f6aab3d8Srobert value_is_offset = true;
5616*f6aab3d8Srobert }
5617*f6aab3d8Srobert
5618*f6aab3d8Srobert if (m_data.CopyData(offset, sizeof(uuid_t), raw_uuid) != 0) {
5619*f6aab3d8Srobert uuid = UUID(raw_uuid, sizeof(uuid_t));
5620be691f3bSpatrick // convert the "main bin spec" type into our
5621be691f3bSpatrick // ObjectFile::BinaryType enum
5622be691f3bSpatrick switch (binspec_type) {
5623be691f3bSpatrick case 0:
5624be691f3bSpatrick type = eBinaryTypeUnknown;
5625be691f3bSpatrick break;
5626be691f3bSpatrick case 1:
5627be691f3bSpatrick type = eBinaryTypeKernel;
5628be691f3bSpatrick break;
5629be691f3bSpatrick case 2:
5630be691f3bSpatrick type = eBinaryTypeUser;
5631be691f3bSpatrick break;
5632be691f3bSpatrick case 3:
5633be691f3bSpatrick type = eBinaryTypeStandalone;
5634be691f3bSpatrick break;
5635be691f3bSpatrick }
5636*f6aab3d8Srobert if (!m_data.GetU32(&offset, &log2_pagesize, 1))
5637*f6aab3d8Srobert return false;
5638*f6aab3d8Srobert if (version > 1 && !m_data.GetU32(&offset, &platform, 1))
5639*f6aab3d8Srobert return false;
5640061da546Spatrick return true;
5641061da546Spatrick }
5642061da546Spatrick }
5643061da546Spatrick }
5644061da546Spatrick }
5645061da546Spatrick offset = cmd_offset + lc.cmdsize;
5646061da546Spatrick }
5647061da546Spatrick }
5648061da546Spatrick return false;
5649061da546Spatrick }
5650061da546Spatrick
5651061da546Spatrick lldb::RegisterContextSP
5652061da546Spatrick ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
5653061da546Spatrick lldb_private::Thread &thread) {
5654061da546Spatrick lldb::RegisterContextSP reg_ctx_sp;
5655061da546Spatrick
5656061da546Spatrick ModuleSP module_sp(GetModule());
5657061da546Spatrick if (module_sp) {
5658061da546Spatrick std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5659061da546Spatrick if (!m_thread_context_offsets_valid)
5660061da546Spatrick GetNumThreadContexts();
5661061da546Spatrick
5662061da546Spatrick const FileRangeArray::Entry *thread_context_file_range =
5663061da546Spatrick m_thread_context_offsets.GetEntryAtIndex(idx);
5664061da546Spatrick if (thread_context_file_range) {
5665061da546Spatrick
5666061da546Spatrick DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
5667061da546Spatrick thread_context_file_range->GetByteSize());
5668061da546Spatrick
5669061da546Spatrick switch (m_header.cputype) {
5670061da546Spatrick case llvm::MachO::CPU_TYPE_ARM64:
5671061da546Spatrick case llvm::MachO::CPU_TYPE_ARM64_32:
5672061da546Spatrick reg_ctx_sp =
5673061da546Spatrick std::make_shared<RegisterContextDarwin_arm64_Mach>(thread, data);
5674061da546Spatrick break;
5675061da546Spatrick
5676061da546Spatrick case llvm::MachO::CPU_TYPE_ARM:
5677061da546Spatrick reg_ctx_sp =
5678061da546Spatrick std::make_shared<RegisterContextDarwin_arm_Mach>(thread, data);
5679061da546Spatrick break;
5680061da546Spatrick
5681061da546Spatrick case llvm::MachO::CPU_TYPE_I386:
5682061da546Spatrick reg_ctx_sp =
5683061da546Spatrick std::make_shared<RegisterContextDarwin_i386_Mach>(thread, data);
5684061da546Spatrick break;
5685061da546Spatrick
5686061da546Spatrick case llvm::MachO::CPU_TYPE_X86_64:
5687061da546Spatrick reg_ctx_sp =
5688061da546Spatrick std::make_shared<RegisterContextDarwin_x86_64_Mach>(thread, data);
5689061da546Spatrick break;
5690061da546Spatrick }
5691061da546Spatrick }
5692061da546Spatrick }
5693061da546Spatrick return reg_ctx_sp;
5694061da546Spatrick }
5695061da546Spatrick
5696061da546Spatrick ObjectFile::Type ObjectFileMachO::CalculateType() {
5697061da546Spatrick switch (m_header.filetype) {
5698061da546Spatrick case MH_OBJECT: // 0x1u
5699061da546Spatrick if (GetAddressByteSize() == 4) {
5700061da546Spatrick // 32 bit kexts are just object files, but they do have a valid
5701061da546Spatrick // UUID load command.
5702061da546Spatrick if (GetUUID()) {
5703061da546Spatrick // this checking for the UUID load command is not enough we could
5704061da546Spatrick // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5705061da546Spatrick // this is required of kexts
5706061da546Spatrick if (m_strata == eStrataInvalid)
5707061da546Spatrick m_strata = eStrataKernel;
5708061da546Spatrick return eTypeSharedLibrary;
5709061da546Spatrick }
5710061da546Spatrick }
5711061da546Spatrick return eTypeObjectFile;
5712061da546Spatrick
5713061da546Spatrick case MH_EXECUTE:
5714061da546Spatrick return eTypeExecutable; // 0x2u
5715061da546Spatrick case MH_FVMLIB:
5716061da546Spatrick return eTypeSharedLibrary; // 0x3u
5717061da546Spatrick case MH_CORE:
5718061da546Spatrick return eTypeCoreFile; // 0x4u
5719061da546Spatrick case MH_PRELOAD:
5720061da546Spatrick return eTypeSharedLibrary; // 0x5u
5721061da546Spatrick case MH_DYLIB:
5722061da546Spatrick return eTypeSharedLibrary; // 0x6u
5723061da546Spatrick case MH_DYLINKER:
5724061da546Spatrick return eTypeDynamicLinker; // 0x7u
5725061da546Spatrick case MH_BUNDLE:
5726061da546Spatrick return eTypeSharedLibrary; // 0x8u
5727061da546Spatrick case MH_DYLIB_STUB:
5728061da546Spatrick return eTypeStubLibrary; // 0x9u
5729061da546Spatrick case MH_DSYM:
5730061da546Spatrick return eTypeDebugInfo; // 0xAu
5731061da546Spatrick case MH_KEXT_BUNDLE:
5732061da546Spatrick return eTypeSharedLibrary; // 0xBu
5733061da546Spatrick default:
5734061da546Spatrick break;
5735061da546Spatrick }
5736061da546Spatrick return eTypeUnknown;
5737061da546Spatrick }
5738061da546Spatrick
5739061da546Spatrick ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
5740061da546Spatrick switch (m_header.filetype) {
5741061da546Spatrick case MH_OBJECT: // 0x1u
5742061da546Spatrick {
5743061da546Spatrick // 32 bit kexts are just object files, but they do have a valid
5744061da546Spatrick // UUID load command.
5745061da546Spatrick if (GetUUID()) {
5746061da546Spatrick // this checking for the UUID load command is not enough we could
5747061da546Spatrick // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5748061da546Spatrick // this is required of kexts
5749061da546Spatrick if (m_type == eTypeInvalid)
5750061da546Spatrick m_type = eTypeSharedLibrary;
5751061da546Spatrick
5752061da546Spatrick return eStrataKernel;
5753061da546Spatrick }
5754061da546Spatrick }
5755061da546Spatrick return eStrataUnknown;
5756061da546Spatrick
5757061da546Spatrick case MH_EXECUTE: // 0x2u
5758061da546Spatrick // Check for the MH_DYLDLINK bit in the flags
5759061da546Spatrick if (m_header.flags & MH_DYLDLINK) {
5760061da546Spatrick return eStrataUser;
5761061da546Spatrick } else {
5762061da546Spatrick SectionList *section_list = GetSectionList();
5763061da546Spatrick if (section_list) {
5764061da546Spatrick static ConstString g_kld_section_name("__KLD");
5765061da546Spatrick if (section_list->FindSectionByName(g_kld_section_name))
5766061da546Spatrick return eStrataKernel;
5767061da546Spatrick }
5768061da546Spatrick }
5769061da546Spatrick return eStrataRawImage;
5770061da546Spatrick
5771061da546Spatrick case MH_FVMLIB:
5772061da546Spatrick return eStrataUser; // 0x3u
5773061da546Spatrick case MH_CORE:
5774061da546Spatrick return eStrataUnknown; // 0x4u
5775061da546Spatrick case MH_PRELOAD:
5776061da546Spatrick return eStrataRawImage; // 0x5u
5777061da546Spatrick case MH_DYLIB:
5778061da546Spatrick return eStrataUser; // 0x6u
5779061da546Spatrick case MH_DYLINKER:
5780061da546Spatrick return eStrataUser; // 0x7u
5781061da546Spatrick case MH_BUNDLE:
5782061da546Spatrick return eStrataUser; // 0x8u
5783061da546Spatrick case MH_DYLIB_STUB:
5784061da546Spatrick return eStrataUser; // 0x9u
5785061da546Spatrick case MH_DSYM:
5786061da546Spatrick return eStrataUnknown; // 0xAu
5787061da546Spatrick case MH_KEXT_BUNDLE:
5788061da546Spatrick return eStrataKernel; // 0xBu
5789061da546Spatrick default:
5790061da546Spatrick break;
5791061da546Spatrick }
5792061da546Spatrick return eStrataUnknown;
5793061da546Spatrick }
5794061da546Spatrick
5795061da546Spatrick llvm::VersionTuple ObjectFileMachO::GetVersion() {
5796061da546Spatrick ModuleSP module_sp(GetModule());
5797061da546Spatrick if (module_sp) {
5798061da546Spatrick std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5799be691f3bSpatrick llvm::MachO::dylib_command load_cmd;
5800061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5801061da546Spatrick uint32_t version_cmd = 0;
5802061da546Spatrick uint64_t version = 0;
5803061da546Spatrick uint32_t i;
5804061da546Spatrick for (i = 0; i < m_header.ncmds; ++i) {
5805061da546Spatrick const lldb::offset_t cmd_offset = offset;
5806061da546Spatrick if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
5807061da546Spatrick break;
5808061da546Spatrick
5809061da546Spatrick if (load_cmd.cmd == LC_ID_DYLIB) {
5810061da546Spatrick if (version_cmd == 0) {
5811061da546Spatrick version_cmd = load_cmd.cmd;
5812061da546Spatrick if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == nullptr)
5813061da546Spatrick break;
5814061da546Spatrick version = load_cmd.dylib.current_version;
5815061da546Spatrick }
5816061da546Spatrick break; // Break for now unless there is another more complete version
5817061da546Spatrick // number load command in the future.
5818061da546Spatrick }
5819061da546Spatrick offset = cmd_offset + load_cmd.cmdsize;
5820061da546Spatrick }
5821061da546Spatrick
5822061da546Spatrick if (version_cmd == LC_ID_DYLIB) {
5823061da546Spatrick unsigned major = (version & 0xFFFF0000ull) >> 16;
5824061da546Spatrick unsigned minor = (version & 0x0000FF00ull) >> 8;
5825061da546Spatrick unsigned subminor = (version & 0x000000FFull);
5826061da546Spatrick return llvm::VersionTuple(major, minor, subminor);
5827061da546Spatrick }
5828061da546Spatrick }
5829061da546Spatrick return llvm::VersionTuple();
5830061da546Spatrick }
5831061da546Spatrick
5832061da546Spatrick ArchSpec ObjectFileMachO::GetArchitecture() {
5833061da546Spatrick ModuleSP module_sp(GetModule());
5834061da546Spatrick ArchSpec arch;
5835061da546Spatrick if (module_sp) {
5836061da546Spatrick std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5837061da546Spatrick
5838061da546Spatrick return GetArchitecture(module_sp, m_header, m_data,
5839061da546Spatrick MachHeaderSizeFromMagic(m_header.magic));
5840061da546Spatrick }
5841061da546Spatrick return arch;
5842061da546Spatrick }
5843061da546Spatrick
5844061da546Spatrick void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process,
5845061da546Spatrick addr_t &base_addr, UUID &uuid) {
5846061da546Spatrick uuid.Clear();
5847061da546Spatrick base_addr = LLDB_INVALID_ADDRESS;
5848061da546Spatrick if (process && process->GetDynamicLoader()) {
5849061da546Spatrick DynamicLoader *dl = process->GetDynamicLoader();
5850061da546Spatrick LazyBool using_shared_cache;
5851061da546Spatrick LazyBool private_shared_cache;
5852061da546Spatrick dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache,
5853061da546Spatrick private_shared_cache);
5854061da546Spatrick }
5855*f6aab3d8Srobert Log *log(GetLog(LLDBLog::Symbols | LLDBLog::Process));
5856061da546Spatrick LLDB_LOGF(
5857061da546Spatrick log,
5858061da546Spatrick "inferior process shared cache has a UUID of %s, base address 0x%" PRIx64,
5859061da546Spatrick uuid.GetAsString().c_str(), base_addr);
5860061da546Spatrick }
5861061da546Spatrick
5862061da546Spatrick // From dyld SPI header dyld_process_info.h
5863061da546Spatrick typedef void *dyld_process_info;
5864061da546Spatrick struct lldb_copy__dyld_process_cache_info {
5865061da546Spatrick uuid_t cacheUUID; // UUID of cache used by process
5866061da546Spatrick uint64_t cacheBaseAddress; // load address of dyld shared cache
5867061da546Spatrick bool noCache; // process is running without a dyld cache
5868061da546Spatrick bool privateCache; // process is using a private copy of its dyld cache
5869061da546Spatrick };
5870061da546Spatrick
5871061da546Spatrick // #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with
5872061da546Spatrick // llvm enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile
5873061da546Spatrick // errors. So we need to use the actual underlying types of task_t and
5874061da546Spatrick // kern_return_t below.
5875061da546Spatrick extern "C" unsigned int /*task_t*/ mach_task_self();
5876061da546Spatrick
5877061da546Spatrick void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
5878061da546Spatrick uuid.Clear();
5879061da546Spatrick base_addr = LLDB_INVALID_ADDRESS;
5880061da546Spatrick
5881be691f3bSpatrick #if defined(__APPLE__)
5882061da546Spatrick uint8_t *(*dyld_get_all_image_infos)(void);
5883061da546Spatrick dyld_get_all_image_infos =
5884061da546Spatrick (uint8_t * (*)()) dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5885061da546Spatrick if (dyld_get_all_image_infos) {
5886061da546Spatrick uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5887061da546Spatrick if (dyld_all_image_infos_address) {
5888061da546Spatrick uint32_t *version = (uint32_t *)
5889061da546Spatrick dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5890061da546Spatrick if (*version >= 13) {
5891061da546Spatrick uuid_t *sharedCacheUUID_address = 0;
5892061da546Spatrick int wordsize = sizeof(uint8_t *);
5893061da546Spatrick if (wordsize == 8) {
5894061da546Spatrick sharedCacheUUID_address =
5895061da546Spatrick (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5896061da546Spatrick 160); // sharedCacheUUID <mach-o/dyld_images.h>
5897061da546Spatrick if (*version >= 15)
5898061da546Spatrick base_addr =
5899061da546Spatrick *(uint64_t
5900061da546Spatrick *)((uint8_t *)dyld_all_image_infos_address +
5901061da546Spatrick 176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5902061da546Spatrick } else {
5903061da546Spatrick sharedCacheUUID_address =
5904061da546Spatrick (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5905061da546Spatrick 84); // sharedCacheUUID <mach-o/dyld_images.h>
5906061da546Spatrick if (*version >= 15) {
5907061da546Spatrick base_addr = 0;
5908061da546Spatrick base_addr =
5909061da546Spatrick *(uint32_t
5910061da546Spatrick *)((uint8_t *)dyld_all_image_infos_address +
5911061da546Spatrick 100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5912061da546Spatrick }
5913061da546Spatrick }
5914*f6aab3d8Srobert uuid = UUID(sharedCacheUUID_address, sizeof(uuid_t));
5915061da546Spatrick }
5916061da546Spatrick }
5917061da546Spatrick } else {
5918061da546Spatrick // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
5919061da546Spatrick dyld_process_info (*dyld_process_info_create)(
5920061da546Spatrick unsigned int /* task_t */ task, uint64_t timestamp,
5921061da546Spatrick unsigned int /*kern_return_t*/ *kernelError);
5922061da546Spatrick void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
5923061da546Spatrick void (*dyld_process_info_release)(dyld_process_info info);
5924061da546Spatrick
5925061da546Spatrick dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t,
5926061da546Spatrick unsigned int /*kern_return_t*/ *))
5927061da546Spatrick dlsym(RTLD_DEFAULT, "_dyld_process_info_create");
5928061da546Spatrick dyld_process_info_get_cache = (void (*)(void *, void *))dlsym(
5929061da546Spatrick RTLD_DEFAULT, "_dyld_process_info_get_cache");
5930061da546Spatrick dyld_process_info_release =
5931061da546Spatrick (void (*)(void *))dlsym(RTLD_DEFAULT, "_dyld_process_info_release");
5932061da546Spatrick
5933061da546Spatrick if (dyld_process_info_create && dyld_process_info_get_cache) {
5934061da546Spatrick unsigned int /*kern_return_t */ kern_ret;
5935061da546Spatrick dyld_process_info process_info =
5936061da546Spatrick dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
5937061da546Spatrick if (process_info) {
5938061da546Spatrick struct lldb_copy__dyld_process_cache_info sc_info;
5939061da546Spatrick memset(&sc_info, 0, sizeof(struct lldb_copy__dyld_process_cache_info));
5940061da546Spatrick dyld_process_info_get_cache(process_info, &sc_info);
5941061da546Spatrick if (sc_info.cacheBaseAddress != 0) {
5942061da546Spatrick base_addr = sc_info.cacheBaseAddress;
5943*f6aab3d8Srobert uuid = UUID(sc_info.cacheUUID, sizeof(uuid_t));
5944061da546Spatrick }
5945061da546Spatrick dyld_process_info_release(process_info);
5946061da546Spatrick }
5947061da546Spatrick }
5948061da546Spatrick }
5949*f6aab3d8Srobert Log *log(GetLog(LLDBLog::Symbols | LLDBLog::Process));
5950061da546Spatrick if (log && uuid.IsValid())
5951061da546Spatrick LLDB_LOGF(log,
5952061da546Spatrick "lldb's in-memory shared cache has a UUID of %s base address of "
5953061da546Spatrick "0x%" PRIx64,
5954061da546Spatrick uuid.GetAsString().c_str(), base_addr);
5955061da546Spatrick #endif
5956061da546Spatrick }
5957061da546Spatrick
5958061da546Spatrick llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() {
5959061da546Spatrick if (!m_min_os_version) {
5960061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5961061da546Spatrick for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5962061da546Spatrick const lldb::offset_t load_cmd_offset = offset;
5963061da546Spatrick
5964*f6aab3d8Srobert llvm::MachO::version_min_command lc = {};
5965061da546Spatrick if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5966061da546Spatrick break;
5967061da546Spatrick if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5968061da546Spatrick lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5969061da546Spatrick lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5970061da546Spatrick lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5971061da546Spatrick if (m_data.GetU32(&offset, &lc.version,
5972061da546Spatrick (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5973061da546Spatrick const uint32_t xxxx = lc.version >> 16;
5974061da546Spatrick const uint32_t yy = (lc.version >> 8) & 0xffu;
5975061da546Spatrick const uint32_t zz = lc.version & 0xffu;
5976061da546Spatrick if (xxxx) {
5977061da546Spatrick m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5978061da546Spatrick break;
5979061da546Spatrick }
5980061da546Spatrick }
5981061da546Spatrick } else if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5982061da546Spatrick // struct build_version_command {
5983061da546Spatrick // uint32_t cmd; /* LC_BUILD_VERSION */
5984061da546Spatrick // uint32_t cmdsize; /* sizeof(struct
5985061da546Spatrick // build_version_command) plus */
5986061da546Spatrick // /* ntools * sizeof(struct
5987061da546Spatrick // build_tool_version) */
5988061da546Spatrick // uint32_t platform; /* platform */
5989061da546Spatrick // uint32_t minos; /* X.Y.Z is encoded in nibbles
5990061da546Spatrick // xxxx.yy.zz */ uint32_t sdk; /* X.Y.Z is encoded in
5991061da546Spatrick // nibbles xxxx.yy.zz */ uint32_t ntools; /* number of
5992061da546Spatrick // tool entries following this */
5993061da546Spatrick // };
5994061da546Spatrick
5995061da546Spatrick offset += 4; // skip platform
5996061da546Spatrick uint32_t minos = m_data.GetU32(&offset);
5997061da546Spatrick
5998061da546Spatrick const uint32_t xxxx = minos >> 16;
5999061da546Spatrick const uint32_t yy = (minos >> 8) & 0xffu;
6000061da546Spatrick const uint32_t zz = minos & 0xffu;
6001061da546Spatrick if (xxxx) {
6002061da546Spatrick m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
6003061da546Spatrick break;
6004061da546Spatrick }
6005061da546Spatrick }
6006061da546Spatrick
6007061da546Spatrick offset = load_cmd_offset + lc.cmdsize;
6008061da546Spatrick }
6009061da546Spatrick
6010061da546Spatrick if (!m_min_os_version) {
6011061da546Spatrick // Set version to an empty value so we don't keep trying to
6012061da546Spatrick m_min_os_version = llvm::VersionTuple();
6013061da546Spatrick }
6014061da546Spatrick }
6015061da546Spatrick
6016061da546Spatrick return *m_min_os_version;
6017061da546Spatrick }
6018061da546Spatrick
6019061da546Spatrick llvm::VersionTuple ObjectFileMachO::GetSDKVersion() {
6020*f6aab3d8Srobert if (!m_sdk_versions) {
6021061da546Spatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
6022061da546Spatrick for (uint32_t i = 0; i < m_header.ncmds; ++i) {
6023061da546Spatrick const lldb::offset_t load_cmd_offset = offset;
6024061da546Spatrick
6025*f6aab3d8Srobert llvm::MachO::version_min_command lc = {};
6026061da546Spatrick if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
6027061da546Spatrick break;
6028061da546Spatrick if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
6029061da546Spatrick lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
6030061da546Spatrick lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
6031061da546Spatrick lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
6032061da546Spatrick if (m_data.GetU32(&offset, &lc.version,
6033061da546Spatrick (sizeof(lc) / sizeof(uint32_t)) - 2)) {
6034061da546Spatrick const uint32_t xxxx = lc.sdk >> 16;
6035061da546Spatrick const uint32_t yy = (lc.sdk >> 8) & 0xffu;
6036061da546Spatrick const uint32_t zz = lc.sdk & 0xffu;
6037061da546Spatrick if (xxxx) {
6038061da546Spatrick m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz);
6039061da546Spatrick break;
6040061da546Spatrick } else {
6041061da546Spatrick GetModule()->ReportWarning("minimum OS version load command with "
6042061da546Spatrick "invalid (0) version found.");
6043061da546Spatrick }
6044061da546Spatrick }
6045061da546Spatrick }
6046061da546Spatrick offset = load_cmd_offset + lc.cmdsize;
6047061da546Spatrick }
6048061da546Spatrick
6049*f6aab3d8Srobert if (!m_sdk_versions) {
6050061da546Spatrick offset = MachHeaderSizeFromMagic(m_header.magic);
6051061da546Spatrick for (uint32_t i = 0; i < m_header.ncmds; ++i) {
6052061da546Spatrick const lldb::offset_t load_cmd_offset = offset;
6053061da546Spatrick
6054*f6aab3d8Srobert llvm::MachO::version_min_command lc = {};
6055061da546Spatrick if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
6056061da546Spatrick break;
6057061da546Spatrick if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
6058061da546Spatrick // struct build_version_command {
6059061da546Spatrick // uint32_t cmd; /* LC_BUILD_VERSION */
6060061da546Spatrick // uint32_t cmdsize; /* sizeof(struct
6061061da546Spatrick // build_version_command) plus */
6062061da546Spatrick // /* ntools * sizeof(struct
6063061da546Spatrick // build_tool_version) */
6064061da546Spatrick // uint32_t platform; /* platform */
6065061da546Spatrick // uint32_t minos; /* X.Y.Z is encoded in nibbles
6066061da546Spatrick // xxxx.yy.zz */ uint32_t sdk; /* X.Y.Z is encoded
6067061da546Spatrick // in nibbles xxxx.yy.zz */ uint32_t ntools; /* number
6068061da546Spatrick // of tool entries following this */
6069061da546Spatrick // };
6070061da546Spatrick
6071061da546Spatrick offset += 4; // skip platform
6072061da546Spatrick uint32_t minos = m_data.GetU32(&offset);
6073061da546Spatrick
6074061da546Spatrick const uint32_t xxxx = minos >> 16;
6075061da546Spatrick const uint32_t yy = (minos >> 8) & 0xffu;
6076061da546Spatrick const uint32_t zz = minos & 0xffu;
6077061da546Spatrick if (xxxx) {
6078061da546Spatrick m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz);
6079061da546Spatrick break;
6080061da546Spatrick }
6081061da546Spatrick }
6082061da546Spatrick offset = load_cmd_offset + lc.cmdsize;
6083061da546Spatrick }
6084061da546Spatrick }
6085061da546Spatrick
6086*f6aab3d8Srobert if (!m_sdk_versions)
6087061da546Spatrick m_sdk_versions = llvm::VersionTuple();
6088061da546Spatrick }
6089061da546Spatrick
6090*f6aab3d8Srobert return *m_sdk_versions;
6091061da546Spatrick }
6092061da546Spatrick
6093061da546Spatrick bool ObjectFileMachO::GetIsDynamicLinkEditor() {
6094061da546Spatrick return m_header.filetype == llvm::MachO::MH_DYLINKER;
6095061da546Spatrick }
6096061da546Spatrick
6097*f6aab3d8Srobert bool ObjectFileMachO::CanTrustAddressRanges() {
6098*f6aab3d8Srobert // Dsymutil guarantees that the .debug_aranges accelerator is complete and can
6099*f6aab3d8Srobert // be trusted by LLDB.
6100*f6aab3d8Srobert return m_header.filetype == llvm::MachO::MH_DSYM;
6101*f6aab3d8Srobert }
6102*f6aab3d8Srobert
6103061da546Spatrick bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
6104061da546Spatrick return m_allow_assembly_emulation_unwind_plans;
6105061da546Spatrick }
6106061da546Spatrick
6107061da546Spatrick Section *ObjectFileMachO::GetMachHeaderSection() {
6108061da546Spatrick // Find the first address of the mach header which is the first non-zero file
6109061da546Spatrick // sized section whose file offset is zero. This is the base file address of
6110061da546Spatrick // the mach-o file which can be subtracted from the vmaddr of the other
6111061da546Spatrick // segments found in memory and added to the load address
6112061da546Spatrick ModuleSP module_sp = GetModule();
6113061da546Spatrick if (!module_sp)
6114061da546Spatrick return nullptr;
6115061da546Spatrick SectionList *section_list = GetSectionList();
6116061da546Spatrick if (!section_list)
6117061da546Spatrick return nullptr;
6118061da546Spatrick const size_t num_sections = section_list->GetSize();
6119061da546Spatrick for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6120061da546Spatrick Section *section = section_list->GetSectionAtIndex(sect_idx).get();
6121061da546Spatrick if (section->GetFileOffset() == 0 && SectionIsLoadable(section))
6122061da546Spatrick return section;
6123061da546Spatrick }
6124*f6aab3d8Srobert
6125*f6aab3d8Srobert // We may have a binary in the shared cache that has a non-zero
6126*f6aab3d8Srobert // file address for its first segment, traditionally the __TEXT segment.
6127*f6aab3d8Srobert // Search for it by name and return it as our next best guess.
6128*f6aab3d8Srobert SectionSP text_segment_sp =
6129*f6aab3d8Srobert GetSectionList()->FindSectionByName(GetSegmentNameTEXT());
6130*f6aab3d8Srobert if (text_segment_sp.get() && SectionIsLoadable(text_segment_sp.get()))
6131*f6aab3d8Srobert return text_segment_sp.get();
6132*f6aab3d8Srobert
6133061da546Spatrick return nullptr;
6134061da546Spatrick }
6135061da546Spatrick
6136061da546Spatrick bool ObjectFileMachO::SectionIsLoadable(const Section *section) {
6137061da546Spatrick if (!section)
6138061da546Spatrick return false;
6139061da546Spatrick const bool is_dsym = (m_header.filetype == MH_DSYM);
6140061da546Spatrick if (section->GetFileSize() == 0 && !is_dsym)
6141061da546Spatrick return false;
6142061da546Spatrick if (section->IsThreadSpecific())
6143061da546Spatrick return false;
6144061da546Spatrick if (GetModule().get() != section->GetModule().get())
6145061da546Spatrick return false;
6146061da546Spatrick // Be careful with __LINKEDIT and __DWARF segments
6147061da546Spatrick if (section->GetName() == GetSegmentNameLINKEDIT() ||
6148061da546Spatrick section->GetName() == GetSegmentNameDWARF()) {
6149061da546Spatrick // Only map __LINKEDIT and __DWARF if we have an in memory image and
6150061da546Spatrick // this isn't a kernel binary like a kext or mach_kernel.
6151061da546Spatrick const bool is_memory_image = (bool)m_process_wp.lock();
6152061da546Spatrick const Strata strata = GetStrata();
6153061da546Spatrick if (is_memory_image == false || strata == eStrataKernel)
6154061da546Spatrick return false;
6155061da546Spatrick }
6156061da546Spatrick return true;
6157061da546Spatrick }
6158061da546Spatrick
6159061da546Spatrick lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
6160061da546Spatrick lldb::addr_t header_load_address, const Section *header_section,
6161061da546Spatrick const Section *section) {
6162061da546Spatrick ModuleSP module_sp = GetModule();
6163061da546Spatrick if (module_sp && header_section && section &&
6164061da546Spatrick header_load_address != LLDB_INVALID_ADDRESS) {
6165061da546Spatrick lldb::addr_t file_addr = header_section->GetFileAddress();
6166061da546Spatrick if (file_addr != LLDB_INVALID_ADDRESS && SectionIsLoadable(section))
6167061da546Spatrick return section->GetFileAddress() - file_addr + header_load_address;
6168061da546Spatrick }
6169061da546Spatrick return LLDB_INVALID_ADDRESS;
6170061da546Spatrick }
6171061da546Spatrick
6172061da546Spatrick bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
6173061da546Spatrick bool value_is_offset) {
6174061da546Spatrick ModuleSP module_sp = GetModule();
6175061da546Spatrick if (!module_sp)
6176061da546Spatrick return false;
6177061da546Spatrick
6178061da546Spatrick SectionList *section_list = GetSectionList();
6179061da546Spatrick if (!section_list)
6180061da546Spatrick return false;
6181061da546Spatrick
6182061da546Spatrick size_t num_loaded_sections = 0;
6183061da546Spatrick const size_t num_sections = section_list->GetSize();
6184061da546Spatrick
6185061da546Spatrick if (value_is_offset) {
6186061da546Spatrick // "value" is an offset to apply to each top level segment
6187061da546Spatrick for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6188061da546Spatrick // Iterate through the object file sections to find all of the
6189061da546Spatrick // sections that size on disk (to avoid __PAGEZERO) and load them
6190061da546Spatrick SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
6191061da546Spatrick if (SectionIsLoadable(section_sp.get()))
6192061da546Spatrick if (target.GetSectionLoadList().SetSectionLoadAddress(
6193061da546Spatrick section_sp, section_sp->GetFileAddress() + value))
6194061da546Spatrick ++num_loaded_sections;
6195061da546Spatrick }
6196061da546Spatrick } else {
6197061da546Spatrick // "value" is the new base address of the mach_header, adjust each
6198061da546Spatrick // section accordingly
6199061da546Spatrick
6200061da546Spatrick Section *mach_header_section = GetMachHeaderSection();
6201061da546Spatrick if (mach_header_section) {
6202061da546Spatrick for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6203061da546Spatrick SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
6204061da546Spatrick
6205061da546Spatrick lldb::addr_t section_load_addr =
6206061da546Spatrick CalculateSectionLoadAddressForMemoryImage(
6207061da546Spatrick value, mach_header_section, section_sp.get());
6208061da546Spatrick if (section_load_addr != LLDB_INVALID_ADDRESS) {
6209061da546Spatrick if (target.GetSectionLoadList().SetSectionLoadAddress(
6210061da546Spatrick section_sp, section_load_addr))
6211061da546Spatrick ++num_loaded_sections;
6212061da546Spatrick }
6213061da546Spatrick }
6214061da546Spatrick }
6215061da546Spatrick }
6216061da546Spatrick return num_loaded_sections > 0;
6217061da546Spatrick }
6218061da546Spatrick
6219be691f3bSpatrick struct all_image_infos_header {
6220be691f3bSpatrick uint32_t version; // currently 1
6221be691f3bSpatrick uint32_t imgcount; // number of binary images
6222be691f3bSpatrick uint64_t entries_fileoff; // file offset in the corefile of where the array of
6223be691f3bSpatrick // struct entry's begin.
6224be691f3bSpatrick uint32_t entries_size; // size of 'struct entry'.
6225be691f3bSpatrick uint32_t unused;
6226be691f3bSpatrick };
6227be691f3bSpatrick
6228be691f3bSpatrick struct image_entry {
6229be691f3bSpatrick uint64_t filepath_offset; // offset in corefile to c-string of the file path,
6230be691f3bSpatrick // UINT64_MAX if unavailable.
6231be691f3bSpatrick uuid_t uuid; // uint8_t[16]. should be set to all zeroes if
6232be691f3bSpatrick // uuid is unknown.
6233be691f3bSpatrick uint64_t load_address; // UINT64_MAX if unknown.
6234be691f3bSpatrick uint64_t seg_addrs_offset; // offset to the array of struct segment_vmaddr's.
6235be691f3bSpatrick uint32_t segment_count; // The number of segments for this binary.
6236be691f3bSpatrick uint32_t unused;
6237be691f3bSpatrick
6238be691f3bSpatrick image_entry() {
6239be691f3bSpatrick filepath_offset = UINT64_MAX;
6240be691f3bSpatrick memset(&uuid, 0, sizeof(uuid_t));
6241be691f3bSpatrick segment_count = 0;
6242be691f3bSpatrick load_address = UINT64_MAX;
6243be691f3bSpatrick seg_addrs_offset = UINT64_MAX;
6244be691f3bSpatrick unused = 0;
6245be691f3bSpatrick }
6246be691f3bSpatrick image_entry(const image_entry &rhs) {
6247be691f3bSpatrick filepath_offset = rhs.filepath_offset;
6248be691f3bSpatrick memcpy(&uuid, &rhs.uuid, sizeof(uuid_t));
6249be691f3bSpatrick segment_count = rhs.segment_count;
6250be691f3bSpatrick seg_addrs_offset = rhs.seg_addrs_offset;
6251be691f3bSpatrick load_address = rhs.load_address;
6252be691f3bSpatrick unused = rhs.unused;
6253be691f3bSpatrick }
6254be691f3bSpatrick };
6255be691f3bSpatrick
6256be691f3bSpatrick struct segment_vmaddr {
6257be691f3bSpatrick char segname[16];
6258be691f3bSpatrick uint64_t vmaddr;
6259be691f3bSpatrick uint64_t unused;
6260be691f3bSpatrick
6261be691f3bSpatrick segment_vmaddr() {
6262be691f3bSpatrick memset(&segname, 0, 16);
6263be691f3bSpatrick vmaddr = UINT64_MAX;
6264be691f3bSpatrick unused = 0;
6265be691f3bSpatrick }
6266be691f3bSpatrick segment_vmaddr(const segment_vmaddr &rhs) {
6267be691f3bSpatrick memcpy(&segname, &rhs.segname, 16);
6268be691f3bSpatrick vmaddr = rhs.vmaddr;
6269be691f3bSpatrick unused = rhs.unused;
6270be691f3bSpatrick }
6271be691f3bSpatrick };
6272be691f3bSpatrick
6273be691f3bSpatrick // Write the payload for the "all image infos" LC_NOTE into
6274be691f3bSpatrick // the supplied all_image_infos_payload, assuming that this
6275be691f3bSpatrick // will be written into the corefile starting at
6276be691f3bSpatrick // initial_file_offset.
6277be691f3bSpatrick //
6278be691f3bSpatrick // The placement of this payload is a little tricky. We're
6279be691f3bSpatrick // laying this out as
6280be691f3bSpatrick //
6281be691f3bSpatrick // 1. header (struct all_image_info_header)
6282be691f3bSpatrick // 2. Array of fixed-size (struct image_entry)'s, one
6283be691f3bSpatrick // per binary image present in the process.
6284be691f3bSpatrick // 3. Arrays of (struct segment_vmaddr)'s, a varying number
6285be691f3bSpatrick // for each binary image.
6286be691f3bSpatrick // 4. Variable length c-strings of binary image filepaths,
6287be691f3bSpatrick // one per binary.
6288be691f3bSpatrick //
6289be691f3bSpatrick // To compute where everything will be laid out in the
6290be691f3bSpatrick // payload, we need to iterate over the images and calculate
6291be691f3bSpatrick // how many segment_vmaddr structures each image will need,
6292be691f3bSpatrick // and how long each image's filepath c-string is. There
6293be691f3bSpatrick // are some multiple passes over the image list while calculating
6294be691f3bSpatrick // everything.
6295be691f3bSpatrick
6296*f6aab3d8Srobert static offset_t CreateAllImageInfosPayload(
6297*f6aab3d8Srobert const lldb::ProcessSP &process_sp, offset_t initial_file_offset,
6298*f6aab3d8Srobert StreamString &all_image_infos_payload, SaveCoreStyle core_style) {
6299be691f3bSpatrick Target &target = process_sp->GetTarget();
6300*f6aab3d8Srobert ModuleList modules = target.GetImages();
6301*f6aab3d8Srobert
6302*f6aab3d8Srobert // stack-only corefiles have no reason to include binaries that
6303*f6aab3d8Srobert // are not executing; we're trying to make the smallest corefile
6304*f6aab3d8Srobert // we can, so leave the rest out.
6305*f6aab3d8Srobert if (core_style == SaveCoreStyle::eSaveCoreStackOnly)
6306*f6aab3d8Srobert modules.Clear();
6307be691f3bSpatrick
6308be691f3bSpatrick std::set<std::string> executing_uuids;
6309be691f3bSpatrick ThreadList &thread_list(process_sp->GetThreadList());
6310be691f3bSpatrick for (uint32_t i = 0; i < thread_list.GetSize(); i++) {
6311be691f3bSpatrick ThreadSP thread_sp = thread_list.GetThreadAtIndex(i);
6312be691f3bSpatrick uint32_t stack_frame_count = thread_sp->GetStackFrameCount();
6313be691f3bSpatrick for (uint32_t j = 0; j < stack_frame_count; j++) {
6314be691f3bSpatrick StackFrameSP stack_frame_sp = thread_sp->GetStackFrameAtIndex(j);
6315be691f3bSpatrick Address pc = stack_frame_sp->GetFrameCodeAddress();
6316be691f3bSpatrick ModuleSP module_sp = pc.GetModule();
6317be691f3bSpatrick if (module_sp) {
6318be691f3bSpatrick UUID uuid = module_sp->GetUUID();
6319be691f3bSpatrick if (uuid.IsValid()) {
6320be691f3bSpatrick executing_uuids.insert(uuid.GetAsString());
6321*f6aab3d8Srobert modules.AppendIfNeeded(module_sp);
6322be691f3bSpatrick }
6323be691f3bSpatrick }
6324be691f3bSpatrick }
6325be691f3bSpatrick }
6326*f6aab3d8Srobert size_t modules_count = modules.GetSize();
6327be691f3bSpatrick
6328be691f3bSpatrick struct all_image_infos_header infos;
6329be691f3bSpatrick infos.version = 1;
6330be691f3bSpatrick infos.imgcount = modules_count;
6331be691f3bSpatrick infos.entries_size = sizeof(image_entry);
6332be691f3bSpatrick infos.entries_fileoff = initial_file_offset + sizeof(all_image_infos_header);
6333be691f3bSpatrick infos.unused = 0;
6334be691f3bSpatrick
6335be691f3bSpatrick all_image_infos_payload.PutHex32(infos.version);
6336be691f3bSpatrick all_image_infos_payload.PutHex32(infos.imgcount);
6337be691f3bSpatrick all_image_infos_payload.PutHex64(infos.entries_fileoff);
6338be691f3bSpatrick all_image_infos_payload.PutHex32(infos.entries_size);
6339be691f3bSpatrick all_image_infos_payload.PutHex32(infos.unused);
6340be691f3bSpatrick
6341be691f3bSpatrick // First create the structures for all of the segment name+vmaddr vectors
6342be691f3bSpatrick // for each module, so we will know the size of them as we add the
6343be691f3bSpatrick // module entries.
6344be691f3bSpatrick std::vector<std::vector<segment_vmaddr>> modules_segment_vmaddrs;
6345be691f3bSpatrick for (size_t i = 0; i < modules_count; i++) {
6346be691f3bSpatrick ModuleSP module = modules.GetModuleAtIndex(i);
6347be691f3bSpatrick
6348be691f3bSpatrick SectionList *sections = module->GetSectionList();
6349be691f3bSpatrick size_t sections_count = sections->GetSize();
6350be691f3bSpatrick std::vector<segment_vmaddr> segment_vmaddrs;
6351be691f3bSpatrick for (size_t j = 0; j < sections_count; j++) {
6352be691f3bSpatrick SectionSP section = sections->GetSectionAtIndex(j);
6353be691f3bSpatrick if (!section->GetParent().get()) {
6354be691f3bSpatrick addr_t vmaddr = section->GetLoadBaseAddress(&target);
6355be691f3bSpatrick if (vmaddr == LLDB_INVALID_ADDRESS)
6356be691f3bSpatrick continue;
6357be691f3bSpatrick ConstString name = section->GetName();
6358be691f3bSpatrick segment_vmaddr seg_vmaddr;
6359*f6aab3d8Srobert // This is the uncommon case where strncpy is exactly
6360*f6aab3d8Srobert // the right one, doesn't need to be nul terminated.
6361*f6aab3d8Srobert // The segment name in a Mach-O LC_SEGMENT/LC_SEGMENT_64 is char[16] and
6362*f6aab3d8Srobert // is not guaranteed to be nul-terminated if all 16 characters are
6363*f6aab3d8Srobert // used.
6364*f6aab3d8Srobert // coverity[buffer_size_warning]
6365be691f3bSpatrick strncpy(seg_vmaddr.segname, name.AsCString(),
6366be691f3bSpatrick sizeof(seg_vmaddr.segname));
6367be691f3bSpatrick seg_vmaddr.vmaddr = vmaddr;
6368be691f3bSpatrick seg_vmaddr.unused = 0;
6369be691f3bSpatrick segment_vmaddrs.push_back(seg_vmaddr);
6370be691f3bSpatrick }
6371be691f3bSpatrick }
6372be691f3bSpatrick modules_segment_vmaddrs.push_back(segment_vmaddrs);
6373be691f3bSpatrick }
6374be691f3bSpatrick
6375be691f3bSpatrick offset_t size_of_vmaddr_structs = 0;
6376be691f3bSpatrick for (size_t i = 0; i < modules_segment_vmaddrs.size(); i++) {
6377be691f3bSpatrick size_of_vmaddr_structs +=
6378be691f3bSpatrick modules_segment_vmaddrs[i].size() * sizeof(segment_vmaddr);
6379be691f3bSpatrick }
6380be691f3bSpatrick
6381be691f3bSpatrick offset_t size_of_filepath_cstrings = 0;
6382be691f3bSpatrick for (size_t i = 0; i < modules_count; i++) {
6383be691f3bSpatrick ModuleSP module_sp = modules.GetModuleAtIndex(i);
6384be691f3bSpatrick size_of_filepath_cstrings += module_sp->GetFileSpec().GetPath().size() + 1;
6385be691f3bSpatrick }
6386be691f3bSpatrick
6387be691f3bSpatrick // Calculate the file offsets of our "all image infos" payload in the
6388be691f3bSpatrick // corefile. initial_file_offset the original value passed in to this method.
6389be691f3bSpatrick
6390be691f3bSpatrick offset_t start_of_entries =
6391be691f3bSpatrick initial_file_offset + sizeof(all_image_infos_header);
6392be691f3bSpatrick offset_t start_of_seg_vmaddrs =
6393be691f3bSpatrick start_of_entries + sizeof(image_entry) * modules_count;
6394be691f3bSpatrick offset_t start_of_filenames = start_of_seg_vmaddrs + size_of_vmaddr_structs;
6395be691f3bSpatrick
6396be691f3bSpatrick offset_t final_file_offset = start_of_filenames + size_of_filepath_cstrings;
6397be691f3bSpatrick
6398be691f3bSpatrick // Now write the one-per-module 'struct image_entry' into the
6399be691f3bSpatrick // StringStream; keep track of where the struct segment_vmaddr
6400be691f3bSpatrick // entries for each module will end up in the corefile.
6401be691f3bSpatrick
6402be691f3bSpatrick offset_t current_string_offset = start_of_filenames;
6403be691f3bSpatrick offset_t current_segaddrs_offset = start_of_seg_vmaddrs;
6404be691f3bSpatrick std::vector<struct image_entry> image_entries;
6405be691f3bSpatrick for (size_t i = 0; i < modules_count; i++) {
6406be691f3bSpatrick ModuleSP module_sp = modules.GetModuleAtIndex(i);
6407be691f3bSpatrick
6408be691f3bSpatrick struct image_entry ent;
6409be691f3bSpatrick memcpy(&ent.uuid, module_sp->GetUUID().GetBytes().data(), sizeof(ent.uuid));
6410be691f3bSpatrick if (modules_segment_vmaddrs[i].size() > 0) {
6411be691f3bSpatrick ent.segment_count = modules_segment_vmaddrs[i].size();
6412be691f3bSpatrick ent.seg_addrs_offset = current_segaddrs_offset;
6413be691f3bSpatrick }
6414be691f3bSpatrick ent.filepath_offset = current_string_offset;
6415be691f3bSpatrick ObjectFile *objfile = module_sp->GetObjectFile();
6416be691f3bSpatrick if (objfile) {
6417be691f3bSpatrick Address base_addr(objfile->GetBaseAddress());
6418be691f3bSpatrick if (base_addr.IsValid()) {
6419be691f3bSpatrick ent.load_address = base_addr.GetLoadAddress(&target);
6420be691f3bSpatrick }
6421be691f3bSpatrick }
6422be691f3bSpatrick
6423be691f3bSpatrick all_image_infos_payload.PutHex64(ent.filepath_offset);
6424be691f3bSpatrick all_image_infos_payload.PutRawBytes(ent.uuid, sizeof(ent.uuid));
6425be691f3bSpatrick all_image_infos_payload.PutHex64(ent.load_address);
6426be691f3bSpatrick all_image_infos_payload.PutHex64(ent.seg_addrs_offset);
6427be691f3bSpatrick all_image_infos_payload.PutHex32(ent.segment_count);
6428be691f3bSpatrick
6429be691f3bSpatrick if (executing_uuids.find(module_sp->GetUUID().GetAsString()) !=
6430be691f3bSpatrick executing_uuids.end())
6431be691f3bSpatrick all_image_infos_payload.PutHex32(1);
6432be691f3bSpatrick else
6433be691f3bSpatrick all_image_infos_payload.PutHex32(0);
6434be691f3bSpatrick
6435be691f3bSpatrick current_segaddrs_offset += ent.segment_count * sizeof(segment_vmaddr);
6436be691f3bSpatrick current_string_offset += module_sp->GetFileSpec().GetPath().size() + 1;
6437be691f3bSpatrick }
6438be691f3bSpatrick
6439be691f3bSpatrick // Now write the struct segment_vmaddr entries into the StringStream.
6440be691f3bSpatrick
6441be691f3bSpatrick for (size_t i = 0; i < modules_segment_vmaddrs.size(); i++) {
6442be691f3bSpatrick if (modules_segment_vmaddrs[i].size() == 0)
6443be691f3bSpatrick continue;
6444be691f3bSpatrick for (struct segment_vmaddr segvm : modules_segment_vmaddrs[i]) {
6445be691f3bSpatrick all_image_infos_payload.PutRawBytes(segvm.segname, sizeof(segvm.segname));
6446be691f3bSpatrick all_image_infos_payload.PutHex64(segvm.vmaddr);
6447be691f3bSpatrick all_image_infos_payload.PutHex64(segvm.unused);
6448be691f3bSpatrick }
6449be691f3bSpatrick }
6450be691f3bSpatrick
6451be691f3bSpatrick for (size_t i = 0; i < modules_count; i++) {
6452be691f3bSpatrick ModuleSP module_sp = modules.GetModuleAtIndex(i);
6453be691f3bSpatrick std::string filepath = module_sp->GetFileSpec().GetPath();
6454be691f3bSpatrick all_image_infos_payload.PutRawBytes(filepath.data(), filepath.size() + 1);
6455be691f3bSpatrick }
6456be691f3bSpatrick
6457be691f3bSpatrick return final_file_offset;
6458be691f3bSpatrick }
6459be691f3bSpatrick
6460be691f3bSpatrick // Temp struct used to combine contiguous memory regions with
6461be691f3bSpatrick // identical permissions.
6462be691f3bSpatrick struct page_object {
6463be691f3bSpatrick addr_t addr;
6464be691f3bSpatrick addr_t size;
6465be691f3bSpatrick uint32_t prot;
6466be691f3bSpatrick };
6467be691f3bSpatrick
6468061da546Spatrick bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
6469be691f3bSpatrick const FileSpec &outfile,
6470be691f3bSpatrick lldb::SaveCoreStyle &core_style, Status &error) {
6471061da546Spatrick if (!process_sp)
6472061da546Spatrick return false;
6473061da546Spatrick
6474*f6aab3d8Srobert // Default on macOS is to create a dirty-memory-only corefile.
6475*f6aab3d8Srobert if (core_style == SaveCoreStyle::eSaveCoreUnspecified) {
6476be691f3bSpatrick core_style = SaveCoreStyle::eSaveCoreDirtyOnly;
6477be691f3bSpatrick }
6478be691f3bSpatrick
6479061da546Spatrick Target &target = process_sp->GetTarget();
6480061da546Spatrick const ArchSpec target_arch = target.GetArchitecture();
6481061da546Spatrick const llvm::Triple &target_triple = target_arch.GetTriple();
6482061da546Spatrick if (target_triple.getVendor() == llvm::Triple::Apple &&
6483061da546Spatrick (target_triple.getOS() == llvm::Triple::MacOSX ||
6484061da546Spatrick target_triple.getOS() == llvm::Triple::IOS ||
6485061da546Spatrick target_triple.getOS() == llvm::Triple::WatchOS ||
6486061da546Spatrick target_triple.getOS() == llvm::Triple::TvOS)) {
6487061da546Spatrick // NEED_BRIDGEOS_TRIPLE target_triple.getOS() == llvm::Triple::BridgeOS))
6488061da546Spatrick // {
6489061da546Spatrick bool make_core = false;
6490061da546Spatrick switch (target_arch.GetMachine()) {
6491061da546Spatrick case llvm::Triple::aarch64:
6492061da546Spatrick case llvm::Triple::aarch64_32:
6493061da546Spatrick case llvm::Triple::arm:
6494061da546Spatrick case llvm::Triple::thumb:
6495061da546Spatrick case llvm::Triple::x86:
6496061da546Spatrick case llvm::Triple::x86_64:
6497061da546Spatrick make_core = true;
6498061da546Spatrick break;
6499061da546Spatrick default:
6500061da546Spatrick error.SetErrorStringWithFormat("unsupported core architecture: %s",
6501061da546Spatrick target_triple.str().c_str());
6502061da546Spatrick break;
6503061da546Spatrick }
6504061da546Spatrick
6505061da546Spatrick if (make_core) {
6506be691f3bSpatrick std::vector<llvm::MachO::segment_command_64> segment_load_commands;
6507061da546Spatrick // uint32_t range_info_idx = 0;
6508061da546Spatrick MemoryRegionInfo range_info;
6509061da546Spatrick Status range_error = process_sp->GetMemoryRegionInfo(0, range_info);
6510061da546Spatrick const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
6511061da546Spatrick const ByteOrder byte_order = target_arch.GetByteOrder();
6512be691f3bSpatrick std::vector<page_object> pages_to_copy;
6513be691f3bSpatrick
6514061da546Spatrick if (range_error.Success()) {
6515061da546Spatrick while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
6516061da546Spatrick // Calculate correct protections
6517061da546Spatrick uint32_t prot = 0;
6518061da546Spatrick if (range_info.GetReadable() == MemoryRegionInfo::eYes)
6519061da546Spatrick prot |= VM_PROT_READ;
6520061da546Spatrick if (range_info.GetWritable() == MemoryRegionInfo::eYes)
6521061da546Spatrick prot |= VM_PROT_WRITE;
6522061da546Spatrick if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
6523061da546Spatrick prot |= VM_PROT_EXECUTE;
6524061da546Spatrick
6525be691f3bSpatrick const addr_t addr = range_info.GetRange().GetRangeBase();
6526be691f3bSpatrick const addr_t size = range_info.GetRange().GetByteSize();
6527be691f3bSpatrick
6528be691f3bSpatrick if (size == 0)
6529061da546Spatrick break;
6530be691f3bSpatrick
6531*f6aab3d8Srobert bool include_this_region = true;
6532*f6aab3d8Srobert bool dirty_pages_only = false;
6533*f6aab3d8Srobert if (core_style == SaveCoreStyle::eSaveCoreStackOnly) {
6534*f6aab3d8Srobert dirty_pages_only = true;
6535*f6aab3d8Srobert if (range_info.IsStackMemory() != MemoryRegionInfo::eYes) {
6536*f6aab3d8Srobert include_this_region = false;
6537*f6aab3d8Srobert }
6538*f6aab3d8Srobert }
6539*f6aab3d8Srobert if (core_style == SaveCoreStyle::eSaveCoreDirtyOnly) {
6540*f6aab3d8Srobert dirty_pages_only = true;
6541*f6aab3d8Srobert }
6542*f6aab3d8Srobert
6543*f6aab3d8Srobert if (prot != 0 && include_this_region) {
6544be691f3bSpatrick addr_t pagesize = range_info.GetPageSize();
6545*f6aab3d8Srobert const std::optional<std::vector<addr_t>> &dirty_page_list =
6546be691f3bSpatrick range_info.GetDirtyPageList();
6547*f6aab3d8Srobert if (dirty_pages_only && dirty_page_list) {
6548*f6aab3d8Srobert for (addr_t dirtypage : *dirty_page_list) {
6549be691f3bSpatrick page_object obj;
6550be691f3bSpatrick obj.addr = dirtypage;
6551be691f3bSpatrick obj.size = pagesize;
6552be691f3bSpatrick obj.prot = prot;
6553be691f3bSpatrick pages_to_copy.push_back(obj);
6554be691f3bSpatrick }
6555be691f3bSpatrick } else {
6556be691f3bSpatrick page_object obj;
6557be691f3bSpatrick obj.addr = addr;
6558be691f3bSpatrick obj.size = size;
6559be691f3bSpatrick obj.prot = prot;
6560be691f3bSpatrick pages_to_copy.push_back(obj);
6561be691f3bSpatrick }
6562061da546Spatrick }
6563061da546Spatrick
6564061da546Spatrick range_error = process_sp->GetMemoryRegionInfo(
6565061da546Spatrick range_info.GetRange().GetRangeEnd(), range_info);
6566061da546Spatrick if (range_error.Fail())
6567061da546Spatrick break;
6568061da546Spatrick }
6569061da546Spatrick
6570be691f3bSpatrick // Combine contiguous entries that have the same
6571be691f3bSpatrick // protections so we don't have an excess of
6572be691f3bSpatrick // load commands.
6573be691f3bSpatrick std::vector<page_object> combined_page_objects;
6574be691f3bSpatrick page_object last_obj;
6575be691f3bSpatrick last_obj.addr = LLDB_INVALID_ADDRESS;
6576*f6aab3d8Srobert last_obj.size = 0;
6577be691f3bSpatrick for (page_object obj : pages_to_copy) {
6578be691f3bSpatrick if (last_obj.addr == LLDB_INVALID_ADDRESS) {
6579be691f3bSpatrick last_obj = obj;
6580be691f3bSpatrick continue;
6581be691f3bSpatrick }
6582be691f3bSpatrick if (last_obj.addr + last_obj.size == obj.addr &&
6583be691f3bSpatrick last_obj.prot == obj.prot) {
6584be691f3bSpatrick last_obj.size += obj.size;
6585be691f3bSpatrick continue;
6586be691f3bSpatrick }
6587be691f3bSpatrick combined_page_objects.push_back(last_obj);
6588be691f3bSpatrick last_obj = obj;
6589be691f3bSpatrick }
6590*f6aab3d8Srobert // Add the last entry we were looking to combine
6591*f6aab3d8Srobert // on to the array.
6592*f6aab3d8Srobert if (last_obj.addr != LLDB_INVALID_ADDRESS && last_obj.size != 0)
6593*f6aab3d8Srobert combined_page_objects.push_back(last_obj);
6594be691f3bSpatrick
6595be691f3bSpatrick for (page_object obj : combined_page_objects) {
6596be691f3bSpatrick uint32_t cmd_type = LC_SEGMENT_64;
6597be691f3bSpatrick uint32_t segment_size = sizeof(llvm::MachO::segment_command_64);
6598be691f3bSpatrick if (addr_byte_size == 4) {
6599be691f3bSpatrick cmd_type = LC_SEGMENT;
6600be691f3bSpatrick segment_size = sizeof(llvm::MachO::segment_command);
6601be691f3bSpatrick }
6602be691f3bSpatrick llvm::MachO::segment_command_64 segment = {
6603be691f3bSpatrick cmd_type, // uint32_t cmd;
6604be691f3bSpatrick segment_size, // uint32_t cmdsize;
6605be691f3bSpatrick {0}, // char segname[16];
6606be691f3bSpatrick obj.addr, // uint64_t vmaddr; // uint32_t for 32-bit
6607be691f3bSpatrick // Mach-O
6608be691f3bSpatrick obj.size, // uint64_t vmsize; // uint32_t for 32-bit
6609be691f3bSpatrick // Mach-O
6610be691f3bSpatrick 0, // uint64_t fileoff; // uint32_t for 32-bit Mach-O
6611be691f3bSpatrick obj.size, // uint64_t filesize; // uint32_t for 32-bit
6612be691f3bSpatrick // Mach-O
6613be691f3bSpatrick obj.prot, // uint32_t maxprot;
6614be691f3bSpatrick obj.prot, // uint32_t initprot;
6615be691f3bSpatrick 0, // uint32_t nsects;
6616be691f3bSpatrick 0}; // uint32_t flags;
6617be691f3bSpatrick segment_load_commands.push_back(segment);
6618be691f3bSpatrick }
6619be691f3bSpatrick
6620061da546Spatrick StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
6621061da546Spatrick
6622be691f3bSpatrick llvm::MachO::mach_header_64 mach_header;
6623061da546Spatrick if (addr_byte_size == 8) {
6624061da546Spatrick mach_header.magic = MH_MAGIC_64;
6625061da546Spatrick } else {
6626061da546Spatrick mach_header.magic = MH_MAGIC;
6627061da546Spatrick }
6628061da546Spatrick mach_header.cputype = target_arch.GetMachOCPUType();
6629061da546Spatrick mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
6630061da546Spatrick mach_header.filetype = MH_CORE;
6631061da546Spatrick mach_header.ncmds = segment_load_commands.size();
6632061da546Spatrick mach_header.flags = 0;
6633061da546Spatrick mach_header.reserved = 0;
6634061da546Spatrick ThreadList &thread_list = process_sp->GetThreadList();
6635061da546Spatrick const uint32_t num_threads = thread_list.GetSize();
6636061da546Spatrick
6637061da546Spatrick // Make an array of LC_THREAD data items. Each one contains the
6638061da546Spatrick // contents of the LC_THREAD load command. The data doesn't contain
6639061da546Spatrick // the load command + load command size, we will add the load command
6640061da546Spatrick // and load command size as we emit the data.
6641061da546Spatrick std::vector<StreamString> LC_THREAD_datas(num_threads);
6642061da546Spatrick for (auto &LC_THREAD_data : LC_THREAD_datas) {
6643061da546Spatrick LC_THREAD_data.GetFlags().Set(Stream::eBinary);
6644061da546Spatrick LC_THREAD_data.SetAddressByteSize(addr_byte_size);
6645061da546Spatrick LC_THREAD_data.SetByteOrder(byte_order);
6646061da546Spatrick }
6647061da546Spatrick for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
6648061da546Spatrick ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
6649061da546Spatrick if (thread_sp) {
6650061da546Spatrick switch (mach_header.cputype) {
6651061da546Spatrick case llvm::MachO::CPU_TYPE_ARM64:
6652061da546Spatrick case llvm::MachO::CPU_TYPE_ARM64_32:
6653061da546Spatrick RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
6654061da546Spatrick thread_sp.get(), LC_THREAD_datas[thread_idx]);
6655061da546Spatrick break;
6656061da546Spatrick
6657061da546Spatrick case llvm::MachO::CPU_TYPE_ARM:
6658061da546Spatrick RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
6659061da546Spatrick thread_sp.get(), LC_THREAD_datas[thread_idx]);
6660061da546Spatrick break;
6661061da546Spatrick
6662061da546Spatrick case llvm::MachO::CPU_TYPE_I386:
6663061da546Spatrick RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
6664061da546Spatrick thread_sp.get(), LC_THREAD_datas[thread_idx]);
6665061da546Spatrick break;
6666061da546Spatrick
6667061da546Spatrick case llvm::MachO::CPU_TYPE_X86_64:
6668061da546Spatrick RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
6669061da546Spatrick thread_sp.get(), LC_THREAD_datas[thread_idx]);
6670061da546Spatrick break;
6671061da546Spatrick }
6672061da546Spatrick }
6673061da546Spatrick }
6674061da546Spatrick
6675061da546Spatrick // The size of the load command is the size of the segments...
6676061da546Spatrick if (addr_byte_size == 8) {
6677be691f3bSpatrick mach_header.sizeofcmds = segment_load_commands.size() *
6678be691f3bSpatrick sizeof(llvm::MachO::segment_command_64);
6679061da546Spatrick } else {
6680be691f3bSpatrick mach_header.sizeofcmds = segment_load_commands.size() *
6681be691f3bSpatrick sizeof(llvm::MachO::segment_command);
6682061da546Spatrick }
6683061da546Spatrick
6684061da546Spatrick // and the size of all LC_THREAD load command
6685061da546Spatrick for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6686061da546Spatrick ++mach_header.ncmds;
6687061da546Spatrick mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
6688061da546Spatrick }
6689061da546Spatrick
6690be691f3bSpatrick // Bits will be set to indicate which bits are NOT used in
6691be691f3bSpatrick // addressing in this process or 0 for unknown.
6692be691f3bSpatrick uint64_t address_mask = process_sp->GetCodeAddressMask();
6693be691f3bSpatrick if (address_mask != 0) {
6694be691f3bSpatrick // LC_NOTE "addrable bits"
6695be691f3bSpatrick mach_header.ncmds++;
6696be691f3bSpatrick mach_header.sizeofcmds += sizeof(llvm::MachO::note_command);
6697be691f3bSpatrick }
6698be691f3bSpatrick
6699be691f3bSpatrick // LC_NOTE "all image infos"
6700be691f3bSpatrick mach_header.ncmds++;
6701be691f3bSpatrick mach_header.sizeofcmds += sizeof(llvm::MachO::note_command);
6702be691f3bSpatrick
6703061da546Spatrick // Write the mach header
6704061da546Spatrick buffer.PutHex32(mach_header.magic);
6705061da546Spatrick buffer.PutHex32(mach_header.cputype);
6706061da546Spatrick buffer.PutHex32(mach_header.cpusubtype);
6707061da546Spatrick buffer.PutHex32(mach_header.filetype);
6708061da546Spatrick buffer.PutHex32(mach_header.ncmds);
6709061da546Spatrick buffer.PutHex32(mach_header.sizeofcmds);
6710061da546Spatrick buffer.PutHex32(mach_header.flags);
6711061da546Spatrick if (addr_byte_size == 8) {
6712061da546Spatrick buffer.PutHex32(mach_header.reserved);
6713061da546Spatrick }
6714061da546Spatrick
6715061da546Spatrick // Skip the mach header and all load commands and align to the next
6716061da546Spatrick // 0x1000 byte boundary
6717061da546Spatrick addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
6718be691f3bSpatrick
6719be691f3bSpatrick file_offset = llvm::alignTo(file_offset, 16);
6720be691f3bSpatrick std::vector<std::unique_ptr<LCNoteEntry>> lc_notes;
6721be691f3bSpatrick
6722be691f3bSpatrick // Add "addrable bits" LC_NOTE when an address mask is available
6723be691f3bSpatrick if (address_mask != 0) {
6724be691f3bSpatrick std::unique_ptr<LCNoteEntry> addrable_bits_lcnote_up(
6725be691f3bSpatrick new LCNoteEntry(addr_byte_size, byte_order));
6726be691f3bSpatrick addrable_bits_lcnote_up->name = "addrable bits";
6727be691f3bSpatrick addrable_bits_lcnote_up->payload_file_offset = file_offset;
6728be691f3bSpatrick int bits = std::bitset<64>(~address_mask).count();
6729be691f3bSpatrick addrable_bits_lcnote_up->payload.PutHex32(3); // version
6730be691f3bSpatrick addrable_bits_lcnote_up->payload.PutHex32(
6731be691f3bSpatrick bits); // # of bits used for addressing
6732be691f3bSpatrick addrable_bits_lcnote_up->payload.PutHex64(0); // unused
6733be691f3bSpatrick
6734be691f3bSpatrick file_offset += addrable_bits_lcnote_up->payload.GetSize();
6735be691f3bSpatrick
6736be691f3bSpatrick lc_notes.push_back(std::move(addrable_bits_lcnote_up));
6737061da546Spatrick }
6738061da546Spatrick
6739be691f3bSpatrick // Add "all image infos" LC_NOTE
6740be691f3bSpatrick std::unique_ptr<LCNoteEntry> all_image_infos_lcnote_up(
6741be691f3bSpatrick new LCNoteEntry(addr_byte_size, byte_order));
6742be691f3bSpatrick all_image_infos_lcnote_up->name = "all image infos";
6743be691f3bSpatrick all_image_infos_lcnote_up->payload_file_offset = file_offset;
6744be691f3bSpatrick file_offset = CreateAllImageInfosPayload(
6745*f6aab3d8Srobert process_sp, file_offset, all_image_infos_lcnote_up->payload,
6746*f6aab3d8Srobert core_style);
6747be691f3bSpatrick lc_notes.push_back(std::move(all_image_infos_lcnote_up));
6748be691f3bSpatrick
6749be691f3bSpatrick // Add LC_NOTE load commands
6750be691f3bSpatrick for (auto &lcnote : lc_notes) {
6751be691f3bSpatrick // Add the LC_NOTE load command to the file.
6752be691f3bSpatrick buffer.PutHex32(LC_NOTE);
6753be691f3bSpatrick buffer.PutHex32(sizeof(llvm::MachO::note_command));
6754be691f3bSpatrick char namebuf[16];
6755be691f3bSpatrick memset(namebuf, 0, sizeof(namebuf));
6756*f6aab3d8Srobert // This is the uncommon case where strncpy is exactly
6757be691f3bSpatrick // the right one, doesn't need to be nul terminated.
6758*f6aab3d8Srobert // LC_NOTE name field is char[16] and is not guaranteed to be
6759*f6aab3d8Srobert // nul-terminated.
6760*f6aab3d8Srobert // coverity[buffer_size_warning]
6761be691f3bSpatrick strncpy(namebuf, lcnote->name.c_str(), sizeof(namebuf));
6762be691f3bSpatrick buffer.PutRawBytes(namebuf, sizeof(namebuf));
6763be691f3bSpatrick buffer.PutHex64(lcnote->payload_file_offset);
6764be691f3bSpatrick buffer.PutHex64(lcnote->payload.GetSize());
6765be691f3bSpatrick }
6766be691f3bSpatrick
6767be691f3bSpatrick // Align to 4096-byte page boundary for the LC_SEGMENTs.
6768be691f3bSpatrick file_offset = llvm::alignTo(file_offset, 4096);
6769be691f3bSpatrick
6770061da546Spatrick for (auto &segment : segment_load_commands) {
6771061da546Spatrick segment.fileoff = file_offset;
6772061da546Spatrick file_offset += segment.filesize;
6773061da546Spatrick }
6774061da546Spatrick
6775061da546Spatrick // Write out all of the LC_THREAD load commands
6776061da546Spatrick for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6777061da546Spatrick const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6778061da546Spatrick buffer.PutHex32(LC_THREAD);
6779061da546Spatrick buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
6780061da546Spatrick buffer.Write(LC_THREAD_data.GetString().data(), LC_THREAD_data_size);
6781061da546Spatrick }
6782061da546Spatrick
6783061da546Spatrick // Write out all of the segment load commands
6784061da546Spatrick for (const auto &segment : segment_load_commands) {
6785061da546Spatrick buffer.PutHex32(segment.cmd);
6786061da546Spatrick buffer.PutHex32(segment.cmdsize);
6787061da546Spatrick buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
6788061da546Spatrick if (addr_byte_size == 8) {
6789061da546Spatrick buffer.PutHex64(segment.vmaddr);
6790061da546Spatrick buffer.PutHex64(segment.vmsize);
6791061da546Spatrick buffer.PutHex64(segment.fileoff);
6792061da546Spatrick buffer.PutHex64(segment.filesize);
6793061da546Spatrick } else {
6794061da546Spatrick buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
6795061da546Spatrick buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
6796061da546Spatrick buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
6797061da546Spatrick buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
6798061da546Spatrick }
6799061da546Spatrick buffer.PutHex32(segment.maxprot);
6800061da546Spatrick buffer.PutHex32(segment.initprot);
6801061da546Spatrick buffer.PutHex32(segment.nsects);
6802061da546Spatrick buffer.PutHex32(segment.flags);
6803061da546Spatrick }
6804061da546Spatrick
6805061da546Spatrick std::string core_file_path(outfile.GetPath());
6806061da546Spatrick auto core_file = FileSystem::Instance().Open(
6807*f6aab3d8Srobert outfile, File::eOpenOptionWriteOnly | File::eOpenOptionTruncate |
6808061da546Spatrick File::eOpenOptionCanCreate);
6809061da546Spatrick if (!core_file) {
6810061da546Spatrick error = core_file.takeError();
6811061da546Spatrick } else {
6812061da546Spatrick // Read 1 page at a time
6813061da546Spatrick uint8_t bytes[0x1000];
6814061da546Spatrick // Write the mach header and load commands out to the core file
6815061da546Spatrick size_t bytes_written = buffer.GetString().size();
6816061da546Spatrick error =
6817061da546Spatrick core_file.get()->Write(buffer.GetString().data(), bytes_written);
6818061da546Spatrick if (error.Success()) {
6819be691f3bSpatrick
6820be691f3bSpatrick for (auto &lcnote : lc_notes) {
6821be691f3bSpatrick if (core_file.get()->SeekFromStart(lcnote->payload_file_offset) ==
6822be691f3bSpatrick -1) {
6823be691f3bSpatrick error.SetErrorStringWithFormat("Unable to seek to corefile pos "
6824be691f3bSpatrick "to write '%s' LC_NOTE payload",
6825be691f3bSpatrick lcnote->name.c_str());
6826be691f3bSpatrick return false;
6827be691f3bSpatrick }
6828be691f3bSpatrick bytes_written = lcnote->payload.GetSize();
6829be691f3bSpatrick error = core_file.get()->Write(lcnote->payload.GetData(),
6830be691f3bSpatrick bytes_written);
6831be691f3bSpatrick if (!error.Success())
6832be691f3bSpatrick return false;
6833be691f3bSpatrick }
6834be691f3bSpatrick
6835061da546Spatrick // Now write the file data for all memory segments in the process
6836061da546Spatrick for (const auto &segment : segment_load_commands) {
6837061da546Spatrick if (core_file.get()->SeekFromStart(segment.fileoff) == -1) {
6838061da546Spatrick error.SetErrorStringWithFormat(
6839061da546Spatrick "unable to seek to offset 0x%" PRIx64 " in '%s'",
6840061da546Spatrick segment.fileoff, core_file_path.c_str());
6841061da546Spatrick break;
6842061da546Spatrick }
6843061da546Spatrick
6844be691f3bSpatrick target.GetDebugger().GetAsyncOutputStream()->Printf(
6845be691f3bSpatrick "Saving %" PRId64
6846061da546Spatrick " bytes of data for memory region at 0x%" PRIx64 "\n",
6847061da546Spatrick segment.vmsize, segment.vmaddr);
6848061da546Spatrick addr_t bytes_left = segment.vmsize;
6849061da546Spatrick addr_t addr = segment.vmaddr;
6850061da546Spatrick Status memory_read_error;
6851061da546Spatrick while (bytes_left > 0 && error.Success()) {
6852061da546Spatrick const size_t bytes_to_read =
6853061da546Spatrick bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6854061da546Spatrick
6855061da546Spatrick // In a savecore setting, we don't really care about caching,
6856061da546Spatrick // as the data is dumped and very likely never read again,
6857061da546Spatrick // so we call ReadMemoryFromInferior to bypass it.
6858061da546Spatrick const size_t bytes_read = process_sp->ReadMemoryFromInferior(
6859061da546Spatrick addr, bytes, bytes_to_read, memory_read_error);
6860061da546Spatrick
6861061da546Spatrick if (bytes_read == bytes_to_read) {
6862061da546Spatrick size_t bytes_written = bytes_read;
6863061da546Spatrick error = core_file.get()->Write(bytes, bytes_written);
6864061da546Spatrick bytes_left -= bytes_read;
6865061da546Spatrick addr += bytes_read;
6866061da546Spatrick } else {
6867061da546Spatrick // Some pages within regions are not readable, those should
6868061da546Spatrick // be zero filled
6869061da546Spatrick memset(bytes, 0, bytes_to_read);
6870061da546Spatrick size_t bytes_written = bytes_to_read;
6871061da546Spatrick error = core_file.get()->Write(bytes, bytes_written);
6872061da546Spatrick bytes_left -= bytes_to_read;
6873061da546Spatrick addr += bytes_to_read;
6874061da546Spatrick }
6875061da546Spatrick }
6876061da546Spatrick }
6877061da546Spatrick }
6878061da546Spatrick }
6879061da546Spatrick } else {
6880061da546Spatrick error.SetErrorString(
6881061da546Spatrick "process doesn't support getting memory region info");
6882061da546Spatrick }
6883061da546Spatrick }
6884061da546Spatrick return true; // This is the right plug to handle saving core files for
6885061da546Spatrick // this process
6886061da546Spatrick }
6887061da546Spatrick return false;
6888061da546Spatrick }
6889be691f3bSpatrick
6890be691f3bSpatrick ObjectFileMachO::MachOCorefileAllImageInfos
6891be691f3bSpatrick ObjectFileMachO::GetCorefileAllImageInfos() {
6892be691f3bSpatrick MachOCorefileAllImageInfos image_infos;
6893be691f3bSpatrick
6894be691f3bSpatrick // Look for an "all image infos" LC_NOTE.
6895be691f3bSpatrick lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
6896be691f3bSpatrick for (uint32_t i = 0; i < m_header.ncmds; ++i) {
6897be691f3bSpatrick const uint32_t cmd_offset = offset;
6898*f6aab3d8Srobert llvm::MachO::load_command lc = {};
6899be691f3bSpatrick if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
6900be691f3bSpatrick break;
6901be691f3bSpatrick if (lc.cmd == LC_NOTE) {
6902be691f3bSpatrick char data_owner[17];
6903be691f3bSpatrick m_data.CopyData(offset, 16, data_owner);
6904be691f3bSpatrick data_owner[16] = '\0';
6905be691f3bSpatrick offset += 16;
6906be691f3bSpatrick uint64_t fileoff = m_data.GetU64_unchecked(&offset);
6907be691f3bSpatrick offset += 4; /* size unused */
6908be691f3bSpatrick
6909be691f3bSpatrick if (strcmp("all image infos", data_owner) == 0) {
6910be691f3bSpatrick offset = fileoff;
6911be691f3bSpatrick // Read the struct all_image_infos_header.
6912be691f3bSpatrick uint32_t version = m_data.GetU32(&offset);
6913be691f3bSpatrick if (version != 1) {
6914be691f3bSpatrick return image_infos;
6915be691f3bSpatrick }
6916be691f3bSpatrick uint32_t imgcount = m_data.GetU32(&offset);
6917be691f3bSpatrick uint64_t entries_fileoff = m_data.GetU64(&offset);
6918*f6aab3d8Srobert // 'entries_size' is not used, nor is the 'unused' entry.
6919*f6aab3d8Srobert // offset += 4; // uint32_t entries_size;
6920*f6aab3d8Srobert // offset += 4; // uint32_t unused;
6921be691f3bSpatrick
6922be691f3bSpatrick offset = entries_fileoff;
6923be691f3bSpatrick for (uint32_t i = 0; i < imgcount; i++) {
6924be691f3bSpatrick // Read the struct image_entry.
6925be691f3bSpatrick offset_t filepath_offset = m_data.GetU64(&offset);
6926be691f3bSpatrick uuid_t uuid;
6927be691f3bSpatrick memcpy(&uuid, m_data.GetData(&offset, sizeof(uuid_t)),
6928be691f3bSpatrick sizeof(uuid_t));
6929be691f3bSpatrick uint64_t load_address = m_data.GetU64(&offset);
6930be691f3bSpatrick offset_t seg_addrs_offset = m_data.GetU64(&offset);
6931be691f3bSpatrick uint32_t segment_count = m_data.GetU32(&offset);
6932be691f3bSpatrick uint32_t currently_executing = m_data.GetU32(&offset);
6933be691f3bSpatrick
6934be691f3bSpatrick MachOCorefileImageEntry image_entry;
6935be691f3bSpatrick image_entry.filename = (const char *)m_data.GetCStr(&filepath_offset);
6936*f6aab3d8Srobert image_entry.uuid = UUID(uuid, sizeof(uuid_t));
6937be691f3bSpatrick image_entry.load_address = load_address;
6938be691f3bSpatrick image_entry.currently_executing = currently_executing;
6939be691f3bSpatrick
6940be691f3bSpatrick offset_t seg_vmaddrs_offset = seg_addrs_offset;
6941be691f3bSpatrick for (uint32_t j = 0; j < segment_count; j++) {
6942be691f3bSpatrick char segname[17];
6943be691f3bSpatrick m_data.CopyData(seg_vmaddrs_offset, 16, segname);
6944be691f3bSpatrick segname[16] = '\0';
6945be691f3bSpatrick seg_vmaddrs_offset += 16;
6946be691f3bSpatrick uint64_t vmaddr = m_data.GetU64(&seg_vmaddrs_offset);
6947be691f3bSpatrick seg_vmaddrs_offset += 8; /* unused */
6948be691f3bSpatrick
6949be691f3bSpatrick std::tuple<ConstString, addr_t> new_seg{ConstString(segname),
6950be691f3bSpatrick vmaddr};
6951be691f3bSpatrick image_entry.segment_load_addresses.push_back(new_seg);
6952be691f3bSpatrick }
6953be691f3bSpatrick image_infos.all_image_infos.push_back(image_entry);
6954be691f3bSpatrick }
6955*f6aab3d8Srobert } else if (strcmp("load binary", data_owner) == 0) {
6956*f6aab3d8Srobert uint32_t version = m_data.GetU32(&fileoff);
6957*f6aab3d8Srobert if (version == 1) {
6958*f6aab3d8Srobert uuid_t uuid;
6959*f6aab3d8Srobert memcpy(&uuid, m_data.GetData(&fileoff, sizeof(uuid_t)),
6960*f6aab3d8Srobert sizeof(uuid_t));
6961*f6aab3d8Srobert uint64_t load_address = m_data.GetU64(&fileoff);
6962*f6aab3d8Srobert uint64_t slide = m_data.GetU64(&fileoff);
6963*f6aab3d8Srobert std::string filename = m_data.GetCStr(&fileoff);
6964*f6aab3d8Srobert
6965*f6aab3d8Srobert MachOCorefileImageEntry image_entry;
6966*f6aab3d8Srobert image_entry.filename = filename;
6967*f6aab3d8Srobert image_entry.uuid = UUID(uuid, sizeof(uuid_t));
6968*f6aab3d8Srobert image_entry.load_address = load_address;
6969*f6aab3d8Srobert image_entry.slide = slide;
6970*f6aab3d8Srobert image_entry.currently_executing = true;
6971*f6aab3d8Srobert image_infos.all_image_infos.push_back(image_entry);
6972*f6aab3d8Srobert }
6973be691f3bSpatrick }
6974be691f3bSpatrick }
6975be691f3bSpatrick offset = cmd_offset + lc.cmdsize;
6976be691f3bSpatrick }
6977be691f3bSpatrick
6978be691f3bSpatrick return image_infos;
6979be691f3bSpatrick }
6980be691f3bSpatrick
6981be691f3bSpatrick bool ObjectFileMachO::LoadCoreFileImages(lldb_private::Process &process) {
6982be691f3bSpatrick MachOCorefileAllImageInfos image_infos = GetCorefileAllImageInfos();
6983*f6aab3d8Srobert Log *log = GetLog(LLDBLog::DynamicLoader);
6984*f6aab3d8Srobert Status error;
6985*f6aab3d8Srobert
6986*f6aab3d8Srobert bool found_platform_binary = false;
6987*f6aab3d8Srobert ModuleList added_modules;
6988*f6aab3d8Srobert for (MachOCorefileImageEntry &image : image_infos.all_image_infos) {
6989*f6aab3d8Srobert ModuleSP module_sp, local_filesystem_module_sp;
6990*f6aab3d8Srobert
6991*f6aab3d8Srobert // If this is a platform binary, it has been loaded (or registered with
6992*f6aab3d8Srobert // the DynamicLoader to be loaded), we don't need to do any further
6993*f6aab3d8Srobert // processing. We're not going to call ModulesDidLoad on this in this
6994*f6aab3d8Srobert // method, so notify==true.
6995*f6aab3d8Srobert if (process.GetTarget()
6996*f6aab3d8Srobert .GetDebugger()
6997*f6aab3d8Srobert .GetPlatformList()
6998*f6aab3d8Srobert .LoadPlatformBinaryAndSetup(&process, image.load_address,
6999*f6aab3d8Srobert true /* notify */)) {
7000*f6aab3d8Srobert LLDB_LOGF(log,
7001*f6aab3d8Srobert "ObjectFileMachO::%s binary at 0x%" PRIx64
7002*f6aab3d8Srobert " is a platform binary, has been handled by a Platform plugin.",
7003*f6aab3d8Srobert __FUNCTION__, image.load_address);
7004*f6aab3d8Srobert continue;
7005*f6aab3d8Srobert }
7006*f6aab3d8Srobert
7007*f6aab3d8Srobert // If this binary is currently executing, we want to force a
7008*f6aab3d8Srobert // possibly expensive search for the binary and its dSYM.
7009*f6aab3d8Srobert if (image.currently_executing && image.uuid.IsValid()) {
7010be691f3bSpatrick ModuleSpec module_spec;
7011be691f3bSpatrick module_spec.GetUUID() = image.uuid;
7012*f6aab3d8Srobert Symbols::DownloadObjectAndSymbolFile(module_spec, error, true);
7013be691f3bSpatrick if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
7014*f6aab3d8Srobert module_sp = process.GetTarget().GetOrCreateModule(module_spec, false);
7015*f6aab3d8Srobert process.GetTarget().GetImages().AppendIfNeeded(module_sp,
7016*f6aab3d8Srobert false /* notify */);
7017be691f3bSpatrick }
7018be691f3bSpatrick }
7019*f6aab3d8Srobert
7020*f6aab3d8Srobert // We have an address, that's the best way to discover the binary.
7021*f6aab3d8Srobert if (!module_sp && image.load_address != LLDB_INVALID_ADDRESS) {
7022*f6aab3d8Srobert module_sp = DynamicLoader::LoadBinaryWithUUIDAndAddress(
7023*f6aab3d8Srobert &process, image.filename, image.uuid, image.load_address,
7024*f6aab3d8Srobert false /* value_is_offset */, image.currently_executing,
7025*f6aab3d8Srobert false /* notify */);
7026*f6aab3d8Srobert }
7027*f6aab3d8Srobert
7028*f6aab3d8Srobert // If we have a slide, we need to find the original binary
7029*f6aab3d8Srobert // by UUID, then we can apply the slide value.
7030*f6aab3d8Srobert if (!module_sp && image.uuid.IsValid() &&
7031*f6aab3d8Srobert image.slide != LLDB_INVALID_ADDRESS) {
7032*f6aab3d8Srobert module_sp = DynamicLoader::LoadBinaryWithUUIDAndAddress(
7033*f6aab3d8Srobert &process, image.filename, image.uuid, image.slide,
7034*f6aab3d8Srobert true /* value_is_offset */, image.currently_executing,
7035*f6aab3d8Srobert false /* notify */);
7036*f6aab3d8Srobert }
7037*f6aab3d8Srobert
7038*f6aab3d8Srobert // Try to find the binary by UUID or filename on the local
7039*f6aab3d8Srobert // filesystem or in lldb's global module cache.
7040*f6aab3d8Srobert if (!module_sp) {
7041be691f3bSpatrick Status error;
7042*f6aab3d8Srobert ModuleSpec module_spec;
7043*f6aab3d8Srobert if (image.uuid.IsValid())
7044*f6aab3d8Srobert module_spec.GetUUID() = image.uuid;
7045*f6aab3d8Srobert if (!image.filename.empty())
7046*f6aab3d8Srobert module_spec.GetFileSpec() = FileSpec(image.filename.c_str());
7047*f6aab3d8Srobert module_sp =
7048be691f3bSpatrick process.GetTarget().GetOrCreateModule(module_spec, false, &error);
7049*f6aab3d8Srobert process.GetTarget().GetImages().AppendIfNeeded(module_sp,
7050*f6aab3d8Srobert false /* notify */);
7051be691f3bSpatrick }
7052*f6aab3d8Srobert
7053*f6aab3d8Srobert // We have a ModuleSP to load in the Target. Load it at the
7054*f6aab3d8Srobert // correct address/slide and notify/load scripting resources.
7055*f6aab3d8Srobert if (module_sp) {
7056*f6aab3d8Srobert added_modules.Append(module_sp, false /* notify */);
7057*f6aab3d8Srobert
7058*f6aab3d8Srobert // We have a list of segment load address
7059*f6aab3d8Srobert if (image.segment_load_addresses.size() > 0) {
7060*f6aab3d8Srobert if (log) {
7061*f6aab3d8Srobert std::string uuidstr = image.uuid.GetAsString();
7062*f6aab3d8Srobert log->Printf("ObjectFileMachO::LoadCoreFileImages adding binary '%s' "
7063*f6aab3d8Srobert "UUID %s with section load addresses",
7064*f6aab3d8Srobert image.filename.c_str(), uuidstr.c_str());
7065be691f3bSpatrick }
7066be691f3bSpatrick for (auto name_vmaddr_tuple : image.segment_load_addresses) {
7067be691f3bSpatrick SectionList *sectlist = module_sp->GetObjectFile()->GetSectionList();
7068be691f3bSpatrick if (sectlist) {
7069be691f3bSpatrick SectionSP sect_sp =
7070be691f3bSpatrick sectlist->FindSectionByName(std::get<0>(name_vmaddr_tuple));
7071be691f3bSpatrick if (sect_sp) {
7072be691f3bSpatrick process.GetTarget().SetSectionLoadAddress(
7073be691f3bSpatrick sect_sp, std::get<1>(name_vmaddr_tuple));
7074be691f3bSpatrick }
7075be691f3bSpatrick }
7076be691f3bSpatrick }
7077*f6aab3d8Srobert } else if (image.load_address != LLDB_INVALID_ADDRESS) {
7078*f6aab3d8Srobert if (log) {
7079*f6aab3d8Srobert std::string uuidstr = image.uuid.GetAsString();
7080*f6aab3d8Srobert log->Printf("ObjectFileMachO::LoadCoreFileImages adding binary '%s' "
7081*f6aab3d8Srobert "UUID %s with load address 0x%" PRIx64,
7082*f6aab3d8Srobert image.filename.c_str(), uuidstr.c_str(),
7083*f6aab3d8Srobert image.load_address);
7084*f6aab3d8Srobert }
7085*f6aab3d8Srobert const bool address_is_slide = false;
7086*f6aab3d8Srobert bool changed = false;
7087*f6aab3d8Srobert module_sp->SetLoadAddress(process.GetTarget(), image.load_address,
7088*f6aab3d8Srobert address_is_slide, changed);
7089*f6aab3d8Srobert } else if (image.slide != 0) {
7090*f6aab3d8Srobert if (log) {
7091*f6aab3d8Srobert std::string uuidstr = image.uuid.GetAsString();
7092*f6aab3d8Srobert log->Printf("ObjectFileMachO::LoadCoreFileImages adding binary '%s' "
7093*f6aab3d8Srobert "UUID %s with slide amount 0x%" PRIx64,
7094*f6aab3d8Srobert image.filename.c_str(), uuidstr.c_str(), image.slide);
7095*f6aab3d8Srobert }
7096*f6aab3d8Srobert const bool address_is_slide = true;
7097*f6aab3d8Srobert bool changed = false;
7098*f6aab3d8Srobert module_sp->SetLoadAddress(process.GetTarget(), image.slide,
7099*f6aab3d8Srobert address_is_slide, changed);
7100*f6aab3d8Srobert } else {
7101*f6aab3d8Srobert if (log) {
7102*f6aab3d8Srobert std::string uuidstr = image.uuid.GetAsString();
7103*f6aab3d8Srobert log->Printf("ObjectFileMachO::LoadCoreFileImages adding binary '%s' "
7104*f6aab3d8Srobert "UUID %s at its file address, no slide applied",
7105*f6aab3d8Srobert image.filename.c_str(), uuidstr.c_str());
7106*f6aab3d8Srobert }
7107*f6aab3d8Srobert const bool address_is_slide = true;
7108*f6aab3d8Srobert bool changed = false;
7109*f6aab3d8Srobert module_sp->SetLoadAddress(process.GetTarget(), 0, address_is_slide,
7110*f6aab3d8Srobert changed);
7111be691f3bSpatrick }
7112be691f3bSpatrick }
7113be691f3bSpatrick }
7114*f6aab3d8Srobert if (added_modules.GetSize() > 0) {
7115*f6aab3d8Srobert process.GetTarget().ModulesDidLoad(added_modules);
7116*f6aab3d8Srobert process.Flush();
7117*f6aab3d8Srobert return true;
7118*f6aab3d8Srobert }
7119*f6aab3d8Srobert // Return true if the only binary we found was the platform binary,
7120*f6aab3d8Srobert // and it was loaded outside the scope of this method.
7121*f6aab3d8Srobert if (found_platform_binary)
7122*f6aab3d8Srobert return true;
7123*f6aab3d8Srobert
7124*f6aab3d8Srobert // No binaries.
7125*f6aab3d8Srobert return false;
7126be691f3bSpatrick }
7127