1//===-- ObjectFileMachO.cpp -----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/ADT/ScopeExit.h"
10#include "llvm/ADT/StringRef.h"
11
12#include "Plugins/Process/Utility/RegisterContextDarwin_arm.h"
13#include "Plugins/Process/Utility/RegisterContextDarwin_arm64.h"
14#include "Plugins/Process/Utility/RegisterContextDarwin_i386.h"
15#include "Plugins/Process/Utility/RegisterContextDarwin_x86_64.h"
16#include "lldb/Core/Debugger.h"
17#include "lldb/Core/Module.h"
18#include "lldb/Core/ModuleSpec.h"
19#include "lldb/Core/PluginManager.h"
20#include "lldb/Core/Progress.h"
21#include "lldb/Core/Section.h"
22#include "lldb/Host/Host.h"
23#include "lldb/Symbol/DWARFCallFrameInfo.h"
24#include "lldb/Symbol/ObjectFile.h"
25#include "lldb/Target/DynamicLoader.h"
26#include "lldb/Target/MemoryRegionInfo.h"
27#include "lldb/Target/Platform.h"
28#include "lldb/Target/Process.h"
29#include "lldb/Target/SectionLoadList.h"
30#include "lldb/Target/Target.h"
31#include "lldb/Target/Thread.h"
32#include "lldb/Target/ThreadList.h"
33#include "lldb/Utility/ArchSpec.h"
34#include "lldb/Utility/DataBuffer.h"
35#include "lldb/Utility/FileSpec.h"
36#include "lldb/Utility/FileSpecList.h"
37#include "lldb/Utility/LLDBLog.h"
38#include "lldb/Utility/Log.h"
39#include "lldb/Utility/RangeMap.h"
40#include "lldb/Utility/RegisterValue.h"
41#include "lldb/Utility/Status.h"
42#include "lldb/Utility/StreamString.h"
43#include "lldb/Utility/Timer.h"
44#include "lldb/Utility/UUID.h"
45
46#include "lldb/Host/SafeMachO.h"
47
48#include "llvm/ADT/DenseSet.h"
49#include "llvm/Support/FormatVariadic.h"
50#include "llvm/Support/MemoryBuffer.h"
51
52#include "ObjectFileMachO.h"
53
54#if defined(__APPLE__)
55#include <TargetConditionals.h>
56// GetLLDBSharedCacheUUID() needs to call dlsym()
57#include <dlfcn.h>
58#include <mach/mach_init.h>
59#include <mach/vm_map.h>
60#include <lldb/Host/SafeMachO.h>
61#endif
62
63#ifndef __APPLE__
64#include "lldb/Utility/AppleUuidCompatibility.h"
65#else
66#include <uuid/uuid.h>
67#endif
68
69#include <bitset>
70#include <memory>
71#include <optional>
72
73// Unfortunately the signpost header pulls in the system MachO header, too.
74#ifdef CPU_TYPE_ARM
75#undef CPU_TYPE_ARM
76#endif
77#ifdef CPU_TYPE_ARM64
78#undef CPU_TYPE_ARM64
79#endif
80#ifdef CPU_TYPE_ARM64_32
81#undef CPU_TYPE_ARM64_32
82#endif
83#ifdef CPU_TYPE_I386
84#undef CPU_TYPE_I386
85#endif
86#ifdef CPU_TYPE_X86_64
87#undef CPU_TYPE_X86_64
88#endif
89#ifdef MH_DYLINKER
90#undef MH_DYLINKER
91#endif
92#ifdef MH_OBJECT
93#undef MH_OBJECT
94#endif
95#ifdef LC_VERSION_MIN_MACOSX
96#undef LC_VERSION_MIN_MACOSX
97#endif
98#ifdef LC_VERSION_MIN_IPHONEOS
99#undef LC_VERSION_MIN_IPHONEOS
100#endif
101#ifdef LC_VERSION_MIN_TVOS
102#undef LC_VERSION_MIN_TVOS
103#endif
104#ifdef LC_VERSION_MIN_WATCHOS
105#undef LC_VERSION_MIN_WATCHOS
106#endif
107#ifdef LC_BUILD_VERSION
108#undef LC_BUILD_VERSION
109#endif
110#ifdef PLATFORM_MACOS
111#undef PLATFORM_MACOS
112#endif
113#ifdef PLATFORM_MACCATALYST
114#undef PLATFORM_MACCATALYST
115#endif
116#ifdef PLATFORM_IOS
117#undef PLATFORM_IOS
118#endif
119#ifdef PLATFORM_IOSSIMULATOR
120#undef PLATFORM_IOSSIMULATOR
121#endif
122#ifdef PLATFORM_TVOS
123#undef PLATFORM_TVOS
124#endif
125#ifdef PLATFORM_TVOSSIMULATOR
126#undef PLATFORM_TVOSSIMULATOR
127#endif
128#ifdef PLATFORM_WATCHOS
129#undef PLATFORM_WATCHOS
130#endif
131#ifdef PLATFORM_WATCHOSSIMULATOR
132#undef PLATFORM_WATCHOSSIMULATOR
133#endif
134
135#define THUMB_ADDRESS_BIT_MASK 0xfffffffffffffffeull
136using namespace lldb;
137using namespace lldb_private;
138using namespace llvm::MachO;
139
140LLDB_PLUGIN_DEFINE(ObjectFileMachO)
141
142static void PrintRegisterValue(RegisterContext *reg_ctx, const char *name,
143 const char *alt_name, size_t reg_byte_size,
144 Stream &data) {
145 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name: name);
146 if (reg_info == nullptr)
147 reg_info = reg_ctx->GetRegisterInfoByName(reg_name: alt_name);
148 if (reg_info) {
149 lldb_private::RegisterValue reg_value;
150 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
151 if (reg_info->byte_size >= reg_byte_size)
152 data.Write(src: reg_value.GetBytes(), src_len: reg_byte_size);
153 else {
154 data.Write(src: reg_value.GetBytes(), src_len: reg_info->byte_size);
155 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n; ++i)
156 data.PutChar(ch: 0);
157 }
158 return;
159 }
160 }
161 // Just write zeros if all else fails
162 for (size_t i = 0; i < reg_byte_size; ++i)
163 data.PutChar(ch: 0);
164}
165
166class RegisterContextDarwin_x86_64_Mach : public RegisterContextDarwin_x86_64 {
167public:
168 RegisterContextDarwin_x86_64_Mach(lldb_private::Thread &thread,
169 const DataExtractor &data)
170 : RegisterContextDarwin_x86_64(thread, 0) {
171 SetRegisterDataFrom_LC_THREAD(data);
172 }
173
174 void InvalidateAllRegisters() override {
175 // Do nothing... registers are always valid...
176 }
177
178 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
179 lldb::offset_t offset = 0;
180 SetError(flavor: GPRRegSet, err_idx: Read, err: -1);
181 SetError(flavor: FPURegSet, err_idx: Read, err: -1);
182 SetError(flavor: EXCRegSet, err_idx: Read, err: -1);
183 bool done = false;
184
185 while (!done) {
186 int flavor = data.GetU32(offset_ptr: &offset);
187 if (flavor == 0)
188 done = true;
189 else {
190 uint32_t i;
191 uint32_t count = data.GetU32(offset_ptr: &offset);
192 switch (flavor) {
193 case GPRRegSet:
194 for (i = 0; i < count; ++i)
195 (&gpr.rax)[i] = data.GetU64(offset_ptr: &offset);
196 SetError(flavor: GPRRegSet, err_idx: Read, err: 0);
197 done = true;
198
199 break;
200 case FPURegSet:
201 // TODO: fill in FPU regs....
202 // SetError (FPURegSet, Read, -1);
203 done = true;
204
205 break;
206 case EXCRegSet:
207 exc.trapno = data.GetU32(offset_ptr: &offset);
208 exc.err = data.GetU32(offset_ptr: &offset);
209 exc.faultvaddr = data.GetU64(offset_ptr: &offset);
210 SetError(flavor: EXCRegSet, err_idx: Read, err: 0);
211 done = true;
212 break;
213 case 7:
214 case 8:
215 case 9:
216 // fancy flavors that encapsulate of the above flavors...
217 break;
218
219 default:
220 done = true;
221 break;
222 }
223 }
224 }
225 }
226
227 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
228 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
229 if (reg_ctx_sp) {
230 RegisterContext *reg_ctx = reg_ctx_sp.get();
231
232 data.PutHex32(uvalue: GPRRegSet); // Flavor
233 data.PutHex32(uvalue: GPRWordCount);
234 PrintRegisterValue(reg_ctx, name: "rax", alt_name: nullptr, reg_byte_size: 8, data);
235 PrintRegisterValue(reg_ctx, name: "rbx", alt_name: nullptr, reg_byte_size: 8, data);
236 PrintRegisterValue(reg_ctx, name: "rcx", alt_name: nullptr, reg_byte_size: 8, data);
237 PrintRegisterValue(reg_ctx, name: "rdx", alt_name: nullptr, reg_byte_size: 8, data);
238 PrintRegisterValue(reg_ctx, name: "rdi", alt_name: nullptr, reg_byte_size: 8, data);
239 PrintRegisterValue(reg_ctx, name: "rsi", alt_name: nullptr, reg_byte_size: 8, data);
240 PrintRegisterValue(reg_ctx, name: "rbp", alt_name: nullptr, reg_byte_size: 8, data);
241 PrintRegisterValue(reg_ctx, name: "rsp", alt_name: nullptr, reg_byte_size: 8, data);
242 PrintRegisterValue(reg_ctx, name: "r8", alt_name: nullptr, reg_byte_size: 8, data);
243 PrintRegisterValue(reg_ctx, name: "r9", alt_name: nullptr, reg_byte_size: 8, data);
244 PrintRegisterValue(reg_ctx, name: "r10", alt_name: nullptr, reg_byte_size: 8, data);
245 PrintRegisterValue(reg_ctx, name: "r11", alt_name: nullptr, reg_byte_size: 8, data);
246 PrintRegisterValue(reg_ctx, name: "r12", alt_name: nullptr, reg_byte_size: 8, data);
247 PrintRegisterValue(reg_ctx, name: "r13", alt_name: nullptr, reg_byte_size: 8, data);
248 PrintRegisterValue(reg_ctx, name: "r14", alt_name: nullptr, reg_byte_size: 8, data);
249 PrintRegisterValue(reg_ctx, name: "r15", alt_name: nullptr, reg_byte_size: 8, data);
250 PrintRegisterValue(reg_ctx, name: "rip", alt_name: nullptr, reg_byte_size: 8, data);
251 PrintRegisterValue(reg_ctx, name: "rflags", alt_name: nullptr, reg_byte_size: 8, data);
252 PrintRegisterValue(reg_ctx, name: "cs", alt_name: nullptr, reg_byte_size: 8, data);
253 PrintRegisterValue(reg_ctx, name: "fs", alt_name: nullptr, reg_byte_size: 8, data);
254 PrintRegisterValue(reg_ctx, name: "gs", alt_name: nullptr, reg_byte_size: 8, data);
255
256 // // Write out the FPU registers
257 // const size_t fpu_byte_size = sizeof(FPU);
258 // size_t bytes_written = 0;
259 // data.PutHex32 (FPURegSet);
260 // data.PutHex32 (fpu_byte_size/sizeof(uint64_t));
261 // bytes_written += data.PutHex32(0); // uint32_t pad[0]
262 // bytes_written += data.PutHex32(0); // uint32_t pad[1]
263 // bytes_written += WriteRegister (reg_ctx, "fcw", "fctrl", 2,
264 // data); // uint16_t fcw; // "fctrl"
265 // bytes_written += WriteRegister (reg_ctx, "fsw" , "fstat", 2,
266 // data); // uint16_t fsw; // "fstat"
267 // bytes_written += WriteRegister (reg_ctx, "ftw" , "ftag", 1,
268 // data); // uint8_t ftw; // "ftag"
269 // bytes_written += data.PutHex8 (0); // uint8_t pad1;
270 // bytes_written += WriteRegister (reg_ctx, "fop" , NULL, 2,
271 // data); // uint16_t fop; // "fop"
272 // bytes_written += WriteRegister (reg_ctx, "fioff", "ip", 4,
273 // data); // uint32_t ip; // "fioff"
274 // bytes_written += WriteRegister (reg_ctx, "fiseg", NULL, 2,
275 // data); // uint16_t cs; // "fiseg"
276 // bytes_written += data.PutHex16 (0); // uint16_t pad2;
277 // bytes_written += WriteRegister (reg_ctx, "dp", "fooff" , 4,
278 // data); // uint32_t dp; // "fooff"
279 // bytes_written += WriteRegister (reg_ctx, "foseg", NULL, 2,
280 // data); // uint16_t ds; // "foseg"
281 // bytes_written += data.PutHex16 (0); // uint16_t pad3;
282 // bytes_written += WriteRegister (reg_ctx, "mxcsr", NULL, 4,
283 // data); // uint32_t mxcsr;
284 // bytes_written += WriteRegister (reg_ctx, "mxcsrmask", NULL,
285 // 4, data);// uint32_t mxcsrmask;
286 // bytes_written += WriteRegister (reg_ctx, "stmm0", NULL,
287 // sizeof(MMSReg), data);
288 // bytes_written += WriteRegister (reg_ctx, "stmm1", NULL,
289 // sizeof(MMSReg), data);
290 // bytes_written += WriteRegister (reg_ctx, "stmm2", NULL,
291 // sizeof(MMSReg), data);
292 // bytes_written += WriteRegister (reg_ctx, "stmm3", NULL,
293 // sizeof(MMSReg), data);
294 // bytes_written += WriteRegister (reg_ctx, "stmm4", NULL,
295 // sizeof(MMSReg), data);
296 // bytes_written += WriteRegister (reg_ctx, "stmm5", NULL,
297 // sizeof(MMSReg), data);
298 // bytes_written += WriteRegister (reg_ctx, "stmm6", NULL,
299 // sizeof(MMSReg), data);
300 // bytes_written += WriteRegister (reg_ctx, "stmm7", NULL,
301 // sizeof(MMSReg), data);
302 // bytes_written += WriteRegister (reg_ctx, "xmm0" , NULL,
303 // sizeof(XMMReg), data);
304 // bytes_written += WriteRegister (reg_ctx, "xmm1" , NULL,
305 // sizeof(XMMReg), data);
306 // bytes_written += WriteRegister (reg_ctx, "xmm2" , NULL,
307 // sizeof(XMMReg), data);
308 // bytes_written += WriteRegister (reg_ctx, "xmm3" , NULL,
309 // sizeof(XMMReg), data);
310 // bytes_written += WriteRegister (reg_ctx, "xmm4" , NULL,
311 // sizeof(XMMReg), data);
312 // bytes_written += WriteRegister (reg_ctx, "xmm5" , NULL,
313 // sizeof(XMMReg), data);
314 // bytes_written += WriteRegister (reg_ctx, "xmm6" , NULL,
315 // sizeof(XMMReg), data);
316 // bytes_written += WriteRegister (reg_ctx, "xmm7" , NULL,
317 // sizeof(XMMReg), data);
318 // bytes_written += WriteRegister (reg_ctx, "xmm8" , NULL,
319 // sizeof(XMMReg), data);
320 // bytes_written += WriteRegister (reg_ctx, "xmm9" , NULL,
321 // sizeof(XMMReg), data);
322 // bytes_written += WriteRegister (reg_ctx, "xmm10", NULL,
323 // sizeof(XMMReg), data);
324 // bytes_written += WriteRegister (reg_ctx, "xmm11", NULL,
325 // sizeof(XMMReg), data);
326 // bytes_written += WriteRegister (reg_ctx, "xmm12", NULL,
327 // sizeof(XMMReg), data);
328 // bytes_written += WriteRegister (reg_ctx, "xmm13", NULL,
329 // sizeof(XMMReg), data);
330 // bytes_written += WriteRegister (reg_ctx, "xmm14", NULL,
331 // sizeof(XMMReg), data);
332 // bytes_written += WriteRegister (reg_ctx, "xmm15", NULL,
333 // sizeof(XMMReg), data);
334 //
335 // // Fill rest with zeros
336 // for (size_t i=0, n = fpu_byte_size - bytes_written; i<n; ++
337 // i)
338 // data.PutChar(0);
339
340 // Write out the EXC registers
341 data.PutHex32(uvalue: EXCRegSet);
342 data.PutHex32(uvalue: EXCWordCount);
343 PrintRegisterValue(reg_ctx, name: "trapno", alt_name: nullptr, reg_byte_size: 4, data);
344 PrintRegisterValue(reg_ctx, name: "err", alt_name: nullptr, reg_byte_size: 4, data);
345 PrintRegisterValue(reg_ctx, name: "faultvaddr", alt_name: nullptr, reg_byte_size: 8, data);
346 return true;
347 }
348 return false;
349 }
350
351protected:
352 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
353
354 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
355
356 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
357
358 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
359 return 0;
360 }
361
362 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
363 return 0;
364 }
365
366 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
367 return 0;
368 }
369};
370
371class RegisterContextDarwin_i386_Mach : public RegisterContextDarwin_i386 {
372public:
373 RegisterContextDarwin_i386_Mach(lldb_private::Thread &thread,
374 const DataExtractor &data)
375 : RegisterContextDarwin_i386(thread, 0) {
376 SetRegisterDataFrom_LC_THREAD(data);
377 }
378
379 void InvalidateAllRegisters() override {
380 // Do nothing... registers are always valid...
381 }
382
383 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
384 lldb::offset_t offset = 0;
385 SetError(flavor: GPRRegSet, err_idx: Read, err: -1);
386 SetError(flavor: FPURegSet, err_idx: Read, err: -1);
387 SetError(flavor: EXCRegSet, err_idx: Read, err: -1);
388 bool done = false;
389
390 while (!done) {
391 int flavor = data.GetU32(offset_ptr: &offset);
392 if (flavor == 0)
393 done = true;
394 else {
395 uint32_t i;
396 uint32_t count = data.GetU32(offset_ptr: &offset);
397 switch (flavor) {
398 case GPRRegSet:
399 for (i = 0; i < count; ++i)
400 (&gpr.eax)[i] = data.GetU32(offset_ptr: &offset);
401 SetError(flavor: GPRRegSet, err_idx: Read, err: 0);
402 done = true;
403
404 break;
405 case FPURegSet:
406 // TODO: fill in FPU regs....
407 // SetError (FPURegSet, Read, -1);
408 done = true;
409
410 break;
411 case EXCRegSet:
412 exc.trapno = data.GetU32(offset_ptr: &offset);
413 exc.err = data.GetU32(offset_ptr: &offset);
414 exc.faultvaddr = data.GetU32(offset_ptr: &offset);
415 SetError(flavor: EXCRegSet, err_idx: Read, err: 0);
416 done = true;
417 break;
418 case 7:
419 case 8:
420 case 9:
421 // fancy flavors that encapsulate of the above flavors...
422 break;
423
424 default:
425 done = true;
426 break;
427 }
428 }
429 }
430 }
431
432 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
433 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
434 if (reg_ctx_sp) {
435 RegisterContext *reg_ctx = reg_ctx_sp.get();
436
437 data.PutHex32(uvalue: GPRRegSet); // Flavor
438 data.PutHex32(uvalue: GPRWordCount);
439 PrintRegisterValue(reg_ctx, name: "eax", alt_name: nullptr, reg_byte_size: 4, data);
440 PrintRegisterValue(reg_ctx, name: "ebx", alt_name: nullptr, reg_byte_size: 4, data);
441 PrintRegisterValue(reg_ctx, name: "ecx", alt_name: nullptr, reg_byte_size: 4, data);
442 PrintRegisterValue(reg_ctx, name: "edx", alt_name: nullptr, reg_byte_size: 4, data);
443 PrintRegisterValue(reg_ctx, name: "edi", alt_name: nullptr, reg_byte_size: 4, data);
444 PrintRegisterValue(reg_ctx, name: "esi", alt_name: nullptr, reg_byte_size: 4, data);
445 PrintRegisterValue(reg_ctx, name: "ebp", alt_name: nullptr, reg_byte_size: 4, data);
446 PrintRegisterValue(reg_ctx, name: "esp", alt_name: nullptr, reg_byte_size: 4, data);
447 PrintRegisterValue(reg_ctx, name: "ss", alt_name: nullptr, reg_byte_size: 4, data);
448 PrintRegisterValue(reg_ctx, name: "eflags", alt_name: nullptr, reg_byte_size: 4, data);
449 PrintRegisterValue(reg_ctx, name: "eip", alt_name: nullptr, reg_byte_size: 4, data);
450 PrintRegisterValue(reg_ctx, name: "cs", alt_name: nullptr, reg_byte_size: 4, data);
451 PrintRegisterValue(reg_ctx, name: "ds", alt_name: nullptr, reg_byte_size: 4, data);
452 PrintRegisterValue(reg_ctx, name: "es", alt_name: nullptr, reg_byte_size: 4, data);
453 PrintRegisterValue(reg_ctx, name: "fs", alt_name: nullptr, reg_byte_size: 4, data);
454 PrintRegisterValue(reg_ctx, name: "gs", alt_name: nullptr, reg_byte_size: 4, data);
455
456 // Write out the EXC registers
457 data.PutHex32(uvalue: EXCRegSet);
458 data.PutHex32(uvalue: EXCWordCount);
459 PrintRegisterValue(reg_ctx, name: "trapno", alt_name: nullptr, reg_byte_size: 4, data);
460 PrintRegisterValue(reg_ctx, name: "err", alt_name: nullptr, reg_byte_size: 4, data);
461 PrintRegisterValue(reg_ctx, name: "faultvaddr", alt_name: nullptr, reg_byte_size: 4, data);
462 return true;
463 }
464 return false;
465 }
466
467protected:
468 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
469
470 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
471
472 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
473
474 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
475 return 0;
476 }
477
478 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
479 return 0;
480 }
481
482 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
483 return 0;
484 }
485};
486
487class RegisterContextDarwin_arm_Mach : public RegisterContextDarwin_arm {
488public:
489 RegisterContextDarwin_arm_Mach(lldb_private::Thread &thread,
490 const DataExtractor &data)
491 : RegisterContextDarwin_arm(thread, 0) {
492 SetRegisterDataFrom_LC_THREAD(data);
493 }
494
495 void InvalidateAllRegisters() override {
496 // Do nothing... registers are always valid...
497 }
498
499 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
500 lldb::offset_t offset = 0;
501 SetError(flavor: GPRRegSet, err_idx: Read, err: -1);
502 SetError(flavor: FPURegSet, err_idx: Read, err: -1);
503 SetError(flavor: EXCRegSet, err_idx: Read, err: -1);
504 bool done = false;
505
506 while (!done) {
507 int flavor = data.GetU32(offset_ptr: &offset);
508 uint32_t count = data.GetU32(offset_ptr: &offset);
509 lldb::offset_t next_thread_state = offset + (count * 4);
510 switch (flavor) {
511 case GPRAltRegSet:
512 case GPRRegSet: {
513 // r0-r15, plus CPSR
514 uint32_t gpr_buf_count = (sizeof(gpr.r) / sizeof(gpr.r[0])) + 1;
515 if (count == gpr_buf_count) {
516 for (uint32_t i = 0; i < (count - 1); ++i) {
517 gpr.r[i] = data.GetU32(offset_ptr: &offset);
518 }
519 gpr.cpsr = data.GetU32(offset_ptr: &offset);
520
521 SetError(flavor: GPRRegSet, err_idx: Read, err: 0);
522 }
523 }
524 offset = next_thread_state;
525 break;
526
527 case FPURegSet: {
528 uint8_t *fpu_reg_buf = (uint8_t *)&fpu.floats;
529 const int fpu_reg_buf_size = sizeof(fpu.floats);
530 if (data.ExtractBytes(offset, length: fpu_reg_buf_size, dst_byte_order: eByteOrderLittle,
531 dst: fpu_reg_buf) == fpu_reg_buf_size) {
532 offset += fpu_reg_buf_size;
533 fpu.fpscr = data.GetU32(offset_ptr: &offset);
534 SetError(flavor: FPURegSet, err_idx: Read, err: 0);
535 } else {
536 done = true;
537 }
538 }
539 offset = next_thread_state;
540 break;
541
542 case EXCRegSet:
543 if (count == 3) {
544 exc.exception = data.GetU32(offset_ptr: &offset);
545 exc.fsr = data.GetU32(offset_ptr: &offset);
546 exc.far = data.GetU32(offset_ptr: &offset);
547 SetError(flavor: EXCRegSet, err_idx: Read, err: 0);
548 }
549 done = true;
550 offset = next_thread_state;
551 break;
552
553 // Unknown register set flavor, stop trying to parse.
554 default:
555 done = true;
556 }
557 }
558 }
559
560 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
561 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
562 if (reg_ctx_sp) {
563 RegisterContext *reg_ctx = reg_ctx_sp.get();
564
565 data.PutHex32(uvalue: GPRRegSet); // Flavor
566 data.PutHex32(uvalue: GPRWordCount);
567 PrintRegisterValue(reg_ctx, name: "r0", alt_name: nullptr, reg_byte_size: 4, data);
568 PrintRegisterValue(reg_ctx, name: "r1", alt_name: nullptr, reg_byte_size: 4, data);
569 PrintRegisterValue(reg_ctx, name: "r2", alt_name: nullptr, reg_byte_size: 4, data);
570 PrintRegisterValue(reg_ctx, name: "r3", alt_name: nullptr, reg_byte_size: 4, data);
571 PrintRegisterValue(reg_ctx, name: "r4", alt_name: nullptr, reg_byte_size: 4, data);
572 PrintRegisterValue(reg_ctx, name: "r5", alt_name: nullptr, reg_byte_size: 4, data);
573 PrintRegisterValue(reg_ctx, name: "r6", alt_name: nullptr, reg_byte_size: 4, data);
574 PrintRegisterValue(reg_ctx, name: "r7", alt_name: nullptr, reg_byte_size: 4, data);
575 PrintRegisterValue(reg_ctx, name: "r8", alt_name: nullptr, reg_byte_size: 4, data);
576 PrintRegisterValue(reg_ctx, name: "r9", alt_name: nullptr, reg_byte_size: 4, data);
577 PrintRegisterValue(reg_ctx, name: "r10", alt_name: nullptr, reg_byte_size: 4, data);
578 PrintRegisterValue(reg_ctx, name: "r11", alt_name: nullptr, reg_byte_size: 4, data);
579 PrintRegisterValue(reg_ctx, name: "r12", alt_name: nullptr, reg_byte_size: 4, data);
580 PrintRegisterValue(reg_ctx, name: "sp", alt_name: nullptr, reg_byte_size: 4, data);
581 PrintRegisterValue(reg_ctx, name: "lr", alt_name: nullptr, reg_byte_size: 4, data);
582 PrintRegisterValue(reg_ctx, name: "pc", alt_name: nullptr, reg_byte_size: 4, data);
583 PrintRegisterValue(reg_ctx, name: "cpsr", alt_name: nullptr, reg_byte_size: 4, data);
584
585 // Write out the EXC registers
586 // data.PutHex32 (EXCRegSet);
587 // data.PutHex32 (EXCWordCount);
588 // WriteRegister (reg_ctx, "exception", NULL, 4, data);
589 // WriteRegister (reg_ctx, "fsr", NULL, 4, data);
590 // WriteRegister (reg_ctx, "far", NULL, 4, data);
591 return true;
592 }
593 return false;
594 }
595
596protected:
597 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
598
599 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
600
601 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
602
603 int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
604
605 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
606 return 0;
607 }
608
609 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
610 return 0;
611 }
612
613 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
614 return 0;
615 }
616
617 int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
618 return -1;
619 }
620};
621
622class RegisterContextDarwin_arm64_Mach : public RegisterContextDarwin_arm64 {
623public:
624 RegisterContextDarwin_arm64_Mach(lldb_private::Thread &thread,
625 const DataExtractor &data)
626 : RegisterContextDarwin_arm64(thread, 0) {
627 SetRegisterDataFrom_LC_THREAD(data);
628 }
629
630 void InvalidateAllRegisters() override {
631 // Do nothing... registers are always valid...
632 }
633
634 void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
635 lldb::offset_t offset = 0;
636 SetError(flavor: GPRRegSet, err_idx: Read, err: -1);
637 SetError(flavor: FPURegSet, err_idx: Read, err: -1);
638 SetError(flavor: EXCRegSet, err_idx: Read, err: -1);
639 bool done = false;
640 while (!done) {
641 int flavor = data.GetU32(offset_ptr: &offset);
642 uint32_t count = data.GetU32(offset_ptr: &offset);
643 lldb::offset_t next_thread_state = offset + (count * 4);
644 switch (flavor) {
645 case GPRRegSet:
646 // x0-x29 + fp + lr + sp + pc (== 33 64-bit registers) plus cpsr (1
647 // 32-bit register)
648 if (count >= (33 * 2) + 1) {
649 for (uint32_t i = 0; i < 29; ++i)
650 gpr.x[i] = data.GetU64(offset_ptr: &offset);
651 gpr.fp = data.GetU64(offset_ptr: &offset);
652 gpr.lr = data.GetU64(offset_ptr: &offset);
653 gpr.sp = data.GetU64(offset_ptr: &offset);
654 gpr.pc = data.GetU64(offset_ptr: &offset);
655 gpr.cpsr = data.GetU32(offset_ptr: &offset);
656 SetError(flavor: GPRRegSet, err_idx: Read, err: 0);
657 }
658 offset = next_thread_state;
659 break;
660 case FPURegSet: {
661 uint8_t *fpu_reg_buf = (uint8_t *)&fpu.v[0];
662 const int fpu_reg_buf_size = sizeof(fpu);
663 if (fpu_reg_buf_size == count * sizeof(uint32_t) &&
664 data.ExtractBytes(offset, length: fpu_reg_buf_size, dst_byte_order: eByteOrderLittle,
665 dst: fpu_reg_buf) == fpu_reg_buf_size) {
666 SetError(flavor: FPURegSet, err_idx: Read, err: 0);
667 } else {
668 done = true;
669 }
670 }
671 offset = next_thread_state;
672 break;
673 case EXCRegSet:
674 if (count == 4) {
675 exc.far = data.GetU64(offset_ptr: &offset);
676 exc.esr = data.GetU32(offset_ptr: &offset);
677 exc.exception = data.GetU32(offset_ptr: &offset);
678 SetError(flavor: EXCRegSet, err_idx: Read, err: 0);
679 }
680 offset = next_thread_state;
681 break;
682 default:
683 done = true;
684 break;
685 }
686 }
687 }
688
689 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
690 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
691 if (reg_ctx_sp) {
692 RegisterContext *reg_ctx = reg_ctx_sp.get();
693
694 data.PutHex32(uvalue: GPRRegSet); // Flavor
695 data.PutHex32(uvalue: GPRWordCount);
696 PrintRegisterValue(reg_ctx, name: "x0", alt_name: nullptr, reg_byte_size: 8, data);
697 PrintRegisterValue(reg_ctx, name: "x1", alt_name: nullptr, reg_byte_size: 8, data);
698 PrintRegisterValue(reg_ctx, name: "x2", alt_name: nullptr, reg_byte_size: 8, data);
699 PrintRegisterValue(reg_ctx, name: "x3", alt_name: nullptr, reg_byte_size: 8, data);
700 PrintRegisterValue(reg_ctx, name: "x4", alt_name: nullptr, reg_byte_size: 8, data);
701 PrintRegisterValue(reg_ctx, name: "x5", alt_name: nullptr, reg_byte_size: 8, data);
702 PrintRegisterValue(reg_ctx, name: "x6", alt_name: nullptr, reg_byte_size: 8, data);
703 PrintRegisterValue(reg_ctx, name: "x7", alt_name: nullptr, reg_byte_size: 8, data);
704 PrintRegisterValue(reg_ctx, name: "x8", alt_name: nullptr, reg_byte_size: 8, data);
705 PrintRegisterValue(reg_ctx, name: "x9", alt_name: nullptr, reg_byte_size: 8, data);
706 PrintRegisterValue(reg_ctx, name: "x10", alt_name: nullptr, reg_byte_size: 8, data);
707 PrintRegisterValue(reg_ctx, name: "x11", alt_name: nullptr, reg_byte_size: 8, data);
708 PrintRegisterValue(reg_ctx, name: "x12", alt_name: nullptr, reg_byte_size: 8, data);
709 PrintRegisterValue(reg_ctx, name: "x13", alt_name: nullptr, reg_byte_size: 8, data);
710 PrintRegisterValue(reg_ctx, name: "x14", alt_name: nullptr, reg_byte_size: 8, data);
711 PrintRegisterValue(reg_ctx, name: "x15", alt_name: nullptr, reg_byte_size: 8, data);
712 PrintRegisterValue(reg_ctx, name: "x16", alt_name: nullptr, reg_byte_size: 8, data);
713 PrintRegisterValue(reg_ctx, name: "x17", alt_name: nullptr, reg_byte_size: 8, data);
714 PrintRegisterValue(reg_ctx, name: "x18", alt_name: nullptr, reg_byte_size: 8, data);
715 PrintRegisterValue(reg_ctx, name: "x19", alt_name: nullptr, reg_byte_size: 8, data);
716 PrintRegisterValue(reg_ctx, name: "x20", alt_name: nullptr, reg_byte_size: 8, data);
717 PrintRegisterValue(reg_ctx, name: "x21", alt_name: nullptr, reg_byte_size: 8, data);
718 PrintRegisterValue(reg_ctx, name: "x22", alt_name: nullptr, reg_byte_size: 8, data);
719 PrintRegisterValue(reg_ctx, name: "x23", alt_name: nullptr, reg_byte_size: 8, data);
720 PrintRegisterValue(reg_ctx, name: "x24", alt_name: nullptr, reg_byte_size: 8, data);
721 PrintRegisterValue(reg_ctx, name: "x25", alt_name: nullptr, reg_byte_size: 8, data);
722 PrintRegisterValue(reg_ctx, name: "x26", alt_name: nullptr, reg_byte_size: 8, data);
723 PrintRegisterValue(reg_ctx, name: "x27", alt_name: nullptr, reg_byte_size: 8, data);
724 PrintRegisterValue(reg_ctx, name: "x28", alt_name: nullptr, reg_byte_size: 8, data);
725 PrintRegisterValue(reg_ctx, name: "fp", alt_name: nullptr, reg_byte_size: 8, data);
726 PrintRegisterValue(reg_ctx, name: "lr", alt_name: nullptr, reg_byte_size: 8, data);
727 PrintRegisterValue(reg_ctx, name: "sp", alt_name: nullptr, reg_byte_size: 8, data);
728 PrintRegisterValue(reg_ctx, name: "pc", alt_name: nullptr, reg_byte_size: 8, data);
729 PrintRegisterValue(reg_ctx, name: "cpsr", alt_name: nullptr, reg_byte_size: 4, data);
730 data.PutHex32(uvalue: 0); // uint32_t pad at the end
731
732 // Write out the EXC registers
733 data.PutHex32(uvalue: EXCRegSet);
734 data.PutHex32(uvalue: EXCWordCount);
735 PrintRegisterValue(reg_ctx, name: "far", alt_name: nullptr, reg_byte_size: 8, data);
736 PrintRegisterValue(reg_ctx, name: "esr", alt_name: nullptr, reg_byte_size: 4, data);
737 PrintRegisterValue(reg_ctx, name: "exception", alt_name: nullptr, reg_byte_size: 4, data);
738 return true;
739 }
740 return false;
741 }
742
743protected:
744 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
745
746 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
747
748 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
749
750 int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
751
752 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
753 return 0;
754 }
755
756 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
757 return 0;
758 }
759
760 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
761 return 0;
762 }
763
764 int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
765 return -1;
766 }
767};
768
769static uint32_t MachHeaderSizeFromMagic(uint32_t magic) {
770 switch (magic) {
771 case MH_MAGIC:
772 case MH_CIGAM:
773 return sizeof(struct llvm::MachO::mach_header);
774
775 case MH_MAGIC_64:
776 case MH_CIGAM_64:
777 return sizeof(struct llvm::MachO::mach_header_64);
778 break;
779
780 default:
781 break;
782 }
783 return 0;
784}
785
786#define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008
787
788char ObjectFileMachO::ID;
789
790void ObjectFileMachO::Initialize() {
791 PluginManager::RegisterPlugin(
792 name: GetPluginNameStatic(), description: GetPluginDescriptionStatic(), create_callback: CreateInstance,
793 create_memory_callback: CreateMemoryInstance, get_module_specifications: GetModuleSpecifications, save_core: SaveCore);
794}
795
796void ObjectFileMachO::Terminate() {
797 PluginManager::UnregisterPlugin(create_callback: CreateInstance);
798}
799
800ObjectFile *ObjectFileMachO::CreateInstance(const lldb::ModuleSP &module_sp,
801 DataBufferSP data_sp,
802 lldb::offset_t data_offset,
803 const FileSpec *file,
804 lldb::offset_t file_offset,
805 lldb::offset_t length) {
806 if (!data_sp) {
807 data_sp = MapFileData(file: *file, Size: length, Offset: file_offset);
808 if (!data_sp)
809 return nullptr;
810 data_offset = 0;
811 }
812
813 if (!ObjectFileMachO::MagicBytesMatch(data_sp, offset: data_offset, length))
814 return nullptr;
815
816 // Update the data to contain the entire file if it doesn't already
817 if (data_sp->GetByteSize() < length) {
818 data_sp = MapFileData(file: *file, Size: length, Offset: file_offset);
819 if (!data_sp)
820 return nullptr;
821 data_offset = 0;
822 }
823 auto objfile_up = std::make_unique<ObjectFileMachO>(
824 args: module_sp, args&: data_sp, args&: data_offset, args&: file, args&: file_offset, args&: length);
825 if (!objfile_up || !objfile_up->ParseHeader())
826 return nullptr;
827
828 return objfile_up.release();
829}
830
831ObjectFile *ObjectFileMachO::CreateMemoryInstance(
832 const lldb::ModuleSP &module_sp, WritableDataBufferSP data_sp,
833 const ProcessSP &process_sp, lldb::addr_t header_addr) {
834 if (ObjectFileMachO::MagicBytesMatch(data_sp, offset: 0, length: data_sp->GetByteSize())) {
835 std::unique_ptr<ObjectFile> objfile_up(
836 new ObjectFileMachO(module_sp, data_sp, process_sp, header_addr));
837 if (objfile_up.get() && objfile_up->ParseHeader())
838 return objfile_up.release();
839 }
840 return nullptr;
841}
842
843size_t ObjectFileMachO::GetModuleSpecifications(
844 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
845 lldb::offset_t data_offset, lldb::offset_t file_offset,
846 lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
847 const size_t initial_count = specs.GetSize();
848
849 if (ObjectFileMachO::MagicBytesMatch(data_sp, offset: 0, length: data_sp->GetByteSize())) {
850 DataExtractor data;
851 data.SetData(data_sp);
852 llvm::MachO::mach_header header;
853 if (ParseHeader(data, data_offset_ptr: &data_offset, header)) {
854 size_t header_and_load_cmds =
855 header.sizeofcmds + MachHeaderSizeFromMagic(magic: header.magic);
856 if (header_and_load_cmds >= data_sp->GetByteSize()) {
857 data_sp = MapFileData(file, Size: header_and_load_cmds, Offset: file_offset);
858 data.SetData(data_sp);
859 data_offset = MachHeaderSizeFromMagic(magic: header.magic);
860 }
861 if (data_sp) {
862 ModuleSpec base_spec;
863 base_spec.GetFileSpec() = file;
864 base_spec.SetObjectOffset(file_offset);
865 base_spec.SetObjectSize(length);
866 GetAllArchSpecs(header, data, lc_offset: data_offset, base_spec, all_specs&: specs);
867 }
868 }
869 }
870 return specs.GetSize() - initial_count;
871}
872
873ConstString ObjectFileMachO::GetSegmentNameTEXT() {
874 static ConstString g_segment_name_TEXT("__TEXT");
875 return g_segment_name_TEXT;
876}
877
878ConstString ObjectFileMachO::GetSegmentNameDATA() {
879 static ConstString g_segment_name_DATA("__DATA");
880 return g_segment_name_DATA;
881}
882
883ConstString ObjectFileMachO::GetSegmentNameDATA_DIRTY() {
884 static ConstString g_segment_name("__DATA_DIRTY");
885 return g_segment_name;
886}
887
888ConstString ObjectFileMachO::GetSegmentNameDATA_CONST() {
889 static ConstString g_segment_name("__DATA_CONST");
890 return g_segment_name;
891}
892
893ConstString ObjectFileMachO::GetSegmentNameOBJC() {
894 static ConstString g_segment_name_OBJC("__OBJC");
895 return g_segment_name_OBJC;
896}
897
898ConstString ObjectFileMachO::GetSegmentNameLINKEDIT() {
899 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
900 return g_section_name_LINKEDIT;
901}
902
903ConstString ObjectFileMachO::GetSegmentNameDWARF() {
904 static ConstString g_section_name("__DWARF");
905 return g_section_name;
906}
907
908ConstString ObjectFileMachO::GetSegmentNameLLVM_COV() {
909 static ConstString g_section_name("__LLVM_COV");
910 return g_section_name;
911}
912
913ConstString ObjectFileMachO::GetSectionNameEHFrame() {
914 static ConstString g_section_name_eh_frame("__eh_frame");
915 return g_section_name_eh_frame;
916}
917
918bool ObjectFileMachO::MagicBytesMatch(DataBufferSP data_sp,
919 lldb::addr_t data_offset,
920 lldb::addr_t data_length) {
921 DataExtractor data;
922 data.SetData(data_sp, offset: data_offset, length: data_length);
923 lldb::offset_t offset = 0;
924 uint32_t magic = data.GetU32(offset_ptr: &offset);
925
926 offset += 4; // cputype
927 offset += 4; // cpusubtype
928 uint32_t filetype = data.GetU32(offset_ptr: &offset);
929
930 // A fileset has a Mach-O header but is not an
931 // individual file and must be handled via an
932 // ObjectContainer plugin.
933 if (filetype == llvm::MachO::MH_FILESET)
934 return false;
935
936 return MachHeaderSizeFromMagic(magic) != 0;
937}
938
939ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
940 DataBufferSP data_sp,
941 lldb::offset_t data_offset,
942 const FileSpec *file,
943 lldb::offset_t file_offset,
944 lldb::offset_t length)
945 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
946 m_mach_sections(), m_entry_point_address(), m_thread_context_offsets(),
947 m_thread_context_offsets_valid(false), m_reexported_dylibs(),
948 m_allow_assembly_emulation_unwind_plans(true) {
949 ::memset(s: &m_header, c: 0, n: sizeof(m_header));
950 ::memset(s: &m_dysymtab, c: 0, n: sizeof(m_dysymtab));
951}
952
953ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
954 lldb::WritableDataBufferSP header_data_sp,
955 const lldb::ProcessSP &process_sp,
956 lldb::addr_t header_addr)
957 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
958 m_mach_sections(), m_entry_point_address(), m_thread_context_offsets(),
959 m_thread_context_offsets_valid(false), m_reexported_dylibs(),
960 m_allow_assembly_emulation_unwind_plans(true) {
961 ::memset(s: &m_header, c: 0, n: sizeof(m_header));
962 ::memset(s: &m_dysymtab, c: 0, n: sizeof(m_dysymtab));
963}
964
965bool ObjectFileMachO::ParseHeader(DataExtractor &data,
966 lldb::offset_t *data_offset_ptr,
967 llvm::MachO::mach_header &header) {
968 data.SetByteOrder(endian::InlHostByteOrder());
969 // Leave magic in the original byte order
970 header.magic = data.GetU32(offset_ptr: data_offset_ptr);
971 bool can_parse = false;
972 bool is_64_bit = false;
973 switch (header.magic) {
974 case MH_MAGIC:
975 data.SetByteOrder(endian::InlHostByteOrder());
976 data.SetAddressByteSize(4);
977 can_parse = true;
978 break;
979
980 case MH_MAGIC_64:
981 data.SetByteOrder(endian::InlHostByteOrder());
982 data.SetAddressByteSize(8);
983 can_parse = true;
984 is_64_bit = true;
985 break;
986
987 case MH_CIGAM:
988 data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
989 ? eByteOrderLittle
990 : eByteOrderBig);
991 data.SetAddressByteSize(4);
992 can_parse = true;
993 break;
994
995 case MH_CIGAM_64:
996 data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
997 ? eByteOrderLittle
998 : eByteOrderBig);
999 data.SetAddressByteSize(8);
1000 is_64_bit = true;
1001 can_parse = true;
1002 break;
1003
1004 default:
1005 break;
1006 }
1007
1008 if (can_parse) {
1009 data.GetU32(offset_ptr: data_offset_ptr, dst: &header.cputype, count: 6);
1010 if (is_64_bit)
1011 *data_offset_ptr += 4;
1012 return true;
1013 } else {
1014 memset(s: &header, c: 0, n: sizeof(header));
1015 }
1016 return false;
1017}
1018
1019bool ObjectFileMachO::ParseHeader() {
1020 ModuleSP module_sp(GetModule());
1021 if (!module_sp)
1022 return false;
1023
1024 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1025 bool can_parse = false;
1026 lldb::offset_t offset = 0;
1027 m_data.SetByteOrder(endian::InlHostByteOrder());
1028 // Leave magic in the original byte order
1029 m_header.magic = m_data.GetU32(offset_ptr: &offset);
1030 switch (m_header.magic) {
1031 case MH_MAGIC:
1032 m_data.SetByteOrder(endian::InlHostByteOrder());
1033 m_data.SetAddressByteSize(4);
1034 can_parse = true;
1035 break;
1036
1037 case MH_MAGIC_64:
1038 m_data.SetByteOrder(endian::InlHostByteOrder());
1039 m_data.SetAddressByteSize(8);
1040 can_parse = true;
1041 break;
1042
1043 case MH_CIGAM:
1044 m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1045 ? eByteOrderLittle
1046 : eByteOrderBig);
1047 m_data.SetAddressByteSize(4);
1048 can_parse = true;
1049 break;
1050
1051 case MH_CIGAM_64:
1052 m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1053 ? eByteOrderLittle
1054 : eByteOrderBig);
1055 m_data.SetAddressByteSize(8);
1056 can_parse = true;
1057 break;
1058
1059 default:
1060 break;
1061 }
1062
1063 if (can_parse) {
1064 m_data.GetU32(offset_ptr: &offset, dst: &m_header.cputype, count: 6);
1065
1066 ModuleSpecList all_specs;
1067 ModuleSpec base_spec;
1068 GetAllArchSpecs(header: m_header, data: m_data, lc_offset: MachHeaderSizeFromMagic(magic: m_header.magic),
1069 base_spec, all_specs);
1070
1071 for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
1072 ArchSpec mach_arch =
1073 all_specs.GetModuleSpecRefAtIndex(i).GetArchitecture();
1074
1075 // Check if the module has a required architecture
1076 const ArchSpec &module_arch = module_sp->GetArchitecture();
1077 if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(rhs: mach_arch))
1078 continue;
1079
1080 if (SetModulesArchitecture(mach_arch)) {
1081 const size_t header_and_lc_size =
1082 m_header.sizeofcmds + MachHeaderSizeFromMagic(magic: m_header.magic);
1083 if (m_data.GetByteSize() < header_and_lc_size) {
1084 DataBufferSP data_sp;
1085 ProcessSP process_sp(m_process_wp.lock());
1086 if (process_sp) {
1087 data_sp = ReadMemory(process_sp, addr: m_memory_addr, byte_size: header_and_lc_size);
1088 } else {
1089 // Read in all only the load command data from the file on disk
1090 data_sp = MapFileData(file: m_file, Size: header_and_lc_size, Offset: m_file_offset);
1091 if (data_sp->GetByteSize() != header_and_lc_size)
1092 continue;
1093 }
1094 if (data_sp)
1095 m_data.SetData(data_sp);
1096 }
1097 }
1098 return true;
1099 }
1100 // None found.
1101 return false;
1102 } else {
1103 memset(s: &m_header, c: 0, n: sizeof(struct llvm::MachO::mach_header));
1104 }
1105 return false;
1106}
1107
1108ByteOrder ObjectFileMachO::GetByteOrder() const {
1109 return m_data.GetByteOrder();
1110}
1111
1112bool ObjectFileMachO::IsExecutable() const {
1113 return m_header.filetype == MH_EXECUTE;
1114}
1115
1116bool ObjectFileMachO::IsDynamicLoader() const {
1117 return m_header.filetype == MH_DYLINKER;
1118}
1119
1120bool ObjectFileMachO::IsSharedCacheBinary() const {
1121 return m_header.flags & MH_DYLIB_IN_CACHE;
1122}
1123
1124bool ObjectFileMachO::IsKext() const {
1125 return m_header.filetype == MH_KEXT_BUNDLE;
1126}
1127
1128uint32_t ObjectFileMachO::GetAddressByteSize() const {
1129 return m_data.GetAddressByteSize();
1130}
1131
1132AddressClass ObjectFileMachO::GetAddressClass(lldb::addr_t file_addr) {
1133 Symtab *symtab = GetSymtab();
1134 if (!symtab)
1135 return AddressClass::eUnknown;
1136
1137 Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
1138 if (symbol) {
1139 if (symbol->ValueIsAddress()) {
1140 SectionSP section_sp(symbol->GetAddressRef().GetSection());
1141 if (section_sp) {
1142 const lldb::SectionType section_type = section_sp->GetType();
1143 switch (section_type) {
1144 case eSectionTypeInvalid:
1145 return AddressClass::eUnknown;
1146
1147 case eSectionTypeCode:
1148 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
1149 // For ARM we have a bit in the n_desc field of the symbol that
1150 // tells us ARM/Thumb which is bit 0x0008.
1151 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
1152 return AddressClass::eCodeAlternateISA;
1153 }
1154 return AddressClass::eCode;
1155
1156 case eSectionTypeContainer:
1157 return AddressClass::eUnknown;
1158
1159 case eSectionTypeData:
1160 case eSectionTypeDataCString:
1161 case eSectionTypeDataCStringPointers:
1162 case eSectionTypeDataSymbolAddress:
1163 case eSectionTypeData4:
1164 case eSectionTypeData8:
1165 case eSectionTypeData16:
1166 case eSectionTypeDataPointers:
1167 case eSectionTypeZeroFill:
1168 case eSectionTypeDataObjCMessageRefs:
1169 case eSectionTypeDataObjCCFStrings:
1170 case eSectionTypeGoSymtab:
1171 return AddressClass::eData;
1172
1173 case eSectionTypeDebug:
1174 case eSectionTypeDWARFDebugAbbrev:
1175 case eSectionTypeDWARFDebugAbbrevDwo:
1176 case eSectionTypeDWARFDebugAddr:
1177 case eSectionTypeDWARFDebugAranges:
1178 case eSectionTypeDWARFDebugCuIndex:
1179 case eSectionTypeDWARFDebugFrame:
1180 case eSectionTypeDWARFDebugInfo:
1181 case eSectionTypeDWARFDebugInfoDwo:
1182 case eSectionTypeDWARFDebugLine:
1183 case eSectionTypeDWARFDebugLineStr:
1184 case eSectionTypeDWARFDebugLoc:
1185 case eSectionTypeDWARFDebugLocDwo:
1186 case eSectionTypeDWARFDebugLocLists:
1187 case eSectionTypeDWARFDebugLocListsDwo:
1188 case eSectionTypeDWARFDebugMacInfo:
1189 case eSectionTypeDWARFDebugMacro:
1190 case eSectionTypeDWARFDebugNames:
1191 case eSectionTypeDWARFDebugPubNames:
1192 case eSectionTypeDWARFDebugPubTypes:
1193 case eSectionTypeDWARFDebugRanges:
1194 case eSectionTypeDWARFDebugRngLists:
1195 case eSectionTypeDWARFDebugRngListsDwo:
1196 case eSectionTypeDWARFDebugStr:
1197 case eSectionTypeDWARFDebugStrDwo:
1198 case eSectionTypeDWARFDebugStrOffsets:
1199 case eSectionTypeDWARFDebugStrOffsetsDwo:
1200 case eSectionTypeDWARFDebugTuIndex:
1201 case eSectionTypeDWARFDebugTypes:
1202 case eSectionTypeDWARFDebugTypesDwo:
1203 case eSectionTypeDWARFAppleNames:
1204 case eSectionTypeDWARFAppleTypes:
1205 case eSectionTypeDWARFAppleNamespaces:
1206 case eSectionTypeDWARFAppleObjC:
1207 case eSectionTypeDWARFGNUDebugAltLink:
1208 case eSectionTypeCTF:
1209 case eSectionTypeSwiftModules:
1210 return AddressClass::eDebug;
1211
1212 case eSectionTypeEHFrame:
1213 case eSectionTypeARMexidx:
1214 case eSectionTypeARMextab:
1215 case eSectionTypeCompactUnwind:
1216 return AddressClass::eRuntime;
1217
1218 case eSectionTypeAbsoluteAddress:
1219 case eSectionTypeELFSymbolTable:
1220 case eSectionTypeELFDynamicSymbols:
1221 case eSectionTypeELFRelocationEntries:
1222 case eSectionTypeELFDynamicLinkInfo:
1223 case eSectionTypeOther:
1224 return AddressClass::eUnknown;
1225 }
1226 }
1227 }
1228
1229 const SymbolType symbol_type = symbol->GetType();
1230 switch (symbol_type) {
1231 case eSymbolTypeAny:
1232 return AddressClass::eUnknown;
1233 case eSymbolTypeAbsolute:
1234 return AddressClass::eUnknown;
1235
1236 case eSymbolTypeCode:
1237 case eSymbolTypeTrampoline:
1238 case eSymbolTypeResolver:
1239 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
1240 // For ARM we have a bit in the n_desc field of the symbol that tells
1241 // us ARM/Thumb which is bit 0x0008.
1242 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
1243 return AddressClass::eCodeAlternateISA;
1244 }
1245 return AddressClass::eCode;
1246
1247 case eSymbolTypeData:
1248 return AddressClass::eData;
1249 case eSymbolTypeRuntime:
1250 return AddressClass::eRuntime;
1251 case eSymbolTypeException:
1252 return AddressClass::eRuntime;
1253 case eSymbolTypeSourceFile:
1254 return AddressClass::eDebug;
1255 case eSymbolTypeHeaderFile:
1256 return AddressClass::eDebug;
1257 case eSymbolTypeObjectFile:
1258 return AddressClass::eDebug;
1259 case eSymbolTypeCommonBlock:
1260 return AddressClass::eDebug;
1261 case eSymbolTypeBlock:
1262 return AddressClass::eDebug;
1263 case eSymbolTypeLocal:
1264 return AddressClass::eData;
1265 case eSymbolTypeParam:
1266 return AddressClass::eData;
1267 case eSymbolTypeVariable:
1268 return AddressClass::eData;
1269 case eSymbolTypeVariableType:
1270 return AddressClass::eDebug;
1271 case eSymbolTypeLineEntry:
1272 return AddressClass::eDebug;
1273 case eSymbolTypeLineHeader:
1274 return AddressClass::eDebug;
1275 case eSymbolTypeScopeBegin:
1276 return AddressClass::eDebug;
1277 case eSymbolTypeScopeEnd:
1278 return AddressClass::eDebug;
1279 case eSymbolTypeAdditional:
1280 return AddressClass::eUnknown;
1281 case eSymbolTypeCompiler:
1282 return AddressClass::eDebug;
1283 case eSymbolTypeInstrumentation:
1284 return AddressClass::eDebug;
1285 case eSymbolTypeUndefined:
1286 return AddressClass::eUnknown;
1287 case eSymbolTypeObjCClass:
1288 return AddressClass::eRuntime;
1289 case eSymbolTypeObjCMetaClass:
1290 return AddressClass::eRuntime;
1291 case eSymbolTypeObjCIVar:
1292 return AddressClass::eRuntime;
1293 case eSymbolTypeReExported:
1294 return AddressClass::eRuntime;
1295 }
1296 }
1297 return AddressClass::eUnknown;
1298}
1299
1300bool ObjectFileMachO::IsStripped() {
1301 if (m_dysymtab.cmd == 0) {
1302 ModuleSP module_sp(GetModule());
1303 if (module_sp) {
1304 lldb::offset_t offset = MachHeaderSizeFromMagic(magic: m_header.magic);
1305 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1306 const lldb::offset_t load_cmd_offset = offset;
1307
1308 llvm::MachO::load_command lc = {};
1309 if (m_data.GetU32(offset_ptr: &offset, dst: &lc.cmd, count: 2) == nullptr)
1310 break;
1311 if (lc.cmd == LC_DYSYMTAB) {
1312 m_dysymtab.cmd = lc.cmd;
1313 m_dysymtab.cmdsize = lc.cmdsize;
1314 if (m_data.GetU32(offset_ptr: &offset, dst: &m_dysymtab.ilocalsym,
1315 count: (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) ==
1316 nullptr) {
1317 // Clear m_dysymtab if we were unable to read all items from the
1318 // load command
1319 ::memset(s: &m_dysymtab, c: 0, n: sizeof(m_dysymtab));
1320 }
1321 }
1322 offset = load_cmd_offset + lc.cmdsize;
1323 }
1324 }
1325 }
1326 if (m_dysymtab.cmd)
1327 return m_dysymtab.nlocalsym <= 1;
1328 return false;
1329}
1330
1331ObjectFileMachO::EncryptedFileRanges ObjectFileMachO::GetEncryptedFileRanges() {
1332 EncryptedFileRanges result;
1333 lldb::offset_t offset = MachHeaderSizeFromMagic(magic: m_header.magic);
1334
1335 llvm::MachO::encryption_info_command encryption_cmd;
1336 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1337 const lldb::offset_t load_cmd_offset = offset;
1338 if (m_data.GetU32(offset_ptr: &offset, dst: &encryption_cmd, count: 2) == nullptr)
1339 break;
1340
1341 // LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for the
1342 // 3 fields we care about, so treat them the same.
1343 if (encryption_cmd.cmd == LC_ENCRYPTION_INFO ||
1344 encryption_cmd.cmd == LC_ENCRYPTION_INFO_64) {
1345 if (m_data.GetU32(offset_ptr: &offset, dst: &encryption_cmd.cryptoff, count: 3)) {
1346 if (encryption_cmd.cryptid != 0) {
1347 EncryptedFileRanges::Entry entry;
1348 entry.SetRangeBase(encryption_cmd.cryptoff);
1349 entry.SetByteSize(encryption_cmd.cryptsize);
1350 result.Append(entry);
1351 }
1352 }
1353 }
1354 offset = load_cmd_offset + encryption_cmd.cmdsize;
1355 }
1356
1357 return result;
1358}
1359
1360void ObjectFileMachO::SanitizeSegmentCommand(
1361 llvm::MachO::segment_command_64 &seg_cmd, uint32_t cmd_idx) {
1362 if (m_length == 0 || seg_cmd.filesize == 0)
1363 return;
1364
1365 if (IsSharedCacheBinary() && !IsInMemory()) {
1366 // In shared cache images, the load commands are relative to the
1367 // shared cache file, and not the specific image we are
1368 // examining. Let's fix this up so that it looks like a normal
1369 // image.
1370 if (strncmp(s1: seg_cmd.segname, s2: GetSegmentNameTEXT().GetCString(),
1371 n: sizeof(seg_cmd.segname)) == 0)
1372 m_text_address = seg_cmd.vmaddr;
1373 if (strncmp(s1: seg_cmd.segname, s2: GetSegmentNameLINKEDIT().GetCString(),
1374 n: sizeof(seg_cmd.segname)) == 0)
1375 m_linkedit_original_offset = seg_cmd.fileoff;
1376
1377 seg_cmd.fileoff = seg_cmd.vmaddr - m_text_address;
1378 }
1379
1380 if (seg_cmd.fileoff > m_length) {
1381 // We have a load command that says it extends past the end of the file.
1382 // This is likely a corrupt file. We don't have any way to return an error
1383 // condition here (this method was likely invoked from something like
1384 // ObjectFile::GetSectionList()), so we just null out the section contents,
1385 // and dump a message to stdout. The most common case here is core file
1386 // debugging with a truncated file.
1387 const char *lc_segment_name =
1388 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1389 GetModule()->ReportWarning(
1390 format: "load command {0} {1} has a fileoff ({2:x16}) that extends beyond "
1391 "the end of the file ({3:x16}), ignoring this section",
1392 args&: cmd_idx, args&: lc_segment_name, args&: seg_cmd.fileoff, args&: m_length);
1393
1394 seg_cmd.fileoff = 0;
1395 seg_cmd.filesize = 0;
1396 }
1397
1398 if (seg_cmd.fileoff + seg_cmd.filesize > m_length) {
1399 // We have a load command that says it extends past the end of the file.
1400 // This is likely a corrupt file. We don't have any way to return an error
1401 // condition here (this method was likely invoked from something like
1402 // ObjectFile::GetSectionList()), so we just null out the section contents,
1403 // and dump a message to stdout. The most common case here is core file
1404 // debugging with a truncated file.
1405 const char *lc_segment_name =
1406 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1407 GetModule()->ReportWarning(
1408 format: "load command {0} {1} has a fileoff + filesize ({2:x16}) that "
1409 "extends beyond the end of the file ({4:x16}), the segment will be "
1410 "truncated to match",
1411 args&: cmd_idx, args&: lc_segment_name, args: seg_cmd.fileoff + seg_cmd.filesize, args&: m_length);
1412
1413 // Truncate the length
1414 seg_cmd.filesize = m_length - seg_cmd.fileoff;
1415 }
1416}
1417
1418static uint32_t
1419GetSegmentPermissions(const llvm::MachO::segment_command_64 &seg_cmd) {
1420 uint32_t result = 0;
1421 if (seg_cmd.initprot & VM_PROT_READ)
1422 result |= ePermissionsReadable;
1423 if (seg_cmd.initprot & VM_PROT_WRITE)
1424 result |= ePermissionsWritable;
1425 if (seg_cmd.initprot & VM_PROT_EXECUTE)
1426 result |= ePermissionsExecutable;
1427 return result;
1428}
1429
1430static lldb::SectionType GetSectionType(uint32_t flags,
1431 ConstString section_name) {
1432
1433 if (flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS))
1434 return eSectionTypeCode;
1435
1436 uint32_t mach_sect_type = flags & SECTION_TYPE;
1437 static ConstString g_sect_name_objc_data("__objc_data");
1438 static ConstString g_sect_name_objc_msgrefs("__objc_msgrefs");
1439 static ConstString g_sect_name_objc_selrefs("__objc_selrefs");
1440 static ConstString g_sect_name_objc_classrefs("__objc_classrefs");
1441 static ConstString g_sect_name_objc_superrefs("__objc_superrefs");
1442 static ConstString g_sect_name_objc_const("__objc_const");
1443 static ConstString g_sect_name_objc_classlist("__objc_classlist");
1444 static ConstString g_sect_name_cfstring("__cfstring");
1445
1446 static ConstString g_sect_name_dwarf_debug_abbrev("__debug_abbrev");
1447 static ConstString g_sect_name_dwarf_debug_abbrev_dwo("__debug_abbrev.dwo");
1448 static ConstString g_sect_name_dwarf_debug_addr("__debug_addr");
1449 static ConstString g_sect_name_dwarf_debug_aranges("__debug_aranges");
1450 static ConstString g_sect_name_dwarf_debug_cu_index("__debug_cu_index");
1451 static ConstString g_sect_name_dwarf_debug_frame("__debug_frame");
1452 static ConstString g_sect_name_dwarf_debug_info("__debug_info");
1453 static ConstString g_sect_name_dwarf_debug_info_dwo("__debug_info.dwo");
1454 static ConstString g_sect_name_dwarf_debug_line("__debug_line");
1455 static ConstString g_sect_name_dwarf_debug_line_dwo("__debug_line.dwo");
1456 static ConstString g_sect_name_dwarf_debug_line_str("__debug_line_str");
1457 static ConstString g_sect_name_dwarf_debug_loc("__debug_loc");
1458 static ConstString g_sect_name_dwarf_debug_loclists("__debug_loclists");
1459 static ConstString g_sect_name_dwarf_debug_loclists_dwo("__debug_loclists.dwo");
1460 static ConstString g_sect_name_dwarf_debug_macinfo("__debug_macinfo");
1461 static ConstString g_sect_name_dwarf_debug_macro("__debug_macro");
1462 static ConstString g_sect_name_dwarf_debug_macro_dwo("__debug_macro.dwo");
1463 static ConstString g_sect_name_dwarf_debug_names("__debug_names");
1464 static ConstString g_sect_name_dwarf_debug_pubnames("__debug_pubnames");
1465 static ConstString g_sect_name_dwarf_debug_pubtypes("__debug_pubtypes");
1466 static ConstString g_sect_name_dwarf_debug_ranges("__debug_ranges");
1467 static ConstString g_sect_name_dwarf_debug_rnglists("__debug_rnglists");
1468 static ConstString g_sect_name_dwarf_debug_str("__debug_str");
1469 static ConstString g_sect_name_dwarf_debug_str_dwo("__debug_str.dwo");
1470 static ConstString g_sect_name_dwarf_debug_str_offs("__debug_str_offs");
1471 static ConstString g_sect_name_dwarf_debug_str_offs_dwo("__debug_str_offs.dwo");
1472 static ConstString g_sect_name_dwarf_debug_tu_index("__debug_tu_index");
1473 static ConstString g_sect_name_dwarf_debug_types("__debug_types");
1474 static ConstString g_sect_name_dwarf_apple_names("__apple_names");
1475 static ConstString g_sect_name_dwarf_apple_types("__apple_types");
1476 static ConstString g_sect_name_dwarf_apple_namespaces("__apple_namespac");
1477 static ConstString g_sect_name_dwarf_apple_objc("__apple_objc");
1478 static ConstString g_sect_name_eh_frame("__eh_frame");
1479 static ConstString g_sect_name_compact_unwind("__unwind_info");
1480 static ConstString g_sect_name_text("__text");
1481 static ConstString g_sect_name_data("__data");
1482 static ConstString g_sect_name_go_symtab("__gosymtab");
1483 static ConstString g_sect_name_ctf("__ctf");
1484 static ConstString g_sect_name_swift_ast("__swift_ast");
1485
1486 if (section_name == g_sect_name_dwarf_debug_abbrev)
1487 return eSectionTypeDWARFDebugAbbrev;
1488 if (section_name == g_sect_name_dwarf_debug_abbrev_dwo)
1489 return eSectionTypeDWARFDebugAbbrevDwo;
1490 if (section_name == g_sect_name_dwarf_debug_addr)
1491 return eSectionTypeDWARFDebugAddr;
1492 if (section_name == g_sect_name_dwarf_debug_aranges)
1493 return eSectionTypeDWARFDebugAranges;
1494 if (section_name == g_sect_name_dwarf_debug_cu_index)
1495 return eSectionTypeDWARFDebugCuIndex;
1496 if (section_name == g_sect_name_dwarf_debug_frame)
1497 return eSectionTypeDWARFDebugFrame;
1498 if (section_name == g_sect_name_dwarf_debug_info)
1499 return eSectionTypeDWARFDebugInfo;
1500 if (section_name == g_sect_name_dwarf_debug_info_dwo)
1501 return eSectionTypeDWARFDebugInfoDwo;
1502 if (section_name == g_sect_name_dwarf_debug_line)
1503 return eSectionTypeDWARFDebugLine;
1504 if (section_name == g_sect_name_dwarf_debug_line_dwo)
1505 return eSectionTypeDWARFDebugLine; // Same as debug_line.
1506 if (section_name == g_sect_name_dwarf_debug_line_str)
1507 return eSectionTypeDWARFDebugLineStr;
1508 if (section_name == g_sect_name_dwarf_debug_loc)
1509 return eSectionTypeDWARFDebugLoc;
1510 if (section_name == g_sect_name_dwarf_debug_loclists)
1511 return eSectionTypeDWARFDebugLocLists;
1512 if (section_name == g_sect_name_dwarf_debug_loclists_dwo)
1513 return eSectionTypeDWARFDebugLocListsDwo;
1514 if (section_name == g_sect_name_dwarf_debug_macinfo)
1515 return eSectionTypeDWARFDebugMacInfo;
1516 if (section_name == g_sect_name_dwarf_debug_macro)
1517 return eSectionTypeDWARFDebugMacro;
1518 if (section_name == g_sect_name_dwarf_debug_macro_dwo)
1519 return eSectionTypeDWARFDebugMacInfo; // Same as debug_macro.
1520 if (section_name == g_sect_name_dwarf_debug_names)
1521 return eSectionTypeDWARFDebugNames;
1522 if (section_name == g_sect_name_dwarf_debug_pubnames)
1523 return eSectionTypeDWARFDebugPubNames;
1524 if (section_name == g_sect_name_dwarf_debug_pubtypes)
1525 return eSectionTypeDWARFDebugPubTypes;
1526 if (section_name == g_sect_name_dwarf_debug_ranges)
1527 return eSectionTypeDWARFDebugRanges;
1528 if (section_name == g_sect_name_dwarf_debug_rnglists)
1529 return eSectionTypeDWARFDebugRngLists;
1530 if (section_name == g_sect_name_dwarf_debug_str)
1531 return eSectionTypeDWARFDebugStr;
1532 if (section_name == g_sect_name_dwarf_debug_str_dwo)
1533 return eSectionTypeDWARFDebugStrDwo;
1534 if (section_name == g_sect_name_dwarf_debug_str_offs)
1535 return eSectionTypeDWARFDebugStrOffsets;
1536 if (section_name == g_sect_name_dwarf_debug_str_offs_dwo)
1537 return eSectionTypeDWARFDebugStrOffsetsDwo;
1538 if (section_name == g_sect_name_dwarf_debug_tu_index)
1539 return eSectionTypeDWARFDebugTuIndex;
1540 if (section_name == g_sect_name_dwarf_debug_types)
1541 return eSectionTypeDWARFDebugTypes;
1542 if (section_name == g_sect_name_dwarf_apple_names)
1543 return eSectionTypeDWARFAppleNames;
1544 if (section_name == g_sect_name_dwarf_apple_types)
1545 return eSectionTypeDWARFAppleTypes;
1546 if (section_name == g_sect_name_dwarf_apple_namespaces)
1547 return eSectionTypeDWARFAppleNamespaces;
1548 if (section_name == g_sect_name_dwarf_apple_objc)
1549 return eSectionTypeDWARFAppleObjC;
1550 if (section_name == g_sect_name_objc_selrefs)
1551 return eSectionTypeDataCStringPointers;
1552 if (section_name == g_sect_name_objc_msgrefs)
1553 return eSectionTypeDataObjCMessageRefs;
1554 if (section_name == g_sect_name_eh_frame)
1555 return eSectionTypeEHFrame;
1556 if (section_name == g_sect_name_compact_unwind)
1557 return eSectionTypeCompactUnwind;
1558 if (section_name == g_sect_name_cfstring)
1559 return eSectionTypeDataObjCCFStrings;
1560 if (section_name == g_sect_name_go_symtab)
1561 return eSectionTypeGoSymtab;
1562 if (section_name == g_sect_name_ctf)
1563 return eSectionTypeCTF;
1564 if (section_name == g_sect_name_swift_ast)
1565 return eSectionTypeSwiftModules;
1566 if (section_name == g_sect_name_objc_data ||
1567 section_name == g_sect_name_objc_classrefs ||
1568 section_name == g_sect_name_objc_superrefs ||
1569 section_name == g_sect_name_objc_const ||
1570 section_name == g_sect_name_objc_classlist) {
1571 return eSectionTypeDataPointers;
1572 }
1573
1574 switch (mach_sect_type) {
1575 // TODO: categorize sections by other flags for regular sections
1576 case S_REGULAR:
1577 if (section_name == g_sect_name_text)
1578 return eSectionTypeCode;
1579 if (section_name == g_sect_name_data)
1580 return eSectionTypeData;
1581 return eSectionTypeOther;
1582 case S_ZEROFILL:
1583 return eSectionTypeZeroFill;
1584 case S_CSTRING_LITERALS: // section with only literal C strings
1585 return eSectionTypeDataCString;
1586 case S_4BYTE_LITERALS: // section with only 4 byte literals
1587 return eSectionTypeData4;
1588 case S_8BYTE_LITERALS: // section with only 8 byte literals
1589 return eSectionTypeData8;
1590 case S_LITERAL_POINTERS: // section with only pointers to literals
1591 return eSectionTypeDataPointers;
1592 case S_NON_LAZY_SYMBOL_POINTERS: // section with only non-lazy symbol pointers
1593 return eSectionTypeDataPointers;
1594 case S_LAZY_SYMBOL_POINTERS: // section with only lazy symbol pointers
1595 return eSectionTypeDataPointers;
1596 case S_SYMBOL_STUBS: // section with only symbol stubs, byte size of stub in
1597 // the reserved2 field
1598 return eSectionTypeCode;
1599 case S_MOD_INIT_FUNC_POINTERS: // section with only function pointers for
1600 // initialization
1601 return eSectionTypeDataPointers;
1602 case S_MOD_TERM_FUNC_POINTERS: // section with only function pointers for
1603 // termination
1604 return eSectionTypeDataPointers;
1605 case S_COALESCED:
1606 return eSectionTypeOther;
1607 case S_GB_ZEROFILL:
1608 return eSectionTypeZeroFill;
1609 case S_INTERPOSING: // section with only pairs of function pointers for
1610 // interposing
1611 return eSectionTypeCode;
1612 case S_16BYTE_LITERALS: // section with only 16 byte literals
1613 return eSectionTypeData16;
1614 case S_DTRACE_DOF:
1615 return eSectionTypeDebug;
1616 case S_LAZY_DYLIB_SYMBOL_POINTERS:
1617 return eSectionTypeDataPointers;
1618 default:
1619 return eSectionTypeOther;
1620 }
1621}
1622
1623struct ObjectFileMachO::SegmentParsingContext {
1624 const EncryptedFileRanges EncryptedRanges;
1625 lldb_private::SectionList &UnifiedList;
1626 uint32_t NextSegmentIdx = 0;
1627 uint32_t NextSectionIdx = 0;
1628 bool FileAddressesChanged = false;
1629
1630 SegmentParsingContext(EncryptedFileRanges EncryptedRanges,
1631 lldb_private::SectionList &UnifiedList)
1632 : EncryptedRanges(std::move(EncryptedRanges)), UnifiedList(UnifiedList) {}
1633};
1634
1635void ObjectFileMachO::ProcessSegmentCommand(
1636 const llvm::MachO::load_command &load_cmd_, lldb::offset_t offset,
1637 uint32_t cmd_idx, SegmentParsingContext &context) {
1638 llvm::MachO::segment_command_64 load_cmd;
1639 memcpy(dest: &load_cmd, src: &load_cmd_, n: sizeof(load_cmd_));
1640
1641 if (!m_data.GetU8(offset_ptr: &offset, dst: (uint8_t *)load_cmd.segname, count: 16))
1642 return;
1643
1644 ModuleSP module_sp = GetModule();
1645 const bool is_core = GetType() == eTypeCoreFile;
1646 const bool is_dsym = (m_header.filetype == MH_DSYM);
1647 bool add_section = true;
1648 bool add_to_unified = true;
1649 ConstString const_segname(
1650 load_cmd.segname, strnlen(string: load_cmd.segname, maxlen: sizeof(load_cmd.segname)));
1651
1652 SectionSP unified_section_sp(
1653 context.UnifiedList.FindSectionByName(section_dstr: const_segname));
1654 if (is_dsym && unified_section_sp) {
1655 if (const_segname == GetSegmentNameLINKEDIT()) {
1656 // We need to keep the __LINKEDIT segment private to this object file
1657 // only
1658 add_to_unified = false;
1659 } else {
1660 // This is the dSYM file and this section has already been created by the
1661 // object file, no need to create it.
1662 add_section = false;
1663 }
1664 }
1665 load_cmd.vmaddr = m_data.GetAddress(offset_ptr: &offset);
1666 load_cmd.vmsize = m_data.GetAddress(offset_ptr: &offset);
1667 load_cmd.fileoff = m_data.GetAddress(offset_ptr: &offset);
1668 load_cmd.filesize = m_data.GetAddress(offset_ptr: &offset);
1669 if (!m_data.GetU32(offset_ptr: &offset, dst: &load_cmd.maxprot, count: 4))
1670 return;
1671
1672 SanitizeSegmentCommand(seg_cmd&: load_cmd, cmd_idx);
1673
1674 const uint32_t segment_permissions = GetSegmentPermissions(seg_cmd: load_cmd);
1675 const bool segment_is_encrypted =
1676 (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
1677
1678 // Use a segment ID of the segment index shifted left by 8 so they never
1679 // conflict with any of the sections.
1680 SectionSP segment_sp;
1681 if (add_section && (const_segname || is_core)) {
1682 segment_sp = std::make_shared<Section>(
1683 args&: module_sp, // Module to which this section belongs
1684 args: this, // Object file to which this sections belongs
1685 args: ++context.NextSegmentIdx
1686 << 8, // Section ID is the 1 based segment index
1687 // shifted right by 8 bits as not to collide with any of the 256
1688 // section IDs that are possible
1689 args&: const_segname, // Name of this section
1690 args: eSectionTypeContainer, // This section is a container of other
1691 // sections.
1692 args&: load_cmd.vmaddr, // File VM address == addresses as they are
1693 // found in the object file
1694 args&: load_cmd.vmsize, // VM size in bytes of this section
1695 args&: load_cmd.fileoff, // Offset to the data for this section in
1696 // the file
1697 args&: load_cmd.filesize, // Size in bytes of this section as found
1698 // in the file
1699 args: 0, // Segments have no alignment information
1700 args&: load_cmd.flags); // Flags for this section
1701
1702 segment_sp->SetIsEncrypted(segment_is_encrypted);
1703 m_sections_up->AddSection(section_sp: segment_sp);
1704 segment_sp->SetPermissions(segment_permissions);
1705 if (add_to_unified)
1706 context.UnifiedList.AddSection(section_sp: segment_sp);
1707 } else if (unified_section_sp) {
1708 // If this is a dSYM and the file addresses in the dSYM differ from the
1709 // file addresses in the ObjectFile, we must use the file base address for
1710 // the Section from the dSYM for the DWARF to resolve correctly.
1711 // This only happens with binaries in the shared cache in practice;
1712 // normally a mismatch like this would give a binary & dSYM that do not
1713 // match UUIDs. When a binary is included in the shared cache, its
1714 // segments are rearranged to optimize the shared cache, so its file
1715 // addresses will differ from what the ObjectFile had originally,
1716 // and what the dSYM has.
1717 if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
1718 Log *log = GetLog(mask: LLDBLog::Symbols);
1719 if (log) {
1720 log->Printf(
1721 format: "Installing dSYM's %s segment file address over ObjectFile's "
1722 "so symbol table/debug info resolves correctly for %s",
1723 const_segname.AsCString(),
1724 module_sp->GetFileSpec().GetFilename().AsCString());
1725 }
1726
1727 // Make sure we've parsed the symbol table from the ObjectFile before
1728 // we go around changing its Sections.
1729 module_sp->GetObjectFile()->GetSymtab();
1730 // eh_frame would present the same problems but we parse that on a per-
1731 // function basis as-needed so it's more difficult to remove its use of
1732 // the Sections. Realistically, the environments where this code path
1733 // will be taken will not have eh_frame sections.
1734
1735 unified_section_sp->SetFileAddress(load_cmd.vmaddr);
1736
1737 // Notify the module that the section addresses have been changed once
1738 // we're done so any file-address caches can be updated.
1739 context.FileAddressesChanged = true;
1740 }
1741 m_sections_up->AddSection(section_sp: unified_section_sp);
1742 }
1743
1744 llvm::MachO::section_64 sect64;
1745 ::memset(s: &sect64, c: 0, n: sizeof(sect64));
1746 // Push a section into our mach sections for the section at index zero
1747 // (NO_SECT) if we don't have any mach sections yet...
1748 if (m_mach_sections.empty())
1749 m_mach_sections.push_back(x: sect64);
1750 uint32_t segment_sect_idx;
1751 const lldb::user_id_t first_segment_sectID = context.NextSectionIdx + 1;
1752
1753 const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
1754 for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
1755 ++segment_sect_idx) {
1756 if (m_data.GetU8(offset_ptr: &offset, dst: (uint8_t *)sect64.sectname,
1757 count: sizeof(sect64.sectname)) == nullptr)
1758 break;
1759 if (m_data.GetU8(offset_ptr: &offset, dst: (uint8_t *)sect64.segname,
1760 count: sizeof(sect64.segname)) == nullptr)
1761 break;
1762 sect64.addr = m_data.GetAddress(offset_ptr: &offset);
1763 sect64.size = m_data.GetAddress(offset_ptr: &offset);
1764
1765 if (m_data.GetU32(offset_ptr: &offset, dst: &sect64.offset, count: num_u32s) == nullptr)
1766 break;
1767
1768 if (IsSharedCacheBinary() && !IsInMemory()) {
1769 sect64.offset = sect64.addr - m_text_address;
1770 }
1771
1772 // Keep a list of mach sections around in case we need to get at data that
1773 // isn't stored in the abstracted Sections.
1774 m_mach_sections.push_back(x: sect64);
1775
1776 if (add_section) {
1777 ConstString section_name(
1778 sect64.sectname, strnlen(string: sect64.sectname, maxlen: sizeof(sect64.sectname)));
1779 if (!const_segname) {
1780 // We have a segment with no name so we need to conjure up segments
1781 // that correspond to the section's segname if there isn't already such
1782 // a section. If there is such a section, we resize the section so that
1783 // it spans all sections. We also mark these sections as fake so
1784 // address matches don't hit if they land in the gaps between the child
1785 // sections.
1786 const_segname.SetTrimmedCStringWithLength(cstr: sect64.segname,
1787 fixed_cstr_len: sizeof(sect64.segname));
1788 segment_sp = context.UnifiedList.FindSectionByName(section_dstr: const_segname);
1789 if (segment_sp.get()) {
1790 Section *segment = segment_sp.get();
1791 // Grow the section size as needed.
1792 const lldb::addr_t sect64_min_addr = sect64.addr;
1793 const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
1794 const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
1795 const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
1796 const lldb::addr_t curr_seg_max_addr =
1797 curr_seg_min_addr + curr_seg_byte_size;
1798 if (sect64_min_addr >= curr_seg_min_addr) {
1799 const lldb::addr_t new_seg_byte_size =
1800 sect64_max_addr - curr_seg_min_addr;
1801 // Only grow the section size if needed
1802 if (new_seg_byte_size > curr_seg_byte_size)
1803 segment->SetByteSize(new_seg_byte_size);
1804 } else {
1805 // We need to change the base address of the segment and adjust the
1806 // child section offsets for all existing children.
1807 const lldb::addr_t slide_amount =
1808 sect64_min_addr - curr_seg_min_addr;
1809 segment->Slide(slide_amount, slide_children: false);
1810 segment->GetChildren().Slide(slide_amount: -slide_amount, slide_children: false);
1811 segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
1812 }
1813
1814 // Grow the section size as needed.
1815 if (sect64.offset) {
1816 const lldb::addr_t segment_min_file_offset =
1817 segment->GetFileOffset();
1818 const lldb::addr_t segment_max_file_offset =
1819 segment_min_file_offset + segment->GetFileSize();
1820
1821 const lldb::addr_t section_min_file_offset = sect64.offset;
1822 const lldb::addr_t section_max_file_offset =
1823 section_min_file_offset + sect64.size;
1824 const lldb::addr_t new_file_offset =
1825 std::min(a: section_min_file_offset, b: segment_min_file_offset);
1826 const lldb::addr_t new_file_size =
1827 std::max(a: section_max_file_offset, b: segment_max_file_offset) -
1828 new_file_offset;
1829 segment->SetFileOffset(new_file_offset);
1830 segment->SetFileSize(new_file_size);
1831 }
1832 } else {
1833 // Create a fake section for the section's named segment
1834 segment_sp = std::make_shared<Section>(
1835 args&: segment_sp, // Parent section
1836 args&: module_sp, // Module to which this section belongs
1837 args: this, // Object file to which this section belongs
1838 args: ++context.NextSegmentIdx
1839 << 8, // Section ID is the 1 based segment index
1840 // shifted right by 8 bits as not to
1841 // collide with any of the 256 section IDs
1842 // that are possible
1843 args&: const_segname, // Name of this section
1844 args: eSectionTypeContainer, // This section is a container of
1845 // other sections.
1846 args&: sect64.addr, // File VM address == addresses as they are
1847 // found in the object file
1848 args&: sect64.size, // VM size in bytes of this section
1849 args&: sect64.offset, // Offset to the data for this section in
1850 // the file
1851 args: sect64.offset ? sect64.size : 0, // Size in bytes of
1852 // this section as
1853 // found in the file
1854 args&: sect64.align,
1855 args&: load_cmd.flags); // Flags for this section
1856 segment_sp->SetIsFake(true);
1857 segment_sp->SetPermissions(segment_permissions);
1858 m_sections_up->AddSection(section_sp: segment_sp);
1859 if (add_to_unified)
1860 context.UnifiedList.AddSection(section_sp: segment_sp);
1861 segment_sp->SetIsEncrypted(segment_is_encrypted);
1862 }
1863 }
1864 assert(segment_sp.get());
1865
1866 lldb::SectionType sect_type = GetSectionType(flags: sect64.flags, section_name);
1867
1868 SectionSP section_sp(new Section(
1869 segment_sp, module_sp, this, ++context.NextSectionIdx, section_name,
1870 sect_type, sect64.addr - segment_sp->GetFileAddress(), sect64.size,
1871 sect64.offset, sect64.offset == 0 ? 0 : sect64.size, sect64.align,
1872 sect64.flags));
1873 // Set the section to be encrypted to match the segment
1874
1875 bool section_is_encrypted = false;
1876 if (!segment_is_encrypted && load_cmd.filesize != 0)
1877 section_is_encrypted = context.EncryptedRanges.FindEntryThatContains(
1878 addr: sect64.offset) != nullptr;
1879
1880 section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted);
1881 section_sp->SetPermissions(segment_permissions);
1882 segment_sp->GetChildren().AddSection(section_sp);
1883
1884 if (segment_sp->IsFake()) {
1885 segment_sp.reset();
1886 const_segname.Clear();
1887 }
1888 }
1889 }
1890 if (segment_sp && is_dsym) {
1891 if (first_segment_sectID <= context.NextSectionIdx) {
1892 lldb::user_id_t sect_uid;
1893 for (sect_uid = first_segment_sectID; sect_uid <= context.NextSectionIdx;
1894 ++sect_uid) {
1895 SectionSP curr_section_sp(
1896 segment_sp->GetChildren().FindSectionByID(sect_id: sect_uid));
1897 SectionSP next_section_sp;
1898 if (sect_uid + 1 <= context.NextSectionIdx)
1899 next_section_sp =
1900 segment_sp->GetChildren().FindSectionByID(sect_id: sect_uid + 1);
1901
1902 if (curr_section_sp.get()) {
1903 if (curr_section_sp->GetByteSize() == 0) {
1904 if (next_section_sp.get() != nullptr)
1905 curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() -
1906 curr_section_sp->GetFileAddress());
1907 else
1908 curr_section_sp->SetByteSize(load_cmd.vmsize);
1909 }
1910 }
1911 }
1912 }
1913 }
1914}
1915
1916void ObjectFileMachO::ProcessDysymtabCommand(
1917 const llvm::MachO::load_command &load_cmd, lldb::offset_t offset) {
1918 m_dysymtab.cmd = load_cmd.cmd;
1919 m_dysymtab.cmdsize = load_cmd.cmdsize;
1920 m_data.GetU32(offset_ptr: &offset, dst: &m_dysymtab.ilocalsym,
1921 count: (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1922}
1923
1924void ObjectFileMachO::CreateSections(SectionList &unified_section_list) {
1925 if (m_sections_up)
1926 return;
1927
1928 m_sections_up = std::make_unique<SectionList>();
1929
1930 lldb::offset_t offset = MachHeaderSizeFromMagic(magic: m_header.magic);
1931 // bool dump_sections = false;
1932 ModuleSP module_sp(GetModule());
1933
1934 offset = MachHeaderSizeFromMagic(magic: m_header.magic);
1935
1936 SegmentParsingContext context(GetEncryptedFileRanges(), unified_section_list);
1937 llvm::MachO::load_command load_cmd;
1938 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1939 const lldb::offset_t load_cmd_offset = offset;
1940 if (m_data.GetU32(offset_ptr: &offset, dst: &load_cmd, count: 2) == nullptr)
1941 break;
1942
1943 if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
1944 ProcessSegmentCommand(load_cmd_: load_cmd, offset, cmd_idx: i, context);
1945 else if (load_cmd.cmd == LC_DYSYMTAB)
1946 ProcessDysymtabCommand(load_cmd, offset);
1947
1948 offset = load_cmd_offset + load_cmd.cmdsize;
1949 }
1950
1951 if (context.FileAddressesChanged && module_sp)
1952 module_sp->SectionFileAddressesChanged();
1953}
1954
1955class MachSymtabSectionInfo {
1956public:
1957 MachSymtabSectionInfo(SectionList *section_list)
1958 : m_section_list(section_list), m_section_infos() {
1959 // Get the number of sections down to a depth of 1 to include all segments
1960 // and their sections, but no other sections that may be added for debug
1961 // map or
1962 m_section_infos.resize(new_size: section_list->GetNumSections(depth: 1));
1963 }
1964
1965 SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
1966 if (n_sect == 0)
1967 return SectionSP();
1968 if (n_sect < m_section_infos.size()) {
1969 if (!m_section_infos[n_sect].section_sp) {
1970 SectionSP section_sp(m_section_list->FindSectionByID(sect_id: n_sect));
1971 m_section_infos[n_sect].section_sp = section_sp;
1972 if (section_sp) {
1973 m_section_infos[n_sect].vm_range.SetBaseAddress(
1974 section_sp->GetFileAddress());
1975 m_section_infos[n_sect].vm_range.SetByteSize(
1976 section_sp->GetByteSize());
1977 } else {
1978 std::string filename = "<unknown>";
1979 SectionSP first_section_sp(m_section_list->GetSectionAtIndex(idx: 0));
1980 if (first_section_sp)
1981 filename = first_section_sp->GetObjectFile()->GetFileSpec().GetPath();
1982
1983 Debugger::ReportError(
1984 message: llvm::formatv(Fmt: "unable to find section {0} for a symbol in "
1985 "{1}, corrupt file?",
1986 Vals&: n_sect, Vals&: filename));
1987 }
1988 }
1989 if (m_section_infos[n_sect].vm_range.Contains(addr: file_addr)) {
1990 // Symbol is in section.
1991 return m_section_infos[n_sect].section_sp;
1992 } else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
1993 m_section_infos[n_sect].vm_range.GetBaseAddress() ==
1994 file_addr) {
1995 // Symbol is in section with zero size, but has the same start address
1996 // as the section. This can happen with linker symbols (symbols that
1997 // start with the letter 'l' or 'L'.
1998 return m_section_infos[n_sect].section_sp;
1999 }
2000 }
2001 return m_section_list->FindSectionContainingFileAddress(addr: file_addr);
2002 }
2003
2004protected:
2005 struct SectionInfo {
2006 SectionInfo() : vm_range(), section_sp() {}
2007
2008 VMRange vm_range;
2009 SectionSP section_sp;
2010 };
2011 SectionList *m_section_list;
2012 std::vector<SectionInfo> m_section_infos;
2013};
2014
2015#define TRIE_SYMBOL_IS_THUMB (1ULL << 63)
2016struct TrieEntry {
2017 void Dump() const {
2018 printf(format: "0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"",
2019 static_cast<unsigned long long>(address),
2020 static_cast<unsigned long long>(flags),
2021 static_cast<unsigned long long>(other), name.GetCString());
2022 if (import_name)
2023 printf(format: " -> \"%s\"\n", import_name.GetCString());
2024 else
2025 printf(format: "\n");
2026 }
2027 ConstString name;
2028 uint64_t address = LLDB_INVALID_ADDRESS;
2029 uint64_t flags =
2030 0; // EXPORT_SYMBOL_FLAGS_REEXPORT, EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER,
2031 // TRIE_SYMBOL_IS_THUMB
2032 uint64_t other = 0;
2033 ConstString import_name;
2034};
2035
2036struct TrieEntryWithOffset {
2037 lldb::offset_t nodeOffset;
2038 TrieEntry entry;
2039
2040 TrieEntryWithOffset(lldb::offset_t offset) : nodeOffset(offset), entry() {}
2041
2042 void Dump(uint32_t idx) const {
2043 printf(format: "[%3u] 0x%16.16llx: ", idx,
2044 static_cast<unsigned long long>(nodeOffset));
2045 entry.Dump();
2046 }
2047
2048 bool operator<(const TrieEntryWithOffset &other) const {
2049 return (nodeOffset < other.nodeOffset);
2050 }
2051};
2052
2053static bool ParseTrieEntries(DataExtractor &data, lldb::offset_t offset,
2054 const bool is_arm, addr_t text_seg_base_addr,
2055 std::vector<llvm::StringRef> &nameSlices,
2056 std::set<lldb::addr_t> &resolver_addresses,
2057 std::vector<TrieEntryWithOffset> &reexports,
2058 std::vector<TrieEntryWithOffset> &ext_symbols) {
2059 if (!data.ValidOffset(offset))
2060 return true;
2061
2062 // Terminal node -- end of a branch, possibly add this to
2063 // the symbol table or resolver table.
2064 const uint64_t terminalSize = data.GetULEB128(offset_ptr: &offset);
2065 lldb::offset_t children_offset = offset + terminalSize;
2066 if (terminalSize != 0) {
2067 TrieEntryWithOffset e(offset);
2068 e.entry.flags = data.GetULEB128(offset_ptr: &offset);
2069 const char *import_name = nullptr;
2070 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
2071 e.entry.address = 0;
2072 e.entry.other = data.GetULEB128(offset_ptr: &offset); // dylib ordinal
2073 import_name = data.GetCStr(offset_ptr: &offset);
2074 } else {
2075 e.entry.address = data.GetULEB128(offset_ptr: &offset);
2076 if (text_seg_base_addr != LLDB_INVALID_ADDRESS)
2077 e.entry.address += text_seg_base_addr;
2078 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2079 e.entry.other = data.GetULEB128(offset_ptr: &offset);
2080 uint64_t resolver_addr = e.entry.other;
2081 if (text_seg_base_addr != LLDB_INVALID_ADDRESS)
2082 resolver_addr += text_seg_base_addr;
2083 if (is_arm)
2084 resolver_addr &= THUMB_ADDRESS_BIT_MASK;
2085 resolver_addresses.insert(x: resolver_addr);
2086 } else
2087 e.entry.other = 0;
2088 }
2089 bool add_this_entry = false;
2090 if (Flags(e.entry.flags).Test(bit: EXPORT_SYMBOL_FLAGS_REEXPORT) &&
2091 import_name && import_name[0]) {
2092 // add symbols that are reexport symbols with a valid import name.
2093 add_this_entry = true;
2094 } else if (e.entry.flags == 0 &&
2095 (import_name == nullptr || import_name[0] == '\0')) {
2096 // add externally visible symbols, in case the nlist record has
2097 // been stripped/omitted.
2098 add_this_entry = true;
2099 }
2100 if (add_this_entry) {
2101 std::string name;
2102 if (!nameSlices.empty()) {
2103 for (auto name_slice : nameSlices)
2104 name.append(s: name_slice.data(), n: name_slice.size());
2105 }
2106 if (name.size() > 1) {
2107 // Skip the leading '_'
2108 e.entry.name.SetCStringWithLength(cstr: name.c_str() + 1, cstr_len: name.size() - 1);
2109 }
2110 if (import_name) {
2111 // Skip the leading '_'
2112 e.entry.import_name.SetCString(import_name + 1);
2113 }
2114 if (Flags(e.entry.flags).Test(bit: EXPORT_SYMBOL_FLAGS_REEXPORT)) {
2115 reexports.push_back(x: e);
2116 } else {
2117 if (is_arm && (e.entry.address & 1)) {
2118 e.entry.flags |= TRIE_SYMBOL_IS_THUMB;
2119 e.entry.address &= THUMB_ADDRESS_BIT_MASK;
2120 }
2121 ext_symbols.push_back(x: e);
2122 }
2123 }
2124 }
2125
2126 const uint8_t childrenCount = data.GetU8(offset_ptr: &children_offset);
2127 for (uint8_t i = 0; i < childrenCount; ++i) {
2128 const char *cstr = data.GetCStr(offset_ptr: &children_offset);
2129 if (cstr)
2130 nameSlices.push_back(x: llvm::StringRef(cstr));
2131 else
2132 return false; // Corrupt data
2133 lldb::offset_t childNodeOffset = data.GetULEB128(offset_ptr: &children_offset);
2134 if (childNodeOffset) {
2135 if (!ParseTrieEntries(data, offset: childNodeOffset, is_arm, text_seg_base_addr,
2136 nameSlices, resolver_addresses, reexports,
2137 ext_symbols)) {
2138 return false;
2139 }
2140 }
2141 nameSlices.pop_back();
2142 }
2143 return true;
2144}
2145
2146static SymbolType GetSymbolType(const char *&symbol_name,
2147 bool &demangled_is_synthesized,
2148 const SectionSP &text_section_sp,
2149 const SectionSP &data_section_sp,
2150 const SectionSP &data_dirty_section_sp,
2151 const SectionSP &data_const_section_sp,
2152 const SectionSP &symbol_section) {
2153 SymbolType type = eSymbolTypeInvalid;
2154
2155 const char *symbol_sect_name = symbol_section->GetName().AsCString();
2156 if (symbol_section->IsDescendant(section: text_section_sp.get())) {
2157 if (symbol_section->IsClear(bit: S_ATTR_PURE_INSTRUCTIONS |
2158 S_ATTR_SELF_MODIFYING_CODE |
2159 S_ATTR_SOME_INSTRUCTIONS))
2160 type = eSymbolTypeData;
2161 else
2162 type = eSymbolTypeCode;
2163 } else if (symbol_section->IsDescendant(section: data_section_sp.get()) ||
2164 symbol_section->IsDescendant(section: data_dirty_section_sp.get()) ||
2165 symbol_section->IsDescendant(section: data_const_section_sp.get())) {
2166 if (symbol_sect_name &&
2167 ::strstr(haystack: symbol_sect_name, needle: "__objc") == symbol_sect_name) {
2168 type = eSymbolTypeRuntime;
2169
2170 if (symbol_name) {
2171 llvm::StringRef symbol_name_ref(symbol_name);
2172 if (symbol_name_ref.starts_with(Prefix: "OBJC_")) {
2173 static const llvm::StringRef g_objc_v2_prefix_class("OBJC_CLASS_$_");
2174 static const llvm::StringRef g_objc_v2_prefix_metaclass(
2175 "OBJC_METACLASS_$_");
2176 static const llvm::StringRef g_objc_v2_prefix_ivar("OBJC_IVAR_$_");
2177 if (symbol_name_ref.starts_with(Prefix: g_objc_v2_prefix_class)) {
2178 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
2179 type = eSymbolTypeObjCClass;
2180 demangled_is_synthesized = true;
2181 } else if (symbol_name_ref.starts_with(Prefix: g_objc_v2_prefix_metaclass)) {
2182 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
2183 type = eSymbolTypeObjCMetaClass;
2184 demangled_is_synthesized = true;
2185 } else if (symbol_name_ref.starts_with(Prefix: g_objc_v2_prefix_ivar)) {
2186 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
2187 type = eSymbolTypeObjCIVar;
2188 demangled_is_synthesized = true;
2189 }
2190 }
2191 }
2192 } else if (symbol_sect_name &&
2193 ::strstr(haystack: symbol_sect_name, needle: "__gcc_except_tab") ==
2194 symbol_sect_name) {
2195 type = eSymbolTypeException;
2196 } else {
2197 type = eSymbolTypeData;
2198 }
2199 } else if (symbol_sect_name &&
2200 ::strstr(haystack: symbol_sect_name, needle: "__IMPORT") == symbol_sect_name) {
2201 type = eSymbolTypeTrampoline;
2202 }
2203 return type;
2204}
2205
2206static std::optional<struct nlist_64>
2207ParseNList(DataExtractor &nlist_data, lldb::offset_t &nlist_data_offset,
2208 size_t nlist_byte_size) {
2209 struct nlist_64 nlist;
2210 if (!nlist_data.ValidOffsetForDataOfSize(offset: nlist_data_offset, length: nlist_byte_size))
2211 return {};
2212 nlist.n_strx = nlist_data.GetU32_unchecked(offset_ptr: &nlist_data_offset);
2213 nlist.n_type = nlist_data.GetU8_unchecked(offset_ptr: &nlist_data_offset);
2214 nlist.n_sect = nlist_data.GetU8_unchecked(offset_ptr: &nlist_data_offset);
2215 nlist.n_desc = nlist_data.GetU16_unchecked(offset_ptr: &nlist_data_offset);
2216 nlist.n_value = nlist_data.GetAddress_unchecked(offset_ptr: &nlist_data_offset);
2217 return nlist;
2218}
2219
2220enum { DebugSymbols = true, NonDebugSymbols = false };
2221
2222void ObjectFileMachO::ParseSymtab(Symtab &symtab) {
2223 ModuleSP module_sp(GetModule());
2224 if (!module_sp)
2225 return;
2226
2227 Log *log = GetLog(mask: LLDBLog::Symbols);
2228
2229 const FileSpec &file = m_file ? m_file : module_sp->GetFileSpec();
2230 const char *file_name = file.GetFilename().AsCString(value_if_empty: "<Unknown>");
2231 LLDB_SCOPED_TIMERF("ObjectFileMachO::ParseSymtab () module = %s", file_name);
2232 LLDB_LOG(log, "Parsing symbol table for {0}", file_name);
2233 Progress progress("Parsing symbol table", file_name);
2234
2235 llvm::MachO::symtab_command symtab_load_command = {.cmd: 0, .cmdsize: 0, .symoff: 0, .nsyms: 0, .stroff: 0, .strsize: 0};
2236 llvm::MachO::linkedit_data_command function_starts_load_command = {.cmd: 0, .cmdsize: 0, .dataoff: 0, .datasize: 0};
2237 llvm::MachO::linkedit_data_command exports_trie_load_command = {.cmd: 0, .cmdsize: 0, .dataoff: 0, .datasize: 0};
2238 llvm::MachO::dyld_info_command dyld_info = {.cmd: 0, .cmdsize: 0, .rebase_off: 0, .rebase_size: 0, .bind_off: 0, .bind_size: 0, .weak_bind_off: 0, .weak_bind_size: 0, .lazy_bind_off: 0, .lazy_bind_size: 0, .export_off: 0, .export_size: 0};
2239 llvm::MachO::dysymtab_command dysymtab = m_dysymtab;
2240 // The data element of type bool indicates that this entry is thumb
2241 // code.
2242 typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2243
2244 // Record the address of every function/data that we add to the symtab.
2245 // We add symbols to the table in the order of most information (nlist
2246 // records) to least (function starts), and avoid duplicating symbols
2247 // via this set.
2248 llvm::DenseSet<addr_t> symbols_added;
2249
2250 // We are using a llvm::DenseSet for "symbols_added" so we must be sure we
2251 // do not add the tombstone or empty keys to the set.
2252 auto add_symbol_addr = [&symbols_added](lldb::addr_t file_addr) {
2253 // Don't add the tombstone or empty keys.
2254 if (file_addr == UINT64_MAX || file_addr == UINT64_MAX - 1)
2255 return;
2256 symbols_added.insert(V: file_addr);
2257 };
2258 FunctionStarts function_starts;
2259 lldb::offset_t offset = MachHeaderSizeFromMagic(magic: m_header.magic);
2260 uint32_t i;
2261 FileSpecList dylib_files;
2262 llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2263 llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
2264 llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2265 UUID image_uuid;
2266
2267 for (i = 0; i < m_header.ncmds; ++i) {
2268 const lldb::offset_t cmd_offset = offset;
2269 // Read in the load command and load command size
2270 llvm::MachO::load_command lc;
2271 if (m_data.GetU32(offset_ptr: &offset, dst: &lc, count: 2) == nullptr)
2272 break;
2273 // Watch for the symbol table load command
2274 switch (lc.cmd) {
2275 case LC_SYMTAB:
2276 symtab_load_command.cmd = lc.cmd;
2277 symtab_load_command.cmdsize = lc.cmdsize;
2278 // Read in the rest of the symtab load command
2279 if (m_data.GetU32(offset_ptr: &offset, dst: &symtab_load_command.symoff, count: 4) ==
2280 nullptr) // fill in symoff, nsyms, stroff, strsize fields
2281 return;
2282 break;
2283
2284 case LC_DYLD_INFO:
2285 case LC_DYLD_INFO_ONLY:
2286 if (m_data.GetU32(offset_ptr: &offset, dst: &dyld_info.rebase_off, count: 10)) {
2287 dyld_info.cmd = lc.cmd;
2288 dyld_info.cmdsize = lc.cmdsize;
2289 } else {
2290 memset(s: &dyld_info, c: 0, n: sizeof(dyld_info));
2291 }
2292 break;
2293
2294 case LC_LOAD_DYLIB:
2295 case LC_LOAD_WEAK_DYLIB:
2296 case LC_REEXPORT_DYLIB:
2297 case LC_LOADFVMLIB:
2298 case LC_LOAD_UPWARD_DYLIB: {
2299 uint32_t name_offset = cmd_offset + m_data.GetU32(offset_ptr: &offset);
2300 const char *path = m_data.PeekCStr(offset: name_offset);
2301 if (path) {
2302 FileSpec file_spec(path);
2303 // Strip the path if there is @rpath, @executable, etc so we just use
2304 // the basename
2305 if (path[0] == '@')
2306 file_spec.ClearDirectory();
2307
2308 if (lc.cmd == LC_REEXPORT_DYLIB) {
2309 m_reexported_dylibs.AppendIfUnique(file: file_spec);
2310 }
2311
2312 dylib_files.Append(file: file_spec);
2313 }
2314 } break;
2315
2316 case LC_DYLD_EXPORTS_TRIE:
2317 exports_trie_load_command.cmd = lc.cmd;
2318 exports_trie_load_command.cmdsize = lc.cmdsize;
2319 if (m_data.GetU32(offset_ptr: &offset, dst: &exports_trie_load_command.dataoff, count: 2) ==
2320 nullptr) // fill in offset and size fields
2321 memset(s: &exports_trie_load_command, c: 0,
2322 n: sizeof(exports_trie_load_command));
2323 break;
2324 case LC_FUNCTION_STARTS:
2325 function_starts_load_command.cmd = lc.cmd;
2326 function_starts_load_command.cmdsize = lc.cmdsize;
2327 if (m_data.GetU32(offset_ptr: &offset, dst: &function_starts_load_command.dataoff, count: 2) ==
2328 nullptr) // fill in data offset and size fields
2329 memset(s: &function_starts_load_command, c: 0,
2330 n: sizeof(function_starts_load_command));
2331 break;
2332
2333 case LC_UUID: {
2334 const uint8_t *uuid_bytes = m_data.PeekData(offset, length: 16);
2335
2336 if (uuid_bytes)
2337 image_uuid = UUID(uuid_bytes, 16);
2338 break;
2339 }
2340
2341 default:
2342 break;
2343 }
2344 offset = cmd_offset + lc.cmdsize;
2345 }
2346
2347 if (!symtab_load_command.cmd)
2348 return;
2349
2350 SectionList *section_list = GetSectionList();
2351 if (section_list == nullptr)
2352 return;
2353
2354 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
2355 const ByteOrder byte_order = m_data.GetByteOrder();
2356 bool bit_width_32 = addr_byte_size == 4;
2357 const size_t nlist_byte_size =
2358 bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2359
2360 DataExtractor nlist_data(nullptr, 0, byte_order, addr_byte_size);
2361 DataExtractor strtab_data(nullptr, 0, byte_order, addr_byte_size);
2362 DataExtractor function_starts_data(nullptr, 0, byte_order, addr_byte_size);
2363 DataExtractor indirect_symbol_index_data(nullptr, 0, byte_order,
2364 addr_byte_size);
2365 DataExtractor dyld_trie_data(nullptr, 0, byte_order, addr_byte_size);
2366
2367 const addr_t nlist_data_byte_size =
2368 symtab_load_command.nsyms * nlist_byte_size;
2369 const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2370 addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2371
2372 ProcessSP process_sp(m_process_wp.lock());
2373 Process *process = process_sp.get();
2374
2375 uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2376 bool is_shared_cache_image = IsSharedCacheBinary();
2377 bool is_local_shared_cache_image = is_shared_cache_image && !IsInMemory();
2378 SectionSP linkedit_section_sp(
2379 section_list->FindSectionByName(section_dstr: GetSegmentNameLINKEDIT()));
2380
2381 if (process && m_header.filetype != llvm::MachO::MH_OBJECT &&
2382 !is_local_shared_cache_image) {
2383 Target &target = process->GetTarget();
2384
2385 memory_module_load_level = target.GetMemoryModuleLoadLevel();
2386
2387 // Reading mach file from memory in a process or core file...
2388
2389 if (linkedit_section_sp) {
2390 addr_t linkedit_load_addr =
2391 linkedit_section_sp->GetLoadBaseAddress(target: &target);
2392 if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2393 // We might be trying to access the symbol table before the
2394 // __LINKEDIT's load address has been set in the target. We can't
2395 // fail to read the symbol table, so calculate the right address
2396 // manually
2397 linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2398 mach_header_load_address: m_memory_addr, mach_header_section: GetMachHeaderSection(), section: linkedit_section_sp.get());
2399 }
2400
2401 const addr_t linkedit_file_offset = linkedit_section_sp->GetFileOffset();
2402 const addr_t symoff_addr = linkedit_load_addr +
2403 symtab_load_command.symoff -
2404 linkedit_file_offset;
2405 strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2406 linkedit_file_offset;
2407
2408 // Always load dyld - the dynamic linker - from memory if we didn't
2409 // find a binary anywhere else. lldb will not register
2410 // dylib/framework/bundle loads/unloads if we don't have the dyld
2411 // symbols, we force dyld to load from memory despite the user's
2412 // target.memory-module-load-level setting.
2413 if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2414 m_header.filetype == llvm::MachO::MH_DYLINKER) {
2415 DataBufferSP nlist_data_sp(
2416 ReadMemory(process_sp, addr: symoff_addr, byte_size: nlist_data_byte_size));
2417 if (nlist_data_sp)
2418 nlist_data.SetData(data_sp: nlist_data_sp, offset: 0, length: nlist_data_sp->GetByteSize());
2419 if (dysymtab.nindirectsyms != 0) {
2420 const addr_t indirect_syms_addr = linkedit_load_addr +
2421 dysymtab.indirectsymoff -
2422 linkedit_file_offset;
2423 DataBufferSP indirect_syms_data_sp(ReadMemory(
2424 process_sp, addr: indirect_syms_addr, byte_size: dysymtab.nindirectsyms * 4));
2425 if (indirect_syms_data_sp)
2426 indirect_symbol_index_data.SetData(
2427 data_sp: indirect_syms_data_sp, offset: 0,
2428 length: indirect_syms_data_sp->GetByteSize());
2429 // If this binary is outside the shared cache,
2430 // cache the string table.
2431 // Binaries in the shared cache all share a giant string table,
2432 // and we can't share the string tables across multiple
2433 // ObjectFileMachO's, so we'd end up re-reading this mega-strtab
2434 // for every binary in the shared cache - it would be a big perf
2435 // problem. For binaries outside the shared cache, it's faster to
2436 // read the entire strtab at once instead of piece-by-piece as we
2437 // process the nlist records.
2438 if (!is_shared_cache_image) {
2439 DataBufferSP strtab_data_sp(
2440 ReadMemory(process_sp, addr: strtab_addr, byte_size: strtab_data_byte_size));
2441 if (strtab_data_sp) {
2442 strtab_data.SetData(data_sp: strtab_data_sp, offset: 0,
2443 length: strtab_data_sp->GetByteSize());
2444 }
2445 }
2446 }
2447 if (memory_module_load_level >= eMemoryModuleLoadLevelPartial) {
2448 if (function_starts_load_command.cmd) {
2449 const addr_t func_start_addr =
2450 linkedit_load_addr + function_starts_load_command.dataoff -
2451 linkedit_file_offset;
2452 DataBufferSP func_start_data_sp(
2453 ReadMemory(process_sp, addr: func_start_addr,
2454 byte_size: function_starts_load_command.datasize));
2455 if (func_start_data_sp)
2456 function_starts_data.SetData(data_sp: func_start_data_sp, offset: 0,
2457 length: func_start_data_sp->GetByteSize());
2458 }
2459 }
2460 }
2461 }
2462 } else {
2463 if (is_local_shared_cache_image) {
2464 // The load commands in shared cache images are relative to the
2465 // beginning of the shared cache, not the library image. The
2466 // data we get handed when creating the ObjectFileMachO starts
2467 // at the beginning of a specific library and spans to the end
2468 // of the cache to be able to reach the shared LINKEDIT
2469 // segments. We need to convert the load command offsets to be
2470 // relative to the beginning of our specific image.
2471 lldb::addr_t linkedit_offset = linkedit_section_sp->GetFileOffset();
2472 lldb::offset_t linkedit_slide =
2473 linkedit_offset - m_linkedit_original_offset;
2474 symtab_load_command.symoff += linkedit_slide;
2475 symtab_load_command.stroff += linkedit_slide;
2476 dyld_info.export_off += linkedit_slide;
2477 dysymtab.indirectsymoff += linkedit_slide;
2478 function_starts_load_command.dataoff += linkedit_slide;
2479 exports_trie_load_command.dataoff += linkedit_slide;
2480 }
2481
2482 nlist_data.SetData(data: m_data, offset: symtab_load_command.symoff,
2483 length: nlist_data_byte_size);
2484 strtab_data.SetData(data: m_data, offset: symtab_load_command.stroff,
2485 length: strtab_data_byte_size);
2486
2487 // We shouldn't have exports data from both the LC_DYLD_INFO command
2488 // AND the LC_DYLD_EXPORTS_TRIE command in the same binary:
2489 lldbassert(!((dyld_info.export_size > 0)
2490 && (exports_trie_load_command.datasize > 0)));
2491 if (dyld_info.export_size > 0) {
2492 dyld_trie_data.SetData(data: m_data, offset: dyld_info.export_off,
2493 length: dyld_info.export_size);
2494 } else if (exports_trie_load_command.datasize > 0) {
2495 dyld_trie_data.SetData(data: m_data, offset: exports_trie_load_command.dataoff,
2496 length: exports_trie_load_command.datasize);
2497 }
2498
2499 if (dysymtab.nindirectsyms != 0) {
2500 indirect_symbol_index_data.SetData(data: m_data, offset: dysymtab.indirectsymoff,
2501 length: dysymtab.nindirectsyms * 4);
2502 }
2503 if (function_starts_load_command.cmd) {
2504 function_starts_data.SetData(data: m_data, offset: function_starts_load_command.dataoff,
2505 length: function_starts_load_command.datasize);
2506 }
2507 }
2508
2509 const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2510
2511 ConstString g_segment_name_TEXT = GetSegmentNameTEXT();
2512 ConstString g_segment_name_DATA = GetSegmentNameDATA();
2513 ConstString g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
2514 ConstString g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
2515 ConstString g_segment_name_OBJC = GetSegmentNameOBJC();
2516 ConstString g_section_name_eh_frame = GetSectionNameEHFrame();
2517 SectionSP text_section_sp(
2518 section_list->FindSectionByName(section_dstr: g_segment_name_TEXT));
2519 SectionSP data_section_sp(
2520 section_list->FindSectionByName(section_dstr: g_segment_name_DATA));
2521 SectionSP data_dirty_section_sp(
2522 section_list->FindSectionByName(section_dstr: g_segment_name_DATA_DIRTY));
2523 SectionSP data_const_section_sp(
2524 section_list->FindSectionByName(section_dstr: g_segment_name_DATA_CONST));
2525 SectionSP objc_section_sp(
2526 section_list->FindSectionByName(section_dstr: g_segment_name_OBJC));
2527 SectionSP eh_frame_section_sp;
2528 if (text_section_sp.get())
2529 eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2530 section_dstr: g_section_name_eh_frame);
2531 else
2532 eh_frame_section_sp =
2533 section_list->FindSectionByName(section_dstr: g_section_name_eh_frame);
2534
2535 const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
2536 const bool always_thumb = GetArchitecture().IsAlwaysThumbInstructions();
2537
2538 // lldb works best if it knows the start address of all functions in a
2539 // module. Linker symbols or debug info are normally the best source of
2540 // information for start addr / size but they may be stripped in a released
2541 // binary. Two additional sources of information exist in Mach-O binaries:
2542 // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2543 // function's start address in the
2544 // binary, relative to the text section.
2545 // eh_frame - the eh_frame FDEs have the start addr & size of
2546 // each function
2547 // LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2548 // all modern binaries.
2549 // Binaries built to run on older releases may need to use eh_frame
2550 // information.
2551
2552 if (text_section_sp && function_starts_data.GetByteSize()) {
2553 FunctionStarts::Entry function_start_entry;
2554 function_start_entry.data = false;
2555 lldb::offset_t function_start_offset = 0;
2556 function_start_entry.addr = text_section_sp->GetFileAddress();
2557 uint64_t delta;
2558 while ((delta = function_starts_data.GetULEB128(offset_ptr: &function_start_offset)) >
2559 0) {
2560 // Now append the current entry
2561 function_start_entry.addr += delta;
2562 if (is_arm) {
2563 if (function_start_entry.addr & 1) {
2564 function_start_entry.addr &= THUMB_ADDRESS_BIT_MASK;
2565 function_start_entry.data = true;
2566 } else if (always_thumb) {
2567 function_start_entry.data = true;
2568 }
2569 }
2570 function_starts.Append(entry: function_start_entry);
2571 }
2572 } else {
2573 // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
2574 // load command claiming an eh_frame but it doesn't actually have the
2575 // eh_frame content. And if we have a dSYM, we don't need to do any of
2576 // this fill-in-the-missing-symbols works anyway - the debug info should
2577 // give us all the functions in the module.
2578 if (text_section_sp.get() && eh_frame_section_sp.get() &&
2579 m_type != eTypeDebugInfo) {
2580 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
2581 DWARFCallFrameInfo::EH);
2582 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2583 eh_frame.GetFunctionAddressAndSizeVector(function_info&: functions);
2584 addr_t text_base_addr = text_section_sp->GetFileAddress();
2585 size_t count = functions.GetSize();
2586 for (size_t i = 0; i < count; ++i) {
2587 const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
2588 functions.GetEntryAtIndex(i);
2589 if (func) {
2590 FunctionStarts::Entry function_start_entry;
2591 function_start_entry.addr = func->base - text_base_addr;
2592 if (is_arm) {
2593 if (function_start_entry.addr & 1) {
2594 function_start_entry.addr &= THUMB_ADDRESS_BIT_MASK;
2595 function_start_entry.data = true;
2596 } else if (always_thumb) {
2597 function_start_entry.data = true;
2598 }
2599 }
2600 function_starts.Append(entry: function_start_entry);
2601 }
2602 }
2603 }
2604 }
2605
2606 const size_t function_starts_count = function_starts.GetSize();
2607
2608 // For user process binaries (executables, dylibs, frameworks, bundles), if
2609 // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
2610 // going to assume the binary has been stripped. Don't allow assembly
2611 // language instruction emulation because we don't know proper function
2612 // start boundaries.
2613 //
2614 // For all other types of binaries (kernels, stand-alone bare board
2615 // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
2616 // sections - we should not make any assumptions about them based on that.
2617 if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2618 m_allow_assembly_emulation_unwind_plans = false;
2619 Log *unwind_or_symbol_log(GetLog(mask: LLDBLog::Symbols | LLDBLog::Unwind));
2620
2621 if (unwind_or_symbol_log)
2622 module_sp->LogMessage(
2623 log: unwind_or_symbol_log,
2624 format: "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2625 }
2626
2627 const user_id_t TEXT_eh_frame_sectID = eh_frame_section_sp.get()
2628 ? eh_frame_section_sp->GetID()
2629 : static_cast<user_id_t>(NO_SECT);
2630
2631 uint32_t N_SO_index = UINT32_MAX;
2632
2633 MachSymtabSectionInfo section_info(section_list);
2634 std::vector<uint32_t> N_FUN_indexes;
2635 std::vector<uint32_t> N_NSYM_indexes;
2636 std::vector<uint32_t> N_INCL_indexes;
2637 std::vector<uint32_t> N_BRAC_indexes;
2638 std::vector<uint32_t> N_COMM_indexes;
2639 typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2640 typedef llvm::DenseMap<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2641 typedef llvm::DenseMap<const char *, uint32_t> ConstNameToSymbolIndexMap;
2642 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2643 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2644 ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
2645 // Any symbols that get merged into another will get an entry in this map
2646 // so we know
2647 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2648 uint32_t nlist_idx = 0;
2649 Symbol *symbol_ptr = nullptr;
2650
2651 uint32_t sym_idx = 0;
2652 Symbol *sym = nullptr;
2653 size_t num_syms = 0;
2654 std::string memory_symbol_name;
2655 uint32_t unmapped_local_symbols_found = 0;
2656
2657 std::vector<TrieEntryWithOffset> reexport_trie_entries;
2658 std::vector<TrieEntryWithOffset> external_sym_trie_entries;
2659 std::set<lldb::addr_t> resolver_addresses;
2660
2661 const size_t dyld_trie_data_size = dyld_trie_data.GetByteSize();
2662 if (dyld_trie_data_size > 0) {
2663 LLDB_LOG(log, "Parsing {0} bytes of dyld trie data", dyld_trie_data_size);
2664 SectionSP text_segment_sp =
2665 GetSectionList()->FindSectionByName(section_dstr: GetSegmentNameTEXT());
2666 lldb::addr_t text_segment_file_addr = LLDB_INVALID_ADDRESS;
2667 if (text_segment_sp)
2668 text_segment_file_addr = text_segment_sp->GetFileAddress();
2669 std::vector<llvm::StringRef> nameSlices;
2670 ParseTrieEntries(data&: dyld_trie_data, offset: 0, is_arm, text_seg_base_addr: text_segment_file_addr,
2671 nameSlices, resolver_addresses, reexports&: reexport_trie_entries,
2672 ext_symbols&: external_sym_trie_entries);
2673 }
2674
2675 typedef std::set<ConstString> IndirectSymbols;
2676 IndirectSymbols indirect_symbol_names;
2677
2678#if TARGET_OS_IPHONE
2679
2680 // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
2681 // optimized by moving LOCAL symbols out of the memory mapped portion of
2682 // the DSC. The symbol information has all been retained, but it isn't
2683 // available in the normal nlist data. However, there *are* duplicate
2684 // entries of *some*
2685 // LOCAL symbols in the normal nlist data. To handle this situation
2686 // correctly, we must first attempt
2687 // to parse any DSC unmapped symbol information. If we find any, we set a
2688 // flag that tells the normal nlist parser to ignore all LOCAL symbols.
2689
2690 if (IsSharedCacheBinary()) {
2691 // Before we can start mapping the DSC, we need to make certain the
2692 // target process is actually using the cache we can find.
2693
2694 // Next we need to determine the correct path for the dyld shared cache.
2695
2696 ArchSpec header_arch = GetArchitecture();
2697
2698 UUID dsc_uuid;
2699 UUID process_shared_cache_uuid;
2700 addr_t process_shared_cache_base_addr;
2701
2702 if (process) {
2703 GetProcessSharedCacheUUID(process, process_shared_cache_base_addr,
2704 process_shared_cache_uuid);
2705 }
2706
2707 __block bool found_image = false;
2708 __block void *nlist_buffer = nullptr;
2709 __block unsigned nlist_count = 0;
2710 __block char *string_table = nullptr;
2711 __block vm_offset_t vm_nlist_memory = 0;
2712 __block mach_msg_type_number_t vm_nlist_bytes_read = 0;
2713 __block vm_offset_t vm_string_memory = 0;
2714 __block mach_msg_type_number_t vm_string_bytes_read = 0;
2715
2716 auto _ = llvm::make_scope_exit(^{
2717 if (vm_nlist_memory)
2718 vm_deallocate(mach_task_self(), vm_nlist_memory, vm_nlist_bytes_read);
2719 if (vm_string_memory)
2720 vm_deallocate(mach_task_self(), vm_string_memory, vm_string_bytes_read);
2721 });
2722
2723 typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
2724 typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
2725 UndefinedNameToDescMap undefined_name_to_desc;
2726 SymbolIndexToName reexport_shlib_needs_fixup;
2727
2728 dyld_for_each_installed_shared_cache(^(dyld_shared_cache_t shared_cache) {
2729 uuid_t cache_uuid;
2730 dyld_shared_cache_copy_uuid(shared_cache, &cache_uuid);
2731 if (found_image)
2732 return;
2733
2734 if (process_shared_cache_uuid.IsValid() &&
2735 process_shared_cache_uuid != UUID::fromData(&cache_uuid, 16))
2736 return;
2737
2738 dyld_shared_cache_for_each_image(shared_cache, ^(dyld_image_t image) {
2739 uuid_t dsc_image_uuid;
2740 if (found_image)
2741 return;
2742
2743 dyld_image_copy_uuid(image, &dsc_image_uuid);
2744 if (image_uuid != UUID::fromData(dsc_image_uuid, 16))
2745 return;
2746
2747 found_image = true;
2748
2749 // Compute the size of the string table. We need to ask dyld for a
2750 // new SPI to avoid this step.
2751 dyld_image_local_nlist_content_4Symbolication(
2752 image, ^(const void *nlistStart, uint64_t nlistCount,
2753 const char *stringTable) {
2754 if (!nlistStart || !nlistCount)
2755 return;
2756
2757 // The buffers passed here are valid only inside the block.
2758 // Use vm_read to make a cheap copy of them available for our
2759 // processing later.
2760 kern_return_t ret =
2761 vm_read(mach_task_self(), (vm_address_t)nlistStart,
2762 nlist_byte_size * nlistCount, &vm_nlist_memory,
2763 &vm_nlist_bytes_read);
2764 if (ret != KERN_SUCCESS)
2765 return;
2766 assert(vm_nlist_bytes_read == nlist_byte_size * nlistCount);
2767
2768 // We don't know the size of the string table. It's cheaper
2769 // to map the whole VM region than to determine the size by
2770 // parsing all the nlist entries.
2771 vm_address_t string_address = (vm_address_t)stringTable;
2772 vm_size_t region_size;
2773 mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT_64;
2774 vm_region_basic_info_data_t info;
2775 memory_object_name_t object;
2776 ret = vm_region_64(mach_task_self(), &string_address,
2777 &region_size, VM_REGION_BASIC_INFO_64,
2778 (vm_region_info_t)&info, &info_count, &object);
2779 if (ret != KERN_SUCCESS)
2780 return;
2781
2782 ret = vm_read(mach_task_self(), (vm_address_t)stringTable,
2783 region_size -
2784 ((vm_address_t)stringTable - string_address),
2785 &vm_string_memory, &vm_string_bytes_read);
2786 if (ret != KERN_SUCCESS)
2787 return;
2788
2789 nlist_buffer = (void *)vm_nlist_memory;
2790 string_table = (char *)vm_string_memory;
2791 nlist_count = nlistCount;
2792 });
2793 });
2794 });
2795 if (nlist_buffer) {
2796 DataExtractor dsc_local_symbols_data(nlist_buffer,
2797 nlist_count * nlist_byte_size,
2798 byte_order, addr_byte_size);
2799 unmapped_local_symbols_found = nlist_count;
2800
2801 // The normal nlist code cannot correctly size the Symbols
2802 // array, we need to allocate it here.
2803 sym = symtab.Resize(
2804 symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2805 unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2806 num_syms = symtab.GetNumSymbols();
2807
2808 lldb::offset_t nlist_data_offset = 0;
2809
2810 for (uint32_t nlist_index = 0;
2811 nlist_index < nlist_count;
2812 nlist_index++) {
2813 /////////////////////////////
2814 {
2815 std::optional<struct nlist_64> nlist_maybe =
2816 ParseNList(dsc_local_symbols_data, nlist_data_offset,
2817 nlist_byte_size);
2818 if (!nlist_maybe)
2819 break;
2820 struct nlist_64 nlist = *nlist_maybe;
2821
2822 SymbolType type = eSymbolTypeInvalid;
2823 const char *symbol_name = string_table + nlist.n_strx;
2824
2825 if (symbol_name == NULL) {
2826 // No symbol should be NULL, even the symbols with no
2827 // string values should have an offset zero which
2828 // points to an empty C-string
2829 Debugger::ReportError(llvm::formatv(
2830 "DSC unmapped local symbol[{0}] has invalid "
2831 "string table offset {1:x} in {2}, ignoring symbol",
2832 nlist_index, nlist.n_strx,
2833 module_sp->GetFileSpec().GetPath());
2834 continue;
2835 }
2836 if (symbol_name[0] == '\0')
2837 symbol_name = NULL;
2838
2839 const char *symbol_name_non_abi_mangled = NULL;
2840
2841 SectionSP symbol_section;
2842 uint32_t symbol_byte_size = 0;
2843 bool add_nlist = true;
2844 bool is_debug = ((nlist.n_type & N_STAB) != 0);
2845 bool demangled_is_synthesized = false;
2846 bool is_gsym = false;
2847 bool set_value = true;
2848
2849 assert(sym_idx < num_syms);
2850
2851 sym[sym_idx].SetDebug(is_debug);
2852
2853 if (is_debug) {
2854 switch (nlist.n_type) {
2855 case N_GSYM:
2856 // global symbol: name,,NO_SECT,type,0
2857 // Sometimes the N_GSYM value contains the address.
2858
2859 // FIXME: In the .o files, we have a GSYM and a debug
2860 // symbol for all the ObjC data. They
2861 // have the same address, but we want to ensure that
2862 // we always find only the real symbol, 'cause we
2863 // don't currently correctly attribute the
2864 // GSYM one to the ObjCClass/Ivar/MetaClass
2865 // symbol type. This is a temporary hack to make
2866 // sure the ObjectiveC symbols get treated correctly.
2867 // To do this right, we should coalesce all the GSYM
2868 // & global symbols that have the same address.
2869
2870 is_gsym = true;
2871 sym[sym_idx].SetExternal(true);
2872
2873 if (symbol_name && symbol_name[0] == '_' &&
2874 symbol_name[1] == 'O') {
2875 llvm::StringRef symbol_name_ref(symbol_name);
2876 if (symbol_name_ref.starts_with(
2877 g_objc_v2_prefix_class)) {
2878 symbol_name_non_abi_mangled = symbol_name + 1;
2879 symbol_name =
2880 symbol_name + g_objc_v2_prefix_class.size();
2881 type = eSymbolTypeObjCClass;
2882 demangled_is_synthesized = true;
2883
2884 } else if (symbol_name_ref.starts_with(
2885 g_objc_v2_prefix_metaclass)) {
2886 symbol_name_non_abi_mangled = symbol_name + 1;
2887 symbol_name =
2888 symbol_name + g_objc_v2_prefix_metaclass.size();
2889 type = eSymbolTypeObjCMetaClass;
2890 demangled_is_synthesized = true;
2891 } else if (symbol_name_ref.starts_with(
2892 g_objc_v2_prefix_ivar)) {
2893 symbol_name_non_abi_mangled = symbol_name + 1;
2894 symbol_name =
2895 symbol_name + g_objc_v2_prefix_ivar.size();
2896 type = eSymbolTypeObjCIVar;
2897 demangled_is_synthesized = true;
2898 }
2899 } else {
2900 if (nlist.n_value != 0)
2901 symbol_section = section_info.GetSection(
2902 nlist.n_sect, nlist.n_value);
2903 type = eSymbolTypeData;
2904 }
2905 break;
2906
2907 case N_FNAME:
2908 // procedure name (f77 kludge): name,,NO_SECT,0,0
2909 type = eSymbolTypeCompiler;
2910 break;
2911
2912 case N_FUN:
2913 // procedure: name,,n_sect,linenumber,address
2914 if (symbol_name) {
2915 type = eSymbolTypeCode;
2916 symbol_section = section_info.GetSection(
2917 nlist.n_sect, nlist.n_value);
2918
2919 N_FUN_addr_to_sym_idx.insert(
2920 std::make_pair(nlist.n_value, sym_idx));
2921 // We use the current number of symbols in the
2922 // symbol table in lieu of using nlist_idx in case
2923 // we ever start trimming entries out
2924 N_FUN_indexes.push_back(sym_idx);
2925 } else {
2926 type = eSymbolTypeCompiler;
2927
2928 if (!N_FUN_indexes.empty()) {
2929 // Copy the size of the function into the
2930 // original
2931 // STAB entry so we don't have
2932 // to hunt for it later
2933 symtab.SymbolAtIndex(N_FUN_indexes.back())
2934 ->SetByteSize(nlist.n_value);
2935 N_FUN_indexes.pop_back();
2936 // We don't really need the end function STAB as
2937 // it contains the size which we already placed
2938 // with the original symbol, so don't add it if
2939 // we want a minimal symbol table
2940 add_nlist = false;
2941 }
2942 }
2943 break;
2944
2945 case N_STSYM:
2946 // static symbol: name,,n_sect,type,address
2947 N_STSYM_addr_to_sym_idx.insert(
2948 std::make_pair(nlist.n_value, sym_idx));
2949 symbol_section = section_info.GetSection(nlist.n_sect,
2950 nlist.n_value);
2951 if (symbol_name && symbol_name[0]) {
2952 type = ObjectFile::GetSymbolTypeFromName(
2953 symbol_name + 1, eSymbolTypeData);
2954 }
2955 break;
2956
2957 case N_LCSYM:
2958 // .lcomm symbol: name,,n_sect,type,address
2959 symbol_section = section_info.GetSection(nlist.n_sect,
2960 nlist.n_value);
2961 type = eSymbolTypeCommonBlock;
2962 break;
2963
2964 case N_BNSYM:
2965 // We use the current number of symbols in the symbol
2966 // table in lieu of using nlist_idx in case we ever
2967 // start trimming entries out Skip these if we want
2968 // minimal symbol tables
2969 add_nlist = false;
2970 break;
2971
2972 case N_ENSYM:
2973 // Set the size of the N_BNSYM to the terminating
2974 // index of this N_ENSYM so that we can always skip
2975 // the entire symbol if we need to navigate more
2976 // quickly at the source level when parsing STABS
2977 // Skip these if we want minimal symbol tables
2978 add_nlist = false;
2979 break;
2980
2981 case N_OPT:
2982 // emitted with gcc2_compiled and in gcc source
2983 type = eSymbolTypeCompiler;
2984 break;
2985
2986 case N_RSYM:
2987 // register sym: name,,NO_SECT,type,register
2988 type = eSymbolTypeVariable;
2989 break;
2990
2991 case N_SLINE:
2992 // src line: 0,,n_sect,linenumber,address
2993 symbol_section = section_info.GetSection(nlist.n_sect,
2994 nlist.n_value);
2995 type = eSymbolTypeLineEntry;
2996 break;
2997
2998 case N_SSYM:
2999 // structure elt: name,,NO_SECT,type,struct_offset
3000 type = eSymbolTypeVariableType;
3001 break;
3002
3003 case N_SO:
3004 // source file name
3005 type = eSymbolTypeSourceFile;
3006 if (symbol_name == NULL) {
3007 add_nlist = false;
3008 if (N_SO_index != UINT32_MAX) {
3009 // Set the size of the N_SO to the terminating
3010 // index of this N_SO so that we can always skip
3011 // the entire N_SO if we need to navigate more
3012 // quickly at the source level when parsing STABS
3013 symbol_ptr = symtab.SymbolAtIndex(N_SO_index);
3014 symbol_ptr->SetByteSize(sym_idx);
3015 symbol_ptr->SetSizeIsSibling(true);
3016 }
3017 N_NSYM_indexes.clear();
3018 N_INCL_indexes.clear();
3019 N_BRAC_indexes.clear();
3020 N_COMM_indexes.clear();
3021 N_FUN_indexes.clear();
3022 N_SO_index = UINT32_MAX;
3023 } else {
3024 // We use the current number of symbols in the
3025 // symbol table in lieu of using nlist_idx in case
3026 // we ever start trimming entries out
3027 const bool N_SO_has_full_path = symbol_name[0] == '/';
3028 if (N_SO_has_full_path) {
3029 if ((N_SO_index == sym_idx - 1) &&
3030 ((sym_idx - 1) < num_syms)) {
3031 // We have two consecutive N_SO entries where
3032 // the first contains a directory and the
3033 // second contains a full path.
3034 sym[sym_idx - 1].GetMangled().SetValue(
3035 ConstString(symbol_name));
3036 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3037 add_nlist = false;
3038 } else {
3039 // This is the first entry in a N_SO that
3040 // contains a directory or
3041 // a full path to the source file
3042 N_SO_index = sym_idx;
3043 }
3044 } else if ((N_SO_index == sym_idx - 1) &&
3045 ((sym_idx - 1) < num_syms)) {
3046 // This is usually the second N_SO entry that
3047 // contains just the filename, so here we combine
3048 // it with the first one if we are minimizing the
3049 // symbol table
3050 const char *so_path = sym[sym_idx - 1]
3051 .GetMangled()
3052 .GetDemangledName()
3053 .AsCString();
3054 if (so_path && so_path[0]) {
3055 std::string full_so_path(so_path);
3056 const size_t double_slash_pos =
3057 full_so_path.find("//");
3058 if (double_slash_pos != std::string::npos) {
3059 // The linker has been generating bad N_SO
3060 // entries with doubled up paths
3061 // in the format "%s%s" where the first
3062 // string in the DW_AT_comp_dir, and the
3063 // second is the directory for the source
3064 // file so you end up with a path that looks
3065 // like "/tmp/src//tmp/src/"
3066 FileSpec so_dir(so_path);
3067 if (!FileSystem::Instance().Exists(so_dir)) {
3068 so_dir.SetFile(
3069 &full_so_path[double_slash_pos + 1],
3070 FileSpec::Style::native);
3071 if (FileSystem::Instance().Exists(so_dir)) {
3072 // Trim off the incorrect path
3073 full_so_path.erase(0, double_slash_pos + 1);
3074 }
3075 }
3076 }
3077 if (*full_so_path.rbegin() != '/')
3078 full_so_path += '/';
3079 full_so_path += symbol_name;
3080 sym[sym_idx - 1].GetMangled().SetValue(
3081 ConstString(full_so_path.c_str()));
3082 add_nlist = false;
3083 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3084 }
3085 } else {
3086 // This could be a relative path to a N_SO
3087 N_SO_index = sym_idx;
3088 }
3089 }
3090 break;
3091
3092 case N_OSO:
3093 // object file name: name,,0,0,st_mtime
3094 type = eSymbolTypeObjectFile;
3095 break;
3096
3097 case N_LSYM:
3098 // local sym: name,,NO_SECT,type,offset
3099 type = eSymbolTypeLocal;
3100 break;
3101
3102 // INCL scopes
3103 case N_BINCL:
3104 // include file beginning: name,,NO_SECT,0,sum We use
3105 // the current number of symbols in the symbol table
3106 // in lieu of using nlist_idx in case we ever start
3107 // trimming entries out
3108 N_INCL_indexes.push_back(sym_idx);
3109 type = eSymbolTypeScopeBegin;
3110 break;
3111
3112 case N_EINCL:
3113 // include file end: name,,NO_SECT,0,0
3114 // Set the size of the N_BINCL to the terminating
3115 // index of this N_EINCL so that we can always skip
3116 // the entire symbol if we need to navigate more
3117 // quickly at the source level when parsing STABS
3118 if (!N_INCL_indexes.empty()) {
3119 symbol_ptr =
3120 symtab.SymbolAtIndex(N_INCL_indexes.back());
3121 symbol_ptr->SetByteSize(sym_idx + 1);
3122 symbol_ptr->SetSizeIsSibling(true);
3123 N_INCL_indexes.pop_back();
3124 }
3125 type = eSymbolTypeScopeEnd;
3126 break;
3127
3128 case N_SOL:
3129 // #included file name: name,,n_sect,0,address
3130 type = eSymbolTypeHeaderFile;
3131
3132 // We currently don't use the header files on darwin
3133 add_nlist = false;
3134 break;
3135
3136 case N_PARAMS:
3137 // compiler parameters: name,,NO_SECT,0,0
3138 type = eSymbolTypeCompiler;
3139 break;
3140
3141 case N_VERSION:
3142 // compiler version: name,,NO_SECT,0,0
3143 type = eSymbolTypeCompiler;
3144 break;
3145
3146 case N_OLEVEL:
3147 // compiler -O level: name,,NO_SECT,0,0
3148 type = eSymbolTypeCompiler;
3149 break;
3150
3151 case N_PSYM:
3152 // parameter: name,,NO_SECT,type,offset
3153 type = eSymbolTypeVariable;
3154 break;
3155
3156 case N_ENTRY:
3157 // alternate entry: name,,n_sect,linenumber,address
3158 symbol_section = section_info.GetSection(nlist.n_sect,
3159 nlist.n_value);
3160 type = eSymbolTypeLineEntry;
3161 break;
3162
3163 // Left and Right Braces
3164 case N_LBRAC:
3165 // left bracket: 0,,NO_SECT,nesting level,address We
3166 // use the current number of symbols in the symbol
3167 // table in lieu of using nlist_idx in case we ever
3168 // start trimming entries out
3169 symbol_section = section_info.GetSection(nlist.n_sect,
3170 nlist.n_value);
3171 N_BRAC_indexes.push_back(sym_idx);
3172 type = eSymbolTypeScopeBegin;
3173 break;
3174
3175 case N_RBRAC:
3176 // right bracket: 0,,NO_SECT,nesting level,address
3177 // Set the size of the N_LBRAC to the terminating
3178 // index of this N_RBRAC so that we can always skip
3179 // the entire symbol if we need to navigate more
3180 // quickly at the source level when parsing STABS
3181 symbol_section = section_info.GetSection(nlist.n_sect,
3182 nlist.n_value);
3183 if (!N_BRAC_indexes.empty()) {
3184 symbol_ptr =
3185 symtab.SymbolAtIndex(N_BRAC_indexes.back());
3186 symbol_ptr->SetByteSize(sym_idx + 1);
3187 symbol_ptr->SetSizeIsSibling(true);
3188 N_BRAC_indexes.pop_back();
3189 }
3190 type = eSymbolTypeScopeEnd;
3191 break;
3192
3193 case N_EXCL:
3194 // deleted include file: name,,NO_SECT,0,sum
3195 type = eSymbolTypeHeaderFile;
3196 break;
3197
3198 // COMM scopes
3199 case N_BCOMM:
3200 // begin common: name,,NO_SECT,0,0
3201 // We use the current number of symbols in the symbol
3202 // table in lieu of using nlist_idx in case we ever
3203 // start trimming entries out
3204 type = eSymbolTypeScopeBegin;
3205 N_COMM_indexes.push_back(sym_idx);
3206 break;
3207
3208 case N_ECOML:
3209 // end common (local name): 0,,n_sect,0,address
3210 symbol_section = section_info.GetSection(nlist.n_sect,
3211 nlist.n_value);
3212 // Fall through
3213
3214 case N_ECOMM:
3215 // end common: name,,n_sect,0,0
3216 // Set the size of the N_BCOMM to the terminating
3217 // index of this N_ECOMM/N_ECOML so that we can
3218 // always skip the entire symbol if we need to
3219 // navigate more quickly at the source level when
3220 // parsing STABS
3221 if (!N_COMM_indexes.empty()) {
3222 symbol_ptr =
3223 symtab.SymbolAtIndex(N_COMM_indexes.back());
3224 symbol_ptr->SetByteSize(sym_idx + 1);
3225 symbol_ptr->SetSizeIsSibling(true);
3226 N_COMM_indexes.pop_back();
3227 }
3228 type = eSymbolTypeScopeEnd;
3229 break;
3230
3231 case N_LENG:
3232 // second stab entry with length information
3233 type = eSymbolTypeAdditional;
3234 break;
3235
3236 default:
3237 break;
3238 }
3239 } else {
3240 // uint8_t n_pext = N_PEXT & nlist.n_type;
3241 uint8_t n_type = N_TYPE & nlist.n_type;
3242 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
3243
3244 switch (n_type) {
3245 case N_INDR: {
3246 const char *reexport_name_cstr =
3247 strtab_data.PeekCStr(nlist.n_value);
3248 if (reexport_name_cstr && reexport_name_cstr[0]) {
3249 type = eSymbolTypeReExported;
3250 ConstString reexport_name(
3251 reexport_name_cstr +
3252 ((reexport_name_cstr[0] == '_') ? 1 : 0));
3253 sym[sym_idx].SetReExportedSymbolName(reexport_name);
3254 set_value = false;
3255 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3256 indirect_symbol_names.insert(ConstString(
3257 symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
3258 } else
3259 type = eSymbolTypeUndefined;
3260 } break;
3261
3262 case N_UNDF:
3263 if (symbol_name && symbol_name[0]) {
3264 ConstString undefined_name(
3265 symbol_name + ((symbol_name[0] == '_') ? 1 : 0));
3266 undefined_name_to_desc[undefined_name] = nlist.n_desc;
3267 }
3268 // Fall through
3269 case N_PBUD:
3270 type = eSymbolTypeUndefined;
3271 break;
3272
3273 case N_ABS:
3274 type = eSymbolTypeAbsolute;
3275 break;
3276
3277 case N_SECT: {
3278 symbol_section = section_info.GetSection(nlist.n_sect,
3279 nlist.n_value);
3280
3281 if (symbol_section == NULL) {
3282 // TODO: warn about this?
3283 add_nlist = false;
3284 break;
3285 }
3286
3287 if (TEXT_eh_frame_sectID == nlist.n_sect) {
3288 type = eSymbolTypeException;
3289 } else {
3290 uint32_t section_type =
3291 symbol_section->Get() & SECTION_TYPE;
3292
3293 switch (section_type) {
3294 case S_CSTRING_LITERALS:
3295 type = eSymbolTypeData;
3296 break; // section with only literal C strings
3297 case S_4BYTE_LITERALS:
3298 type = eSymbolTypeData;
3299 break; // section with only 4 byte literals
3300 case S_8BYTE_LITERALS:
3301 type = eSymbolTypeData;
3302 break; // section with only 8 byte literals
3303 case S_LITERAL_POINTERS:
3304 type = eSymbolTypeTrampoline;
3305 break; // section with only pointers to literals
3306 case S_NON_LAZY_SYMBOL_POINTERS:
3307 type = eSymbolTypeTrampoline;
3308 break; // section with only non-lazy symbol
3309 // pointers
3310 case S_LAZY_SYMBOL_POINTERS:
3311 type = eSymbolTypeTrampoline;
3312 break; // section with only lazy symbol pointers
3313 case S_SYMBOL_STUBS:
3314 type = eSymbolTypeTrampoline;
3315 break; // section with only symbol stubs, byte
3316 // size of stub in the reserved2 field
3317 case S_MOD_INIT_FUNC_POINTERS:
3318 type = eSymbolTypeCode;
3319 break; // section with only function pointers for
3320 // initialization
3321 case S_MOD_TERM_FUNC_POINTERS:
3322 type = eSymbolTypeCode;
3323 break; // section with only function pointers for
3324 // termination
3325 case S_INTERPOSING:
3326 type = eSymbolTypeTrampoline;
3327 break; // section with only pairs of function
3328 // pointers for interposing
3329 case S_16BYTE_LITERALS:
3330 type = eSymbolTypeData;
3331 break; // section with only 16 byte literals
3332 case S_DTRACE_DOF:
3333 type = eSymbolTypeInstrumentation;
3334 break;
3335 case S_LAZY_DYLIB_SYMBOL_POINTERS:
3336 type = eSymbolTypeTrampoline;
3337 break;
3338 default:
3339 switch (symbol_section->GetType()) {
3340 case lldb::eSectionTypeCode:
3341 type = eSymbolTypeCode;
3342 break;
3343 case eSectionTypeData:
3344 case eSectionTypeDataCString: // Inlined C string
3345 // data
3346 case eSectionTypeDataCStringPointers: // Pointers
3347 // to C
3348 // string
3349 // data
3350 case eSectionTypeDataSymbolAddress: // Address of
3351 // a symbol in
3352 // the symbol
3353 // table
3354 case eSectionTypeData4:
3355 case eSectionTypeData8:
3356 case eSectionTypeData16:
3357 type = eSymbolTypeData;
3358 break;
3359 default:
3360 break;
3361 }
3362 break;
3363 }
3364
3365 if (type == eSymbolTypeInvalid) {
3366 const char *symbol_sect_name =
3367 symbol_section->GetName().AsCString();
3368 if (symbol_section->IsDescendant(
3369 text_section_sp.get())) {
3370 if (symbol_section->IsClear(
3371 S_ATTR_PURE_INSTRUCTIONS |
3372 S_ATTR_SELF_MODIFYING_CODE |
3373 S_ATTR_SOME_INSTRUCTIONS))
3374 type = eSymbolTypeData;
3375 else
3376 type = eSymbolTypeCode;
3377 } else if (symbol_section->IsDescendant(
3378 data_section_sp.get()) ||
3379 symbol_section->IsDescendant(
3380 data_dirty_section_sp.get()) ||
3381 symbol_section->IsDescendant(
3382 data_const_section_sp.get())) {
3383 if (symbol_sect_name &&
3384 ::strstr(symbol_sect_name, "__objc") ==
3385 symbol_sect_name) {
3386 type = eSymbolTypeRuntime;
3387
3388 if (symbol_name) {
3389 llvm::StringRef symbol_name_ref(symbol_name);
3390 if (symbol_name_ref.starts_with("_OBJC_")) {
3391 llvm::StringRef
3392 g_objc_v2_prefix_class(
3393 "_OBJC_CLASS_$_");
3394 llvm::StringRef
3395 g_objc_v2_prefix_metaclass(
3396 "_OBJC_METACLASS_$_");
3397 llvm::StringRef
3398 g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
3399 if (symbol_name_ref.starts_with(
3400 g_objc_v2_prefix_class)) {
3401 symbol_name_non_abi_mangled =
3402 symbol_name + 1;
3403 symbol_name =
3404 symbol_name +
3405 g_objc_v2_prefix_class.size();
3406 type = eSymbolTypeObjCClass;
3407 demangled_is_synthesized = true;
3408 } else if (
3409 symbol_name_ref.starts_with(
3410 g_objc_v2_prefix_metaclass)) {
3411 symbol_name_non_abi_mangled =
3412 symbol_name + 1;
3413 symbol_name =
3414 symbol_name +
3415 g_objc_v2_prefix_metaclass.size();
3416 type = eSymbolTypeObjCMetaClass;
3417 demangled_is_synthesized = true;
3418 } else if (symbol_name_ref.starts_with(
3419 g_objc_v2_prefix_ivar)) {
3420 symbol_name_non_abi_mangled =
3421 symbol_name + 1;
3422 symbol_name =
3423 symbol_name +
3424 g_objc_v2_prefix_ivar.size();
3425 type = eSymbolTypeObjCIVar;
3426 demangled_is_synthesized = true;
3427 }
3428 }
3429 }
3430 } else if (symbol_sect_name &&
3431 ::strstr(symbol_sect_name,
3432 "__gcc_except_tab") ==
3433 symbol_sect_name) {
3434 type = eSymbolTypeException;
3435 } else {
3436 type = eSymbolTypeData;
3437 }
3438 } else if (symbol_sect_name &&
3439 ::strstr(symbol_sect_name, "__IMPORT") ==
3440 symbol_sect_name) {
3441 type = eSymbolTypeTrampoline;
3442 } else if (symbol_section->IsDescendant(
3443 objc_section_sp.get())) {
3444 type = eSymbolTypeRuntime;
3445 if (symbol_name && symbol_name[0] == '.') {
3446 llvm::StringRef symbol_name_ref(symbol_name);
3447 llvm::StringRef
3448 g_objc_v1_prefix_class(".objc_class_name_");
3449 if (symbol_name_ref.starts_with(
3450 g_objc_v1_prefix_class)) {
3451 symbol_name_non_abi_mangled = symbol_name;
3452 symbol_name = symbol_name +
3453 g_objc_v1_prefix_class.size();
3454 type = eSymbolTypeObjCClass;
3455 demangled_is_synthesized = true;
3456 }
3457 }
3458 }
3459 }
3460 }
3461 } break;
3462 }
3463 }
3464
3465 if (add_nlist) {
3466 uint64_t symbol_value = nlist.n_value;
3467 if (symbol_name_non_abi_mangled) {
3468 sym[sym_idx].GetMangled().SetMangledName(
3469 ConstString(symbol_name_non_abi_mangled));
3470 sym[sym_idx].GetMangled().SetDemangledName(
3471 ConstString(symbol_name));
3472 } else {
3473 if (symbol_name && symbol_name[0] == '_') {
3474 symbol_name++; // Skip the leading underscore
3475 }
3476
3477 if (symbol_name) {
3478 ConstString const_symbol_name(symbol_name);
3479 sym[sym_idx].GetMangled().SetValue(const_symbol_name);
3480 if (is_gsym && is_debug) {
3481 const char *gsym_name =
3482 sym[sym_idx]
3483 .GetMangled()
3484 .GetName(Mangled::ePreferMangled)
3485 .GetCString();
3486 if (gsym_name)
3487 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3488 }
3489 }
3490 }
3491 if (symbol_section) {
3492 const addr_t section_file_addr =
3493 symbol_section->GetFileAddress();
3494 if (symbol_byte_size == 0 &&
3495 function_starts_count > 0) {
3496 addr_t symbol_lookup_file_addr = nlist.n_value;
3497 // Do an exact address match for non-ARM addresses,
3498 // else get the closest since the symbol might be a
3499 // thumb symbol which has an address with bit zero
3500 // set
3501 FunctionStarts::Entry *func_start_entry =
3502 function_starts.FindEntry(symbol_lookup_file_addr,
3503 !is_arm);
3504 if (is_arm && func_start_entry) {
3505 // Verify that the function start address is the
3506 // symbol address (ARM) or the symbol address + 1
3507 // (thumb)
3508 if (func_start_entry->addr !=
3509 symbol_lookup_file_addr &&
3510 func_start_entry->addr !=
3511 (symbol_lookup_file_addr + 1)) {
3512 // Not the right entry, NULL it out...
3513 func_start_entry = NULL;
3514 }
3515 }
3516 if (func_start_entry) {
3517 func_start_entry->data = true;
3518
3519 addr_t symbol_file_addr = func_start_entry->addr;
3520 uint32_t symbol_flags = 0;
3521 if (is_arm) {
3522 if (symbol_file_addr & 1)
3523 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3524 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3525 }
3526
3527 const FunctionStarts::Entry *next_func_start_entry =
3528 function_starts.FindNextEntry(func_start_entry);
3529 const addr_t section_end_file_addr =
3530 section_file_addr +
3531 symbol_section->GetByteSize();
3532 if (next_func_start_entry) {
3533 addr_t next_symbol_file_addr =
3534 next_func_start_entry->addr;
3535 // Be sure the clear the Thumb address bit when
3536 // we calculate the size from the current and
3537 // next address
3538 if (is_arm)
3539 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3540 symbol_byte_size = std::min<lldb::addr_t>(
3541 next_symbol_file_addr - symbol_file_addr,
3542 section_end_file_addr - symbol_file_addr);
3543 } else {
3544 symbol_byte_size =
3545 section_end_file_addr - symbol_file_addr;
3546 }
3547 }
3548 }
3549 symbol_value -= section_file_addr;
3550 }
3551
3552 if (is_debug == false) {
3553 if (type == eSymbolTypeCode) {
3554 // See if we can find a N_FUN entry for any code
3555 // symbols. If we do find a match, and the name
3556 // matches, then we can merge the two into just the
3557 // function symbol to avoid duplicate entries in
3558 // the symbol table
3559 auto range =
3560 N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
3561 if (range.first != range.second) {
3562 bool found_it = false;
3563 for (auto pos = range.first; pos != range.second;
3564 ++pos) {
3565 if (sym[sym_idx].GetMangled().GetName(
3566 Mangled::ePreferMangled) ==
3567 sym[pos->second].GetMangled().GetName(
3568 Mangled::ePreferMangled)) {
3569 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3570 // We just need the flags from the linker
3571 // symbol, so put these flags
3572 // into the N_FUN flags to avoid duplicate
3573 // symbols in the symbol table
3574 sym[pos->second].SetExternal(
3575 sym[sym_idx].IsExternal());
3576 sym[pos->second].SetFlags(nlist.n_type << 16 |
3577 nlist.n_desc);
3578 if (resolver_addresses.find(nlist.n_value) !=
3579 resolver_addresses.end())
3580 sym[pos->second].SetType(eSymbolTypeResolver);
3581 sym[sym_idx].Clear();
3582 found_it = true;
3583 break;
3584 }
3585 }
3586 if (found_it)
3587 continue;
3588 } else {
3589 if (resolver_addresses.find(nlist.n_value) !=
3590 resolver_addresses.end())
3591 type = eSymbolTypeResolver;
3592 }
3593 } else if (type == eSymbolTypeData ||
3594 type == eSymbolTypeObjCClass ||
3595 type == eSymbolTypeObjCMetaClass ||
3596 type == eSymbolTypeObjCIVar) {
3597 // See if we can find a N_STSYM entry for any data
3598 // symbols. If we do find a match, and the name
3599 // matches, then we can merge the two into just the
3600 // Static symbol to avoid duplicate entries in the
3601 // symbol table
3602 auto range = N_STSYM_addr_to_sym_idx.equal_range(
3603 nlist.n_value);
3604 if (range.first != range.second) {
3605 bool found_it = false;
3606 for (auto pos = range.first; pos != range.second;
3607 ++pos) {
3608 if (sym[sym_idx].GetMangled().GetName(
3609 Mangled::ePreferMangled) ==
3610 sym[pos->second].GetMangled().GetName(
3611 Mangled::ePreferMangled)) {
3612 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3613 // We just need the flags from the linker
3614 // symbol, so put these flags
3615 // into the N_STSYM flags to avoid duplicate
3616 // symbols in the symbol table
3617 sym[pos->second].SetExternal(
3618 sym[sym_idx].IsExternal());
3619 sym[pos->second].SetFlags(nlist.n_type << 16 |
3620 nlist.n_desc);
3621 sym[sym_idx].Clear();
3622 found_it = true;
3623 break;
3624 }
3625 }
3626 if (found_it)
3627 continue;
3628 } else {
3629 const char *gsym_name =
3630 sym[sym_idx]
3631 .GetMangled()
3632 .GetName(Mangled::ePreferMangled)
3633 .GetCString();
3634 if (gsym_name) {
3635 // Combine N_GSYM stab entries with the non
3636 // stab symbol
3637 ConstNameToSymbolIndexMap::const_iterator pos =
3638 N_GSYM_name_to_sym_idx.find(gsym_name);
3639 if (pos != N_GSYM_name_to_sym_idx.end()) {
3640 const uint32_t GSYM_sym_idx = pos->second;
3641 m_nlist_idx_to_sym_idx[nlist_idx] =
3642 GSYM_sym_idx;
3643 // Copy the address, because often the N_GSYM
3644 // address has an invalid address of zero
3645 // when the global is a common symbol
3646 sym[GSYM_sym_idx].GetAddressRef().SetSection(
3647 symbol_section);
3648 sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3649 symbol_value);
3650 add_symbol_addr(sym[GSYM_sym_idx]
3651 .GetAddress()
3652 .GetFileAddress());
3653 // We just need the flags from the linker
3654 // symbol, so put these flags
3655 // into the N_GSYM flags to avoid duplicate
3656 // symbols in the symbol table
3657 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
3658 nlist.n_desc);
3659 sym[sym_idx].Clear();
3660 continue;
3661 }
3662 }
3663 }
3664 }
3665 }
3666
3667 sym[sym_idx].SetID(nlist_idx);
3668 sym[sym_idx].SetType(type);
3669 if (set_value) {
3670 sym[sym_idx].GetAddressRef().SetSection(symbol_section);
3671 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
3672 add_symbol_addr(
3673 sym[sym_idx].GetAddress().GetFileAddress());
3674 }
3675 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
3676
3677 if (symbol_byte_size > 0)
3678 sym[sym_idx].SetByteSize(symbol_byte_size);
3679
3680 if (demangled_is_synthesized)
3681 sym[sym_idx].SetDemangledNameIsSynthesized(true);
3682 ++sym_idx;
3683 } else {
3684 sym[sym_idx].Clear();
3685 }
3686 }
3687 /////////////////////////////
3688 }
3689 }
3690
3691 for (const auto &pos : reexport_shlib_needs_fixup) {
3692 const auto undef_pos = undefined_name_to_desc.find(pos.second);
3693 if (undef_pos != undefined_name_to_desc.end()) {
3694 const uint8_t dylib_ordinal =
3695 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3696 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
3697 sym[pos.first].SetReExportedSymbolSharedLibrary(
3698 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3699 }
3700 }
3701 }
3702
3703#endif
3704 lldb::offset_t nlist_data_offset = 0;
3705
3706 if (nlist_data.GetByteSize() > 0) {
3707
3708 // If the sym array was not created while parsing the DSC unmapped
3709 // symbols, create it now.
3710 if (sym == nullptr) {
3711 sym =
3712 symtab.Resize(count: symtab_load_command.nsyms + m_dysymtab.nindirectsyms);
3713 num_syms = symtab.GetNumSymbols();
3714 }
3715
3716 if (unmapped_local_symbols_found) {
3717 assert(m_dysymtab.ilocalsym == 0);
3718 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3719 nlist_idx = m_dysymtab.nlocalsym;
3720 } else {
3721 nlist_idx = 0;
3722 }
3723
3724 typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
3725 typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
3726 UndefinedNameToDescMap undefined_name_to_desc;
3727 SymbolIndexToName reexport_shlib_needs_fixup;
3728
3729 // Symtab parsing is a huge mess. Everything is entangled and the code
3730 // requires access to a ridiculous amount of variables. LLDB depends
3731 // heavily on the proper merging of symbols and to get that right we need
3732 // to make sure we have parsed all the debug symbols first. Therefore we
3733 // invoke the lambda twice, once to parse only the debug symbols and then
3734 // once more to parse the remaining symbols.
3735 auto ParseSymbolLambda = [&](struct nlist_64 &nlist, uint32_t nlist_idx,
3736 bool debug_only) {
3737 const bool is_debug = ((nlist.n_type & N_STAB) != 0);
3738 if (is_debug != debug_only)
3739 return true;
3740
3741 const char *symbol_name_non_abi_mangled = nullptr;
3742 const char *symbol_name = nullptr;
3743
3744 if (have_strtab_data) {
3745 symbol_name = strtab_data.PeekCStr(offset: nlist.n_strx);
3746
3747 if (symbol_name == nullptr) {
3748 // No symbol should be NULL, even the symbols with no string values
3749 // should have an offset zero which points to an empty C-string
3750 Debugger::ReportError(message: llvm::formatv(
3751 Fmt: "symbol[{0}] has invalid string table offset {1:x} in {2}, "
3752 "ignoring symbol",
3753 Vals&: nlist_idx, Vals&: nlist.n_strx, Vals: module_sp->GetFileSpec().GetPath()));
3754 return true;
3755 }
3756 if (symbol_name[0] == '\0')
3757 symbol_name = nullptr;
3758 } else {
3759 const addr_t str_addr = strtab_addr + nlist.n_strx;
3760 Status str_error;
3761 if (process->ReadCStringFromMemory(vm_addr: str_addr, out_str&: memory_symbol_name,
3762 error&: str_error))
3763 symbol_name = memory_symbol_name.c_str();
3764 }
3765
3766 SymbolType type = eSymbolTypeInvalid;
3767 SectionSP symbol_section;
3768 lldb::addr_t symbol_byte_size = 0;
3769 bool add_nlist = true;
3770 bool is_gsym = false;
3771 bool demangled_is_synthesized = false;
3772 bool set_value = true;
3773
3774 assert(sym_idx < num_syms);
3775 sym[sym_idx].SetDebug(is_debug);
3776
3777 if (is_debug) {
3778 switch (nlist.n_type) {
3779 case N_GSYM:
3780 // global symbol: name,,NO_SECT,type,0
3781 // Sometimes the N_GSYM value contains the address.
3782
3783 // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3784 // the ObjC data. They
3785 // have the same address, but we want to ensure that we always find
3786 // only the real symbol, 'cause we don't currently correctly
3787 // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3788 // type. This is a temporary hack to make sure the ObjectiveC
3789 // symbols get treated correctly. To do this right, we should
3790 // coalesce all the GSYM & global symbols that have the same
3791 // address.
3792 is_gsym = true;
3793 sym[sym_idx].SetExternal(true);
3794
3795 if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3796 llvm::StringRef symbol_name_ref(symbol_name);
3797 if (symbol_name_ref.starts_with(Prefix: g_objc_v2_prefix_class)) {
3798 symbol_name_non_abi_mangled = symbol_name + 1;
3799 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3800 type = eSymbolTypeObjCClass;
3801 demangled_is_synthesized = true;
3802
3803 } else if (symbol_name_ref.starts_with(
3804 Prefix: g_objc_v2_prefix_metaclass)) {
3805 symbol_name_non_abi_mangled = symbol_name + 1;
3806 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3807 type = eSymbolTypeObjCMetaClass;
3808 demangled_is_synthesized = true;
3809 } else if (symbol_name_ref.starts_with(Prefix: g_objc_v2_prefix_ivar)) {
3810 symbol_name_non_abi_mangled = symbol_name + 1;
3811 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3812 type = eSymbolTypeObjCIVar;
3813 demangled_is_synthesized = true;
3814 }
3815 } else {
3816 if (nlist.n_value != 0)
3817 symbol_section =
3818 section_info.GetSection(n_sect: nlist.n_sect, file_addr: nlist.n_value);
3819 type = eSymbolTypeData;
3820 }
3821 break;
3822
3823 case N_FNAME:
3824 // procedure name (f77 kludge): name,,NO_SECT,0,0
3825 type = eSymbolTypeCompiler;
3826 break;
3827
3828 case N_FUN:
3829 // procedure: name,,n_sect,linenumber,address
3830 if (symbol_name) {
3831 type = eSymbolTypeCode;
3832 symbol_section =
3833 section_info.GetSection(n_sect: nlist.n_sect, file_addr: nlist.n_value);
3834
3835 N_FUN_addr_to_sym_idx.insert(
3836 x: std::make_pair(x&: nlist.n_value, y&: sym_idx));
3837 // We use the current number of symbols in the symbol table in
3838 // lieu of using nlist_idx in case we ever start trimming entries
3839 // out
3840 N_FUN_indexes.push_back(x: sym_idx);
3841 } else {
3842 type = eSymbolTypeCompiler;
3843
3844 if (!N_FUN_indexes.empty()) {
3845 // Copy the size of the function into the original STAB entry
3846 // so we don't have to hunt for it later
3847 symtab.SymbolAtIndex(idx: N_FUN_indexes.back())
3848 ->SetByteSize(nlist.n_value);
3849 N_FUN_indexes.pop_back();
3850 // We don't really need the end function STAB as it contains
3851 // the size which we already placed with the original symbol,
3852 // so don't add it if we want a minimal symbol table
3853 add_nlist = false;
3854 }
3855 }
3856 break;
3857
3858 case N_STSYM:
3859 // static symbol: name,,n_sect,type,address
3860 N_STSYM_addr_to_sym_idx.insert(
3861 x: std::make_pair(x&: nlist.n_value, y&: sym_idx));
3862 symbol_section = section_info.GetSection(n_sect: nlist.n_sect, file_addr: nlist.n_value);
3863 if (symbol_name && symbol_name[0]) {
3864 type = ObjectFile::GetSymbolTypeFromName(name: symbol_name + 1,
3865 symbol_type_hint: eSymbolTypeData);
3866 }
3867 break;
3868
3869 case N_LCSYM:
3870 // .lcomm symbol: name,,n_sect,type,address
3871 symbol_section = section_info.GetSection(n_sect: nlist.n_sect, file_addr: nlist.n_value);
3872 type = eSymbolTypeCommonBlock;
3873 break;
3874
3875 case N_BNSYM:
3876 // We use the current number of symbols in the symbol table in lieu
3877 // of using nlist_idx in case we ever start trimming entries out
3878 // Skip these if we want minimal symbol tables
3879 add_nlist = false;
3880 break;
3881
3882 case N_ENSYM:
3883 // Set the size of the N_BNSYM to the terminating index of this
3884 // N_ENSYM so that we can always skip the entire symbol if we need
3885 // to navigate more quickly at the source level when parsing STABS
3886 // Skip these if we want minimal symbol tables
3887 add_nlist = false;
3888 break;
3889
3890 case N_OPT:
3891 // emitted with gcc2_compiled and in gcc source
3892 type = eSymbolTypeCompiler;
3893 break;
3894
3895 case N_RSYM:
3896 // register sym: name,,NO_SECT,type,register
3897 type = eSymbolTypeVariable;
3898 break;
3899
3900 case N_SLINE:
3901 // src line: 0,,n_sect,linenumber,address
3902 symbol_section = section_info.GetSection(n_sect: nlist.n_sect, file_addr: nlist.n_value);
3903 type = eSymbolTypeLineEntry;
3904 break;
3905
3906 case N_SSYM:
3907 // structure elt: name,,NO_SECT,type,struct_offset
3908 type = eSymbolTypeVariableType;
3909 break;
3910
3911 case N_SO:
3912 // source file name
3913 type = eSymbolTypeSourceFile;
3914 if (symbol_name == nullptr) {
3915 add_nlist = false;
3916 if (N_SO_index != UINT32_MAX) {
3917 // Set the size of the N_SO to the terminating index of this
3918 // N_SO so that we can always skip the entire N_SO if we need
3919 // to navigate more quickly at the source level when parsing
3920 // STABS
3921 symbol_ptr = symtab.SymbolAtIndex(idx: N_SO_index);
3922 symbol_ptr->SetByteSize(sym_idx);
3923 symbol_ptr->SetSizeIsSibling(true);
3924 }
3925 N_NSYM_indexes.clear();
3926 N_INCL_indexes.clear();
3927 N_BRAC_indexes.clear();
3928 N_COMM_indexes.clear();
3929 N_FUN_indexes.clear();
3930 N_SO_index = UINT32_MAX;
3931 } else {
3932 // We use the current number of symbols in the symbol table in
3933 // lieu of using nlist_idx in case we ever start trimming entries
3934 // out
3935 const bool N_SO_has_full_path = symbol_name[0] == '/';
3936 if (N_SO_has_full_path) {
3937 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3938 // We have two consecutive N_SO entries where the first
3939 // contains a directory and the second contains a full path.
3940 sym[sym_idx - 1].GetMangled().SetValue(
3941 ConstString(symbol_name));
3942 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3943 add_nlist = false;
3944 } else {
3945 // This is the first entry in a N_SO that contains a
3946 // directory or a full path to the source file
3947 N_SO_index = sym_idx;
3948 }
3949 } else if ((N_SO_index == sym_idx - 1) &&
3950 ((sym_idx - 1) < num_syms)) {
3951 // This is usually the second N_SO entry that contains just the
3952 // filename, so here we combine it with the first one if we are
3953 // minimizing the symbol table
3954 const char *so_path =
3955 sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString();
3956 if (so_path && so_path[0]) {
3957 std::string full_so_path(so_path);
3958 const size_t double_slash_pos = full_so_path.find(s: "//");
3959 if (double_slash_pos != std::string::npos) {
3960 // The linker has been generating bad N_SO entries with
3961 // doubled up paths in the format "%s%s" where the first
3962 // string in the DW_AT_comp_dir, and the second is the
3963 // directory for the source file so you end up with a path
3964 // that looks like "/tmp/src//tmp/src/"
3965 FileSpec so_dir(so_path);
3966 if (!FileSystem::Instance().Exists(file_spec: so_dir)) {
3967 so_dir.SetFile(path: &full_so_path[double_slash_pos + 1],
3968 style: FileSpec::Style::native);
3969 if (FileSystem::Instance().Exists(file_spec: so_dir)) {
3970 // Trim off the incorrect path
3971 full_so_path.erase(pos: 0, n: double_slash_pos + 1);
3972 }
3973 }
3974 }
3975 if (*full_so_path.rbegin() != '/')
3976 full_so_path += '/';
3977 full_so_path += symbol_name;
3978 sym[sym_idx - 1].GetMangled().SetValue(
3979 ConstString(full_so_path.c_str()));
3980 add_nlist = false;
3981 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3982 }
3983 } else {
3984 // This could be a relative path to a N_SO
3985 N_SO_index = sym_idx;
3986 }
3987 }
3988 break;
3989
3990 case N_OSO:
3991 // object file name: name,,0,0,st_mtime
3992 type = eSymbolTypeObjectFile;
3993 break;
3994
3995 case N_LSYM:
3996 // local sym: name,,NO_SECT,type,offset
3997 type = eSymbolTypeLocal;
3998 break;
3999
4000 // INCL scopes
4001 case N_BINCL:
4002 // include file beginning: name,,NO_SECT,0,sum We use the current
4003 // number of symbols in the symbol table in lieu of using nlist_idx
4004 // in case we ever start trimming entries out
4005 N_INCL_indexes.push_back(x: sym_idx);
4006 type = eSymbolTypeScopeBegin;
4007 break;
4008
4009 case N_EINCL:
4010 // include file end: name,,NO_SECT,0,0
4011 // Set the size of the N_BINCL to the terminating index of this
4012 // N_EINCL so that we can always skip the entire symbol if we need
4013 // to navigate more quickly at the source level when parsing STABS
4014 if (!N_INCL_indexes.empty()) {
4015 symbol_ptr = symtab.SymbolAtIndex(idx: N_INCL_indexes.back());
4016 symbol_ptr->SetByteSize(sym_idx + 1);
4017 symbol_ptr->SetSizeIsSibling(true);
4018 N_INCL_indexes.pop_back();
4019 }
4020 type = eSymbolTypeScopeEnd;
4021 break;
4022
4023 case N_SOL:
4024 // #included file name: name,,n_sect,0,address
4025 type = eSymbolTypeHeaderFile;
4026
4027 // We currently don't use the header files on darwin
4028 add_nlist = false;
4029 break;
4030
4031 case N_PARAMS:
4032 // compiler parameters: name,,NO_SECT,0,0
4033 type = eSymbolTypeCompiler;
4034 break;
4035
4036 case N_VERSION:
4037 // compiler version: name,,NO_SECT,0,0
4038 type = eSymbolTypeCompiler;
4039 break;
4040
4041 case N_OLEVEL:
4042 // compiler -O level: name,,NO_SECT,0,0
4043 type = eSymbolTypeCompiler;
4044 break;
4045
4046 case N_PSYM:
4047 // parameter: name,,NO_SECT,type,offset
4048 type = eSymbolTypeVariable;
4049 break;
4050
4051 case N_ENTRY:
4052 // alternate entry: name,,n_sect,linenumber,address
4053 symbol_section = section_info.GetSection(n_sect: nlist.n_sect, file_addr: nlist.n_value);
4054 type = eSymbolTypeLineEntry;
4055 break;
4056
4057 // Left and Right Braces
4058 case N_LBRAC:
4059 // left bracket: 0,,NO_SECT,nesting level,address We use the
4060 // current number of symbols in the symbol table in lieu of using
4061 // nlist_idx in case we ever start trimming entries out
4062 symbol_section = section_info.GetSection(n_sect: nlist.n_sect, file_addr: nlist.n_value);
4063 N_BRAC_indexes.push_back(x: sym_idx);
4064 type = eSymbolTypeScopeBegin;
4065 break;
4066
4067 case N_RBRAC:
4068 // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4069 // the N_LBRAC to the terminating index of this N_RBRAC so that we
4070 // can always skip the entire symbol if we need to navigate more
4071 // quickly at the source level when parsing STABS
4072 symbol_section = section_info.GetSection(n_sect: nlist.n_sect, file_addr: nlist.n_value);
4073 if (!N_BRAC_indexes.empty()) {
4074 symbol_ptr = symtab.SymbolAtIndex(idx: N_BRAC_indexes.back());
4075 symbol_ptr->SetByteSize(sym_idx + 1);
4076 symbol_ptr->SetSizeIsSibling(true);
4077 N_BRAC_indexes.pop_back();
4078 }
4079 type = eSymbolTypeScopeEnd;
4080 break;
4081
4082 case N_EXCL:
4083 // deleted include file: name,,NO_SECT,0,sum
4084 type = eSymbolTypeHeaderFile;
4085 break;
4086
4087 // COMM scopes
4088 case N_BCOMM:
4089 // begin common: name,,NO_SECT,0,0
4090 // We use the current number of symbols in the symbol table in lieu
4091 // of using nlist_idx in case we ever start trimming entries out
4092 type = eSymbolTypeScopeBegin;
4093 N_COMM_indexes.push_back(x: sym_idx);
4094 break;
4095
4096 case N_ECOML:
4097 // end common (local name): 0,,n_sect,0,address
4098 symbol_section = section_info.GetSection(n_sect: nlist.n_sect, file_addr: nlist.n_value);
4099 [[fallthrough]];
4100
4101 case N_ECOMM:
4102 // end common: name,,n_sect,0,0
4103 // Set the size of the N_BCOMM to the terminating index of this
4104 // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4105 // we need to navigate more quickly at the source level when
4106 // parsing STABS
4107 if (!N_COMM_indexes.empty()) {
4108 symbol_ptr = symtab.SymbolAtIndex(idx: N_COMM_indexes.back());
4109 symbol_ptr->SetByteSize(sym_idx + 1);
4110 symbol_ptr->SetSizeIsSibling(true);
4111 N_COMM_indexes.pop_back();
4112 }
4113 type = eSymbolTypeScopeEnd;
4114 break;
4115
4116 case N_LENG:
4117 // second stab entry with length information
4118 type = eSymbolTypeAdditional;
4119 break;
4120
4121 default:
4122 break;
4123 }
4124 } else {
4125 uint8_t n_type = N_TYPE & nlist.n_type;
4126 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4127
4128 switch (n_type) {
4129 case N_INDR: {
4130 const char *reexport_name_cstr = strtab_data.PeekCStr(offset: nlist.n_value);
4131 if (reexport_name_cstr && reexport_name_cstr[0] && symbol_name) {
4132 type = eSymbolTypeReExported;
4133 ConstString reexport_name(reexport_name_cstr +
4134 ((reexport_name_cstr[0] == '_') ? 1 : 0));
4135 sym[sym_idx].SetReExportedSymbolName(reexport_name);
4136 set_value = false;
4137 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4138 indirect_symbol_names.insert(
4139 x: ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4140 } else
4141 type = eSymbolTypeUndefined;
4142 } break;
4143
4144 case N_UNDF:
4145 if (symbol_name && symbol_name[0]) {
4146 ConstString undefined_name(symbol_name +
4147 ((symbol_name[0] == '_') ? 1 : 0));
4148 undefined_name_to_desc[undefined_name] = nlist.n_desc;
4149 }
4150 [[fallthrough]];
4151
4152 case N_PBUD:
4153 type = eSymbolTypeUndefined;
4154 break;
4155
4156 case N_ABS:
4157 type = eSymbolTypeAbsolute;
4158 break;
4159
4160 case N_SECT: {
4161 symbol_section = section_info.GetSection(n_sect: nlist.n_sect, file_addr: nlist.n_value);
4162
4163 if (!symbol_section) {
4164 // TODO: warn about this?
4165 add_nlist = false;
4166 break;
4167 }
4168
4169 if (TEXT_eh_frame_sectID == nlist.n_sect) {
4170 type = eSymbolTypeException;
4171 } else {
4172 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4173
4174 switch (section_type) {
4175 case S_CSTRING_LITERALS:
4176 type = eSymbolTypeData;
4177 break; // section with only literal C strings
4178 case S_4BYTE_LITERALS:
4179 type = eSymbolTypeData;
4180 break; // section with only 4 byte literals
4181 case S_8BYTE_LITERALS:
4182 type = eSymbolTypeData;
4183 break; // section with only 8 byte literals
4184 case S_LITERAL_POINTERS:
4185 type = eSymbolTypeTrampoline;
4186 break; // section with only pointers to literals
4187 case S_NON_LAZY_SYMBOL_POINTERS:
4188 type = eSymbolTypeTrampoline;
4189 break; // section with only non-lazy symbol pointers
4190 case S_LAZY_SYMBOL_POINTERS:
4191 type = eSymbolTypeTrampoline;
4192 break; // section with only lazy symbol pointers
4193 case S_SYMBOL_STUBS:
4194 type = eSymbolTypeTrampoline;
4195 break; // section with only symbol stubs, byte size of stub in
4196 // the reserved2 field
4197 case S_MOD_INIT_FUNC_POINTERS:
4198 type = eSymbolTypeCode;
4199 break; // section with only function pointers for initialization
4200 case S_MOD_TERM_FUNC_POINTERS:
4201 type = eSymbolTypeCode;
4202 break; // section with only function pointers for termination
4203 case S_INTERPOSING:
4204 type = eSymbolTypeTrampoline;
4205 break; // section with only pairs of function pointers for
4206 // interposing
4207 case S_16BYTE_LITERALS:
4208 type = eSymbolTypeData;
4209 break; // section with only 16 byte literals
4210 case S_DTRACE_DOF:
4211 type = eSymbolTypeInstrumentation;
4212 break;
4213 case S_LAZY_DYLIB_SYMBOL_POINTERS:
4214 type = eSymbolTypeTrampoline;
4215 break;
4216 default:
4217 switch (symbol_section->GetType()) {
4218 case lldb::eSectionTypeCode:
4219 type = eSymbolTypeCode;
4220 break;
4221 case eSectionTypeData:
4222 case eSectionTypeDataCString: // Inlined C string data
4223 case eSectionTypeDataCStringPointers: // Pointers to C string
4224 // data
4225 case eSectionTypeDataSymbolAddress: // Address of a symbol in
4226 // the symbol table
4227 case eSectionTypeData4:
4228 case eSectionTypeData8:
4229 case eSectionTypeData16:
4230 type = eSymbolTypeData;
4231 break;
4232 default:
4233 break;
4234 }
4235 break;
4236 }
4237
4238 if (type == eSymbolTypeInvalid) {
4239 const char *symbol_sect_name =
4240 symbol_section->GetName().AsCString();
4241 if (symbol_section->IsDescendant(section: text_section_sp.get())) {
4242 if (symbol_section->IsClear(bit: S_ATTR_PURE_INSTRUCTIONS |
4243 S_ATTR_SELF_MODIFYING_CODE |
4244 S_ATTR_SOME_INSTRUCTIONS))
4245 type = eSymbolTypeData;
4246 else
4247 type = eSymbolTypeCode;
4248 } else if (symbol_section->IsDescendant(section: data_section_sp.get()) ||
4249 symbol_section->IsDescendant(
4250 section: data_dirty_section_sp.get()) ||
4251 symbol_section->IsDescendant(
4252 section: data_const_section_sp.get())) {
4253 if (symbol_sect_name &&
4254 ::strstr(haystack: symbol_sect_name, needle: "__objc") == symbol_sect_name) {
4255 type = eSymbolTypeRuntime;
4256
4257 if (symbol_name) {
4258 llvm::StringRef symbol_name_ref(symbol_name);
4259 if (symbol_name_ref.starts_with(Prefix: "_OBJC_")) {
4260 llvm::StringRef g_objc_v2_prefix_class(
4261 "_OBJC_CLASS_$_");
4262 llvm::StringRef g_objc_v2_prefix_metaclass(
4263 "_OBJC_METACLASS_$_");
4264 llvm::StringRef g_objc_v2_prefix_ivar(
4265 "_OBJC_IVAR_$_");
4266 if (symbol_name_ref.starts_with(Prefix: g_objc_v2_prefix_class)) {
4267 symbol_name_non_abi_mangled = symbol_name + 1;
4268 symbol_name =
4269 symbol_name + g_objc_v2_prefix_class.size();
4270 type = eSymbolTypeObjCClass;
4271 demangled_is_synthesized = true;
4272 } else if (symbol_name_ref.starts_with(
4273 Prefix: g_objc_v2_prefix_metaclass)) {
4274 symbol_name_non_abi_mangled = symbol_name + 1;
4275 symbol_name =
4276 symbol_name + g_objc_v2_prefix_metaclass.size();
4277 type = eSymbolTypeObjCMetaClass;
4278 demangled_is_synthesized = true;
4279 } else if (symbol_name_ref.starts_with(
4280 Prefix: g_objc_v2_prefix_ivar)) {
4281 symbol_name_non_abi_mangled = symbol_name + 1;
4282 symbol_name =
4283 symbol_name + g_objc_v2_prefix_ivar.size();
4284 type = eSymbolTypeObjCIVar;
4285 demangled_is_synthesized = true;
4286 }
4287 }
4288 }
4289 } else if (symbol_sect_name &&
4290 ::strstr(haystack: symbol_sect_name, needle: "__gcc_except_tab") ==
4291 symbol_sect_name) {
4292 type = eSymbolTypeException;
4293 } else {
4294 type = eSymbolTypeData;
4295 }
4296 } else if (symbol_sect_name &&
4297 ::strstr(haystack: symbol_sect_name, needle: "__IMPORT") ==
4298 symbol_sect_name) {
4299 type = eSymbolTypeTrampoline;
4300 } else if (symbol_section->IsDescendant(section: objc_section_sp.get())) {
4301 type = eSymbolTypeRuntime;
4302 if (symbol_name && symbol_name[0] == '.') {
4303 llvm::StringRef symbol_name_ref(symbol_name);
4304 llvm::StringRef g_objc_v1_prefix_class(
4305 ".objc_class_name_");
4306 if (symbol_name_ref.starts_with(Prefix: g_objc_v1_prefix_class)) {
4307 symbol_name_non_abi_mangled = symbol_name;
4308 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4309 type = eSymbolTypeObjCClass;
4310 demangled_is_synthesized = true;
4311 }
4312 }
4313 }
4314 }
4315 }
4316 } break;
4317 }
4318 }
4319
4320 if (!add_nlist) {
4321 sym[sym_idx].Clear();
4322 return true;
4323 }
4324
4325 uint64_t symbol_value = nlist.n_value;
4326
4327 if (symbol_name_non_abi_mangled) {
4328 sym[sym_idx].GetMangled().SetMangledName(
4329 ConstString(symbol_name_non_abi_mangled));
4330 sym[sym_idx].GetMangled().SetDemangledName(ConstString(symbol_name));
4331 } else {
4332
4333 if (symbol_name && symbol_name[0] == '_') {
4334 symbol_name++; // Skip the leading underscore
4335 }
4336
4337 if (symbol_name) {
4338 ConstString const_symbol_name(symbol_name);
4339 sym[sym_idx].GetMangled().SetValue(const_symbol_name);
4340 }
4341 }
4342
4343 if (is_gsym) {
4344 const char *gsym_name = sym[sym_idx]
4345 .GetMangled()
4346 .GetName(preference: Mangled::ePreferMangled)
4347 .GetCString();
4348 if (gsym_name)
4349 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4350 }
4351
4352 if (symbol_section) {
4353 const addr_t section_file_addr = symbol_section->GetFileAddress();
4354 if (symbol_byte_size == 0 && function_starts_count > 0) {
4355 addr_t symbol_lookup_file_addr = nlist.n_value;
4356 // Do an exact address match for non-ARM addresses, else get the
4357 // closest since the symbol might be a thumb symbol which has an
4358 // address with bit zero set.
4359 FunctionStarts::Entry *func_start_entry =
4360 function_starts.FindEntry(addr: symbol_lookup_file_addr, exact_match_only: !is_arm);
4361 if (is_arm && func_start_entry) {
4362 // Verify that the function start address is the symbol address
4363 // (ARM) or the symbol address + 1 (thumb).
4364 if (func_start_entry->addr != symbol_lookup_file_addr &&
4365 func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4366 // Not the right entry, NULL it out...
4367 func_start_entry = nullptr;
4368 }
4369 }
4370 if (func_start_entry) {
4371 func_start_entry->data = true;
4372
4373 addr_t symbol_file_addr = func_start_entry->addr;
4374 if (is_arm)
4375 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4376
4377 const FunctionStarts::Entry *next_func_start_entry =
4378 function_starts.FindNextEntry(entry: func_start_entry);
4379 const addr_t section_end_file_addr =
4380 section_file_addr + symbol_section->GetByteSize();
4381 if (next_func_start_entry) {
4382 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4383 // Be sure the clear the Thumb address bit when we calculate the
4384 // size from the current and next address
4385 if (is_arm)
4386 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4387 symbol_byte_size = std::min<lldb::addr_t>(
4388 a: next_symbol_file_addr - symbol_file_addr,
4389 b: section_end_file_addr - symbol_file_addr);
4390 } else {
4391 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4392 }
4393 }
4394 }
4395 symbol_value -= section_file_addr;
4396 }
4397
4398 if (!is_debug) {
4399 if (type == eSymbolTypeCode) {
4400 // See if we can find a N_FUN entry for any code symbols. If we do
4401 // find a match, and the name matches, then we can merge the two into
4402 // just the function symbol to avoid duplicate entries in the symbol
4403 // table.
4404 std::pair<ValueToSymbolIndexMap::const_iterator,
4405 ValueToSymbolIndexMap::const_iterator>
4406 range;
4407 range = N_FUN_addr_to_sym_idx.equal_range(x: nlist.n_value);
4408 if (range.first != range.second) {
4409 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4410 pos != range.second; ++pos) {
4411 if (sym[sym_idx].GetMangled().GetName(preference: Mangled::ePreferMangled) ==
4412 sym[pos->second].GetMangled().GetName(
4413 preference: Mangled::ePreferMangled)) {
4414 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4415 // We just need the flags from the linker symbol, so put these
4416 // flags into the N_FUN flags to avoid duplicate symbols in the
4417 // symbol table.
4418 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4419 sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4420 if (resolver_addresses.find(x: nlist.n_value) !=
4421 resolver_addresses.end())
4422 sym[pos->second].SetType(eSymbolTypeResolver);
4423 sym[sym_idx].Clear();
4424 return true;
4425 }
4426 }
4427 } else {
4428 if (resolver_addresses.find(x: nlist.n_value) !=
4429 resolver_addresses.end())
4430 type = eSymbolTypeResolver;
4431 }
4432 } else if (type == eSymbolTypeData || type == eSymbolTypeObjCClass ||
4433 type == eSymbolTypeObjCMetaClass ||
4434 type == eSymbolTypeObjCIVar) {
4435 // See if we can find a N_STSYM entry for any data symbols. If we do
4436 // find a match, and the name matches, then we can merge the two into
4437 // just the Static symbol to avoid duplicate entries in the symbol
4438 // table.
4439 std::pair<ValueToSymbolIndexMap::const_iterator,
4440 ValueToSymbolIndexMap::const_iterator>
4441 range;
4442 range = N_STSYM_addr_to_sym_idx.equal_range(x: nlist.n_value);
4443 if (range.first != range.second) {
4444 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4445 pos != range.second; ++pos) {
4446 if (sym[sym_idx].GetMangled().GetName(preference: Mangled::ePreferMangled) ==
4447 sym[pos->second].GetMangled().GetName(
4448 preference: Mangled::ePreferMangled)) {
4449 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4450 // We just need the flags from the linker symbol, so put these
4451 // flags into the N_STSYM flags to avoid duplicate symbols in
4452 // the symbol table.
4453 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4454 sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4455 sym[sym_idx].Clear();
4456 return true;
4457 }
4458 }
4459 } else {
4460 // Combine N_GSYM stab entries with the non stab symbol.
4461 const char *gsym_name = sym[sym_idx]
4462 .GetMangled()
4463 .GetName(preference: Mangled::ePreferMangled)
4464 .GetCString();
4465 if (gsym_name) {
4466 ConstNameToSymbolIndexMap::const_iterator pos =
4467 N_GSYM_name_to_sym_idx.find(Val: gsym_name);
4468 if (pos != N_GSYM_name_to_sym_idx.end()) {
4469 const uint32_t GSYM_sym_idx = pos->second;
4470 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
4471 // Copy the address, because often the N_GSYM address has an
4472 // invalid address of zero when the global is a common symbol.
4473 sym[GSYM_sym_idx].GetAddressRef().SetSection(symbol_section);
4474 sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4475 add_symbol_addr(
4476 sym[GSYM_sym_idx].GetAddress().GetFileAddress());
4477 // We just need the flags from the linker symbol, so put these
4478 // flags into the N_GSYM flags to avoid duplicate symbols in
4479 // the symbol table.
4480 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4481 sym[sym_idx].Clear();
4482 return true;
4483 }
4484 }
4485 }
4486 }
4487 }
4488
4489 sym[sym_idx].SetID(nlist_idx);
4490 sym[sym_idx].SetType(type);
4491 if (set_value) {
4492 sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4493 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4494 if (symbol_section)
4495 add_symbol_addr(sym[sym_idx].GetAddress().GetFileAddress());
4496 }
4497 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4498 if (nlist.n_desc & N_WEAK_REF)
4499 sym[sym_idx].SetIsWeak(true);
4500
4501 if (symbol_byte_size > 0)
4502 sym[sym_idx].SetByteSize(symbol_byte_size);
4503
4504 if (demangled_is_synthesized)
4505 sym[sym_idx].SetDemangledNameIsSynthesized(true);
4506
4507 ++sym_idx;
4508 return true;
4509 };
4510
4511 // First parse all the nlists but don't process them yet. See the next
4512 // comment for an explanation why.
4513 std::vector<struct nlist_64> nlists;
4514 nlists.reserve(n: symtab_load_command.nsyms);
4515 for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
4516 if (auto nlist =
4517 ParseNList(nlist_data, nlist_data_offset, nlist_byte_size))
4518 nlists.push_back(x: *nlist);
4519 else
4520 break;
4521 }
4522
4523 // Now parse all the debug symbols. This is needed to merge non-debug
4524 // symbols in the next step. Non-debug symbols are always coalesced into
4525 // the debug symbol. Doing this in one step would mean that some symbols
4526 // won't be merged.
4527 nlist_idx = 0;
4528 for (auto &nlist : nlists) {
4529 if (!ParseSymbolLambda(nlist, nlist_idx++, DebugSymbols))
4530 break;
4531 }
4532
4533 // Finally parse all the non debug symbols.
4534 nlist_idx = 0;
4535 for (auto &nlist : nlists) {
4536 if (!ParseSymbolLambda(nlist, nlist_idx++, NonDebugSymbols))
4537 break;
4538 }
4539
4540 for (const auto &pos : reexport_shlib_needs_fixup) {
4541 const auto undef_pos = undefined_name_to_desc.find(Val: pos.second);
4542 if (undef_pos != undefined_name_to_desc.end()) {
4543 const uint8_t dylib_ordinal =
4544 llvm::MachO::GET_LIBRARY_ORDINAL(n_desc: undef_pos->second);
4545 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4546 sym[pos.first].SetReExportedSymbolSharedLibrary(
4547 dylib_files.GetFileSpecAtIndex(idx: dylib_ordinal - 1));
4548 }
4549 }
4550 }
4551
4552 // Count how many trie symbols we'll add to the symbol table
4553 int trie_symbol_table_augment_count = 0;
4554 for (auto &e : external_sym_trie_entries) {
4555 if (!symbols_added.contains(V: e.entry.address))
4556 trie_symbol_table_augment_count++;
4557 }
4558
4559 if (num_syms < sym_idx + trie_symbol_table_augment_count) {
4560 num_syms = sym_idx + trie_symbol_table_augment_count;
4561 sym = symtab.Resize(count: num_syms);
4562 }
4563 uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4564
4565 // Add symbols from the trie to the symbol table.
4566 for (auto &e : external_sym_trie_entries) {
4567 if (symbols_added.contains(V: e.entry.address))
4568 continue;
4569
4570 // Find the section that this trie address is in, use that to annotate
4571 // symbol type as we add the trie address and name to the symbol table.
4572 Address symbol_addr;
4573 if (module_sp->ResolveFileAddress(vm_addr: e.entry.address, so_addr&: symbol_addr)) {
4574 SectionSP symbol_section(symbol_addr.GetSection());
4575 const char *symbol_name = e.entry.name.GetCString();
4576 bool demangled_is_synthesized = false;
4577 SymbolType type =
4578 GetSymbolType(symbol_name, demangled_is_synthesized, text_section_sp,
4579 data_section_sp, data_dirty_section_sp,
4580 data_const_section_sp, symbol_section);
4581
4582 sym[sym_idx].SetType(type);
4583 if (symbol_section) {
4584 sym[sym_idx].SetID(synthetic_sym_id++);
4585 sym[sym_idx].GetMangled().SetMangledName(ConstString(symbol_name));
4586 if (demangled_is_synthesized)
4587 sym[sym_idx].SetDemangledNameIsSynthesized(true);
4588 sym[sym_idx].SetIsSynthetic(true);
4589 sym[sym_idx].SetExternal(true);
4590 sym[sym_idx].GetAddressRef() = symbol_addr;
4591 add_symbol_addr(symbol_addr.GetFileAddress());
4592 if (e.entry.flags & TRIE_SYMBOL_IS_THUMB)
4593 sym[sym_idx].SetFlags(MACHO_NLIST_ARM_SYMBOL_IS_THUMB);
4594 ++sym_idx;
4595 }
4596 }
4597 }
4598
4599 if (function_starts_count > 0) {
4600 uint32_t num_synthetic_function_symbols = 0;
4601 for (i = 0; i < function_starts_count; ++i) {
4602 if (!symbols_added.contains(V: function_starts.GetEntryRef(i).addr))
4603 ++num_synthetic_function_symbols;
4604 }
4605
4606 if (num_synthetic_function_symbols > 0) {
4607 if (num_syms < sym_idx + num_synthetic_function_symbols) {
4608 num_syms = sym_idx + num_synthetic_function_symbols;
4609 sym = symtab.Resize(count: num_syms);
4610 }
4611 for (i = 0; i < function_starts_count; ++i) {
4612 const FunctionStarts::Entry *func_start_entry =
4613 function_starts.GetEntryAtIndex(i);
4614 if (!symbols_added.contains(V: func_start_entry->addr)) {
4615 addr_t symbol_file_addr = func_start_entry->addr;
4616 uint32_t symbol_flags = 0;
4617 if (func_start_entry->data)
4618 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4619 Address symbol_addr;
4620 if (module_sp->ResolveFileAddress(vm_addr: symbol_file_addr, so_addr&: symbol_addr)) {
4621 SectionSP symbol_section(symbol_addr.GetSection());
4622 uint32_t symbol_byte_size = 0;
4623 if (symbol_section) {
4624 const addr_t section_file_addr = symbol_section->GetFileAddress();
4625 const FunctionStarts::Entry *next_func_start_entry =
4626 function_starts.FindNextEntry(entry: func_start_entry);
4627 const addr_t section_end_file_addr =
4628 section_file_addr + symbol_section->GetByteSize();
4629 if (next_func_start_entry) {
4630 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4631 if (is_arm)
4632 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4633 symbol_byte_size = std::min<lldb::addr_t>(
4634 a: next_symbol_file_addr - symbol_file_addr,
4635 b: section_end_file_addr - symbol_file_addr);
4636 } else {
4637 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4638 }
4639 sym[sym_idx].SetID(synthetic_sym_id++);
4640 // Don't set the name for any synthetic symbols, the Symbol
4641 // object will generate one if needed when the name is accessed
4642 // via accessors.
4643 sym[sym_idx].GetMangled().SetDemangledName(ConstString());
4644 sym[sym_idx].SetType(eSymbolTypeCode);
4645 sym[sym_idx].SetIsSynthetic(true);
4646 sym[sym_idx].GetAddressRef() = symbol_addr;
4647 add_symbol_addr(symbol_addr.GetFileAddress());
4648 if (symbol_flags)
4649 sym[sym_idx].SetFlags(symbol_flags);
4650 if (symbol_byte_size)
4651 sym[sym_idx].SetByteSize(symbol_byte_size);
4652 ++sym_idx;
4653 }
4654 }
4655 }
4656 }
4657 }
4658 }
4659
4660 // Trim our symbols down to just what we ended up with after removing any
4661 // symbols.
4662 if (sym_idx < num_syms) {
4663 num_syms = sym_idx;
4664 sym = symtab.Resize(count: num_syms);
4665 }
4666
4667 // Now synthesize indirect symbols
4668 if (m_dysymtab.nindirectsyms != 0) {
4669 if (indirect_symbol_index_data.GetByteSize()) {
4670 NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4671 m_nlist_idx_to_sym_idx.end();
4672
4673 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4674 ++sect_idx) {
4675 if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4676 S_SYMBOL_STUBS) {
4677 uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2;
4678 if (symbol_stub_byte_size == 0)
4679 continue;
4680
4681 const uint32_t num_symbol_stubs =
4682 m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4683
4684 if (num_symbol_stubs == 0)
4685 continue;
4686
4687 const uint32_t symbol_stub_index_offset =
4688 m_mach_sections[sect_idx].reserved1;
4689 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx) {
4690 const uint32_t symbol_stub_index =
4691 symbol_stub_index_offset + stub_idx;
4692 const lldb::addr_t symbol_stub_addr =
4693 m_mach_sections[sect_idx].addr +
4694 (stub_idx * symbol_stub_byte_size);
4695 lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4696 if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4697 offset: symbol_stub_offset, length: 4)) {
4698 const uint32_t stub_sym_id =
4699 indirect_symbol_index_data.GetU32(offset_ptr: &symbol_stub_offset);
4700 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4701 continue;
4702
4703 NListIndexToSymbolIndexMap::const_iterator index_pos =
4704 m_nlist_idx_to_sym_idx.find(Val: stub_sym_id);
4705 Symbol *stub_symbol = nullptr;
4706 if (index_pos != end_index_pos) {
4707 // We have a remapping from the original nlist index to a
4708 // current symbol index, so just look this up by index
4709 stub_symbol = symtab.SymbolAtIndex(idx: index_pos->second);
4710 } else {
4711 // We need to lookup a symbol using the original nlist symbol
4712 // index since this index is coming from the S_SYMBOL_STUBS
4713 stub_symbol = symtab.FindSymbolByID(uid: stub_sym_id);
4714 }
4715
4716 if (stub_symbol) {
4717 Address so_addr(symbol_stub_addr, section_list);
4718
4719 if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4720 // Change the external symbol into a trampoline that makes
4721 // sense These symbols were N_UNDF N_EXT, and are useless
4722 // to us, so we can re-use them so we don't have to make up
4723 // a synthetic symbol for no good reason.
4724 if (resolver_addresses.find(x: symbol_stub_addr) ==
4725 resolver_addresses.end())
4726 stub_symbol->SetType(eSymbolTypeTrampoline);
4727 else
4728 stub_symbol->SetType(eSymbolTypeResolver);
4729 stub_symbol->SetExternal(false);
4730 stub_symbol->GetAddressRef() = so_addr;
4731 stub_symbol->SetByteSize(symbol_stub_byte_size);
4732 } else {
4733 // Make a synthetic symbol to describe the trampoline stub
4734 Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4735 if (sym_idx >= num_syms) {
4736 sym = symtab.Resize(count: ++num_syms);
4737 stub_symbol = nullptr; // this pointer no longer valid
4738 }
4739 sym[sym_idx].SetID(synthetic_sym_id++);
4740 sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4741 if (resolver_addresses.find(x: symbol_stub_addr) ==
4742 resolver_addresses.end())
4743 sym[sym_idx].SetType(eSymbolTypeTrampoline);
4744 else
4745 sym[sym_idx].SetType(eSymbolTypeResolver);
4746 sym[sym_idx].SetIsSynthetic(true);
4747 sym[sym_idx].GetAddressRef() = so_addr;
4748 add_symbol_addr(so_addr.GetFileAddress());
4749 sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4750 ++sym_idx;
4751 }
4752 } else {
4753 if (log)
4754 log->Warning(fmt: "symbol stub referencing symbol table symbol "
4755 "%u that isn't in our minimal symbol table, "
4756 "fix this!!!",
4757 stub_sym_id);
4758 }
4759 }
4760 }
4761 }
4762 }
4763 }
4764 }
4765
4766 if (!reexport_trie_entries.empty()) {
4767 for (const auto &e : reexport_trie_entries) {
4768 if (e.entry.import_name) {
4769 // Only add indirect symbols from the Trie entries if we didn't have
4770 // a N_INDR nlist entry for this already
4771 if (indirect_symbol_names.find(x: e.entry.name) ==
4772 indirect_symbol_names.end()) {
4773 // Make a synthetic symbol to describe re-exported symbol.
4774 if (sym_idx >= num_syms)
4775 sym = symtab.Resize(count: ++num_syms);
4776 sym[sym_idx].SetID(synthetic_sym_id++);
4777 sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4778 sym[sym_idx].SetType(eSymbolTypeReExported);
4779 sym[sym_idx].SetIsSynthetic(true);
4780 sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4781 if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4782 sym[sym_idx].SetReExportedSymbolSharedLibrary(
4783 dylib_files.GetFileSpecAtIndex(idx: e.entry.other - 1));
4784 }
4785 ++sym_idx;
4786 }
4787 }
4788 }
4789 }
4790}
4791
4792void ObjectFileMachO::Dump(Stream *s) {
4793 ModuleSP module_sp(GetModule());
4794 if (module_sp) {
4795 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4796 s->Printf(format: "%p: ", static_cast<void *>(this));
4797 s->Indent();
4798 if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4799 s->PutCString(cstr: "ObjectFileMachO64");
4800 else
4801 s->PutCString(cstr: "ObjectFileMachO32");
4802
4803 *s << ", file = '" << m_file;
4804 ModuleSpecList all_specs;
4805 ModuleSpec base_spec;
4806 GetAllArchSpecs(header: m_header, data: m_data, lc_offset: MachHeaderSizeFromMagic(magic: m_header.magic),
4807 base_spec, all_specs);
4808 for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
4809 *s << "', triple";
4810 if (e)
4811 s->Printf(format: "[%d]", i);
4812 *s << " = ";
4813 *s << all_specs.GetModuleSpecRefAtIndex(i)
4814 .GetArchitecture()
4815 .GetTriple()
4816 .getTriple();
4817 }
4818 *s << "\n";
4819 SectionList *sections = GetSectionList();
4820 if (sections)
4821 sections->Dump(s&: s->AsRawOstream(), indent: s->GetIndentLevel(), target: nullptr, show_header: true,
4822 UINT32_MAX);
4823
4824 if (m_symtab_up)
4825 m_symtab_up->Dump(s, target: nullptr, sort_type: eSortOrderNone);
4826 }
4827}
4828
4829UUID ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4830 const lldb_private::DataExtractor &data,
4831 lldb::offset_t lc_offset) {
4832 uint32_t i;
4833 llvm::MachO::uuid_command load_cmd;
4834
4835 lldb::offset_t offset = lc_offset;
4836 for (i = 0; i < header.ncmds; ++i) {
4837 const lldb::offset_t cmd_offset = offset;
4838 if (data.GetU32(offset_ptr: &offset, dst: &load_cmd, count: 2) == nullptr)
4839 break;
4840
4841 if (load_cmd.cmd == LC_UUID) {
4842 const uint8_t *uuid_bytes = data.PeekData(offset, length: 16);
4843
4844 if (uuid_bytes) {
4845 // OpenCL on Mac OS X uses the same UUID for each of its object files.
4846 // We pretend these object files have no UUID to prevent crashing.
4847
4848 const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4849 0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4850 0xbb, 0x14, 0xf0, 0x0d};
4851
4852 if (!memcmp(s1: uuid_bytes, s2: opencl_uuid, n: 16))
4853 return UUID();
4854
4855 return UUID(uuid_bytes, 16);
4856 }
4857 return UUID();
4858 }
4859 offset = cmd_offset + load_cmd.cmdsize;
4860 }
4861 return UUID();
4862}
4863
4864static llvm::StringRef GetOSName(uint32_t cmd) {
4865 switch (cmd) {
4866 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
4867 return llvm::Triple::getOSTypeName(Kind: llvm::Triple::IOS);
4868 case llvm::MachO::LC_VERSION_MIN_MACOSX:
4869 return llvm::Triple::getOSTypeName(Kind: llvm::Triple::MacOSX);
4870 case llvm::MachO::LC_VERSION_MIN_TVOS:
4871 return llvm::Triple::getOSTypeName(Kind: llvm::Triple::TvOS);
4872 case llvm::MachO::LC_VERSION_MIN_WATCHOS:
4873 return llvm::Triple::getOSTypeName(Kind: llvm::Triple::WatchOS);
4874 default:
4875 llvm_unreachable("unexpected LC_VERSION load command");
4876 }
4877}
4878
4879namespace {
4880struct OSEnv {
4881 llvm::StringRef os_type;
4882 llvm::StringRef environment;
4883 OSEnv(uint32_t cmd) {
4884 switch (cmd) {
4885 case llvm::MachO::PLATFORM_MACOS:
4886 os_type = llvm::Triple::getOSTypeName(Kind: llvm::Triple::MacOSX);
4887 return;
4888 case llvm::MachO::PLATFORM_IOS:
4889 os_type = llvm::Triple::getOSTypeName(Kind: llvm::Triple::IOS);
4890 return;
4891 case llvm::MachO::PLATFORM_TVOS:
4892 os_type = llvm::Triple::getOSTypeName(Kind: llvm::Triple::TvOS);
4893 return;
4894 case llvm::MachO::PLATFORM_WATCHOS:
4895 os_type = llvm::Triple::getOSTypeName(Kind: llvm::Triple::WatchOS);
4896 return;
4897 case llvm::MachO::PLATFORM_BRIDGEOS:
4898 os_type = llvm::Triple::getOSTypeName(Kind: llvm::Triple::BridgeOS);
4899 return;
4900 case llvm::MachO::PLATFORM_DRIVERKIT:
4901 os_type = llvm::Triple::getOSTypeName(Kind: llvm::Triple::DriverKit);
4902 return;
4903 case llvm::MachO::PLATFORM_MACCATALYST:
4904 os_type = llvm::Triple::getOSTypeName(Kind: llvm::Triple::IOS);
4905 environment = llvm::Triple::getEnvironmentTypeName(Kind: llvm::Triple::MacABI);
4906 return;
4907 case llvm::MachO::PLATFORM_IOSSIMULATOR:
4908 os_type = llvm::Triple::getOSTypeName(Kind: llvm::Triple::IOS);
4909 environment =
4910 llvm::Triple::getEnvironmentTypeName(Kind: llvm::Triple::Simulator);
4911 return;
4912 case llvm::MachO::PLATFORM_TVOSSIMULATOR:
4913 os_type = llvm::Triple::getOSTypeName(Kind: llvm::Triple::TvOS);
4914 environment =
4915 llvm::Triple::getEnvironmentTypeName(Kind: llvm::Triple::Simulator);
4916 return;
4917 case llvm::MachO::PLATFORM_WATCHOSSIMULATOR:
4918 os_type = llvm::Triple::getOSTypeName(Kind: llvm::Triple::WatchOS);
4919 environment =
4920 llvm::Triple::getEnvironmentTypeName(Kind: llvm::Triple::Simulator);
4921 return;
4922 case llvm::MachO::PLATFORM_XROS:
4923 os_type = llvm::Triple::getOSTypeName(Kind: llvm::Triple::XROS);
4924 return;
4925 case llvm::MachO::PLATFORM_XROS_SIMULATOR:
4926 os_type = llvm::Triple::getOSTypeName(Kind: llvm::Triple::XROS);
4927 environment =
4928 llvm::Triple::getEnvironmentTypeName(Kind: llvm::Triple::Simulator);
4929 return;
4930 default: {
4931 Log *log(GetLog(mask: LLDBLog::Symbols | LLDBLog::Process));
4932 LLDB_LOGF(log, "unsupported platform in LC_BUILD_VERSION");
4933 }
4934 }
4935 }
4936};
4937
4938struct MinOS {
4939 uint32_t major_version, minor_version, patch_version;
4940 MinOS(uint32_t version)
4941 : major_version(version >> 16), minor_version((version >> 8) & 0xffu),
4942 patch_version(version & 0xffu) {}
4943};
4944} // namespace
4945
4946void ObjectFileMachO::GetAllArchSpecs(const llvm::MachO::mach_header &header,
4947 const lldb_private::DataExtractor &data,
4948 lldb::offset_t lc_offset,
4949 ModuleSpec &base_spec,
4950 lldb_private::ModuleSpecList &all_specs) {
4951 auto &base_arch = base_spec.GetArchitecture();
4952 base_arch.SetArchitecture(arch_type: eArchTypeMachO, cpu: header.cputype, sub: header.cpusubtype);
4953 if (!base_arch.IsValid())
4954 return;
4955
4956 bool found_any = false;
4957 auto add_triple = [&](const llvm::Triple &triple) {
4958 auto spec = base_spec;
4959 spec.GetArchitecture().GetTriple() = triple;
4960 if (spec.GetArchitecture().IsValid()) {
4961 spec.GetUUID() = ObjectFileMachO::GetUUID(header, data, lc_offset);
4962 all_specs.Append(spec);
4963 found_any = true;
4964 }
4965 };
4966
4967 // Set OS to an unspecified unknown or a "*" so it can match any OS
4968 llvm::Triple base_triple = base_arch.GetTriple();
4969 base_triple.setOS(llvm::Triple::UnknownOS);
4970 base_triple.setOSName(llvm::StringRef());
4971
4972 if (header.filetype == MH_PRELOAD) {
4973 if (header.cputype == CPU_TYPE_ARM) {
4974 // If this is a 32-bit arm binary, and it's a standalone binary, force
4975 // the Vendor to Apple so we don't accidentally pick up the generic
4976 // armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the
4977 // frame pointer register; most other armv7 ABIs use a combination of
4978 // r7 and r11.
4979 base_triple.setVendor(llvm::Triple::Apple);
4980 } else {
4981 // Set vendor to an unspecified unknown or a "*" so it can match any
4982 // vendor This is required for correct behavior of EFI debugging on
4983 // x86_64
4984 base_triple.setVendor(llvm::Triple::UnknownVendor);
4985 base_triple.setVendorName(llvm::StringRef());
4986 }
4987 return add_triple(base_triple);
4988 }
4989
4990 llvm::MachO::load_command load_cmd;
4991
4992 // See if there is an LC_VERSION_MIN_* load command that can give
4993 // us the OS type.
4994 lldb::offset_t offset = lc_offset;
4995 for (uint32_t i = 0; i < header.ncmds; ++i) {
4996 const lldb::offset_t cmd_offset = offset;
4997 if (data.GetU32(offset_ptr: &offset, dst: &load_cmd, count: 2) == nullptr)
4998 break;
4999
5000 llvm::MachO::version_min_command version_min;
5001 switch (load_cmd.cmd) {
5002 case llvm::MachO::LC_VERSION_MIN_MACOSX:
5003 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
5004 case llvm::MachO::LC_VERSION_MIN_TVOS:
5005 case llvm::MachO::LC_VERSION_MIN_WATCHOS: {
5006 if (load_cmd.cmdsize != sizeof(version_min))
5007 break;
5008 if (data.ExtractBytes(offset: cmd_offset, length: sizeof(version_min),
5009 dst_byte_order: data.GetByteOrder(), dst: &version_min) == 0)
5010 break;
5011 MinOS min_os(version_min.version);
5012 llvm::SmallString<32> os_name;
5013 llvm::raw_svector_ostream os(os_name);
5014 os << GetOSName(cmd: load_cmd.cmd) << min_os.major_version << '.'
5015 << min_os.minor_version << '.' << min_os.patch_version;
5016
5017 auto triple = base_triple;
5018 triple.setOSName(os.str());
5019
5020 // Disambiguate legacy simulator platforms.
5021 if (load_cmd.cmd != llvm::MachO::LC_VERSION_MIN_MACOSX &&
5022 (base_triple.getArch() == llvm::Triple::x86_64 ||
5023 base_triple.getArch() == llvm::Triple::x86)) {
5024 // The combination of legacy LC_VERSION_MIN load command and
5025 // x86 architecture always indicates a simulator environment.
5026 // The combination of LC_VERSION_MIN and arm architecture only
5027 // appears for native binaries. Back-deploying simulator
5028 // binaries on Apple Silicon Macs use the modern unambigous
5029 // LC_BUILD_VERSION load commands; no special handling required.
5030 triple.setEnvironment(llvm::Triple::Simulator);
5031 }
5032 add_triple(triple);
5033 break;
5034 }
5035 default:
5036 break;
5037 }
5038
5039 offset = cmd_offset + load_cmd.cmdsize;
5040 }
5041
5042 // See if there are LC_BUILD_VERSION load commands that can give
5043 // us the OS type.
5044 offset = lc_offset;
5045 for (uint32_t i = 0; i < header.ncmds; ++i) {
5046 const lldb::offset_t cmd_offset = offset;
5047 if (data.GetU32(offset_ptr: &offset, dst: &load_cmd, count: 2) == nullptr)
5048 break;
5049
5050 do {
5051 if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) {
5052 llvm::MachO::build_version_command build_version;
5053 if (load_cmd.cmdsize < sizeof(build_version)) {
5054 // Malformed load command.
5055 break;
5056 }
5057 if (data.ExtractBytes(offset: cmd_offset, length: sizeof(build_version),
5058 dst_byte_order: data.GetByteOrder(), dst: &build_version) == 0)
5059 break;
5060 MinOS min_os(build_version.minos);
5061 OSEnv os_env(build_version.platform);
5062 llvm::SmallString<16> os_name;
5063 llvm::raw_svector_ostream os(os_name);
5064 os << os_env.os_type << min_os.major_version << '.'
5065 << min_os.minor_version << '.' << min_os.patch_version;
5066 auto triple = base_triple;
5067 triple.setOSName(os.str());
5068 os_name.clear();
5069 if (!os_env.environment.empty())
5070 triple.setEnvironmentName(os_env.environment);
5071 add_triple(triple);
5072 }
5073 } while (false);
5074 offset = cmd_offset + load_cmd.cmdsize;
5075 }
5076
5077 if (!found_any) {
5078 add_triple(base_triple);
5079 }
5080}
5081
5082ArchSpec ObjectFileMachO::GetArchitecture(
5083 ModuleSP module_sp, const llvm::MachO::mach_header &header,
5084 const lldb_private::DataExtractor &data, lldb::offset_t lc_offset) {
5085 ModuleSpecList all_specs;
5086 ModuleSpec base_spec;
5087 GetAllArchSpecs(header, data, lc_offset: MachHeaderSizeFromMagic(magic: header.magic),
5088 base_spec, all_specs);
5089
5090 // If the object file offers multiple alternative load commands,
5091 // pick the one that matches the module.
5092 if (module_sp) {
5093 const ArchSpec &module_arch = module_sp->GetArchitecture();
5094 for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
5095 ArchSpec mach_arch =
5096 all_specs.GetModuleSpecRefAtIndex(i).GetArchitecture();
5097 if (module_arch.IsCompatibleMatch(rhs: mach_arch))
5098 return mach_arch;
5099 }
5100 }
5101
5102 // Return the first arch we found.
5103 if (all_specs.GetSize() == 0)
5104 return {};
5105 return all_specs.GetModuleSpecRefAtIndex(i: 0).GetArchitecture();
5106}
5107
5108UUID ObjectFileMachO::GetUUID() {
5109 ModuleSP module_sp(GetModule());
5110 if (module_sp) {
5111 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5112 lldb::offset_t offset = MachHeaderSizeFromMagic(magic: m_header.magic);
5113 return GetUUID(header: m_header, data: m_data, lc_offset: offset);
5114 }
5115 return UUID();
5116}
5117
5118uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) {
5119 uint32_t count = 0;
5120 ModuleSP module_sp(GetModule());
5121 if (module_sp) {
5122 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5123 llvm::MachO::load_command load_cmd;
5124 lldb::offset_t offset = MachHeaderSizeFromMagic(magic: m_header.magic);
5125 std::vector<std::string> rpath_paths;
5126 std::vector<std::string> rpath_relative_paths;
5127 std::vector<std::string> at_exec_relative_paths;
5128 uint32_t i;
5129 for (i = 0; i < m_header.ncmds; ++i) {
5130 const uint32_t cmd_offset = offset;
5131 if (m_data.GetU32(offset_ptr: &offset, dst: &load_cmd, count: 2) == nullptr)
5132 break;
5133
5134 switch (load_cmd.cmd) {
5135 case LC_RPATH:
5136 case LC_LOAD_DYLIB:
5137 case LC_LOAD_WEAK_DYLIB:
5138 case LC_REEXPORT_DYLIB:
5139 case LC_LOAD_DYLINKER:
5140 case LC_LOADFVMLIB:
5141 case LC_LOAD_UPWARD_DYLIB: {
5142 uint32_t name_offset = cmd_offset + m_data.GetU32(offset_ptr: &offset);
5143 const char *path = m_data.PeekCStr(offset: name_offset);
5144 if (path) {
5145 if (load_cmd.cmd == LC_RPATH)
5146 rpath_paths.push_back(x: path);
5147 else {
5148 if (path[0] == '@') {
5149 if (strncmp(s1: path, s2: "@rpath", n: strlen(s: "@rpath")) == 0)
5150 rpath_relative_paths.push_back(x: path + strlen(s: "@rpath"));
5151 else if (strncmp(s1: path, s2: "@executable_path",
5152 n: strlen(s: "@executable_path")) == 0)
5153 at_exec_relative_paths.push_back(x: path +
5154 strlen(s: "@executable_path"));
5155 } else {
5156 FileSpec file_spec(path);
5157 if (files.AppendIfUnique(file: file_spec))
5158 count++;
5159 }
5160 }
5161 }
5162 } break;
5163
5164 default:
5165 break;
5166 }
5167 offset = cmd_offset + load_cmd.cmdsize;
5168 }
5169
5170 FileSpec this_file_spec(m_file);
5171 FileSystem::Instance().Resolve(file_spec&: this_file_spec);
5172
5173 if (!rpath_paths.empty()) {
5174 // Fixup all LC_RPATH values to be absolute paths
5175 std::string loader_path("@loader_path");
5176 std::string executable_path("@executable_path");
5177 for (auto &rpath : rpath_paths) {
5178 if (llvm::StringRef(rpath).starts_with(Prefix: loader_path)) {
5179 rpath.erase(pos: 0, n: loader_path.size());
5180 rpath.insert(pos: 0, s: this_file_spec.GetDirectory().GetCString());
5181 } else if (llvm::StringRef(rpath).starts_with(Prefix: executable_path)) {
5182 rpath.erase(pos: 0, n: executable_path.size());
5183 rpath.insert(pos: 0, s: this_file_spec.GetDirectory().GetCString());
5184 }
5185 }
5186
5187 for (const auto &rpath_relative_path : rpath_relative_paths) {
5188 for (const auto &rpath : rpath_paths) {
5189 std::string path = rpath;
5190 path += rpath_relative_path;
5191 // It is OK to resolve this path because we must find a file on disk
5192 // for us to accept it anyway if it is rpath relative.
5193 FileSpec file_spec(path);
5194 FileSystem::Instance().Resolve(file_spec);
5195 if (FileSystem::Instance().Exists(file_spec) &&
5196 files.AppendIfUnique(file: file_spec)) {
5197 count++;
5198 break;
5199 }
5200 }
5201 }
5202 }
5203
5204 // We may have @executable_paths but no RPATHS. Figure those out here.
5205 // Only do this if this object file is the executable. We have no way to
5206 // get back to the actual executable otherwise, so we won't get the right
5207 // path.
5208 if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
5209 FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
5210 for (const auto &at_exec_relative_path : at_exec_relative_paths) {
5211 FileSpec file_spec =
5212 exec_dir.CopyByAppendingPathComponent(component: at_exec_relative_path);
5213 if (FileSystem::Instance().Exists(file_spec) &&
5214 files.AppendIfUnique(file: file_spec))
5215 count++;
5216 }
5217 }
5218 }
5219 return count;
5220}
5221
5222lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
5223 // If the object file is not an executable it can't hold the entry point.
5224 // m_entry_point_address is initialized to an invalid address, so we can just
5225 // return that. If m_entry_point_address is valid it means we've found it
5226 // already, so return the cached value.
5227
5228 if ((!IsExecutable() && !IsDynamicLoader()) ||
5229 m_entry_point_address.IsValid()) {
5230 return m_entry_point_address;
5231 }
5232
5233 // Otherwise, look for the UnixThread or Thread command. The data for the
5234 // Thread command is given in /usr/include/mach-o.h, but it is basically:
5235 //
5236 // uint32_t flavor - this is the flavor argument you would pass to
5237 // thread_get_state
5238 // uint32_t count - this is the count of longs in the thread state data
5239 // struct XXX_thread_state state - this is the structure from
5240 // <machine/thread_status.h> corresponding to the flavor.
5241 // <repeat this trio>
5242 //
5243 // So we just keep reading the various register flavors till we find the GPR
5244 // one, then read the PC out of there.
5245 // FIXME: We will need to have a "RegisterContext data provider" class at some
5246 // point that can get all the registers
5247 // out of data in this form & attach them to a given thread. That should
5248 // underlie the MacOS X User process plugin, and we'll also need it for the
5249 // MacOS X Core File process plugin. When we have that we can also use it
5250 // here.
5251 //
5252 // For now we hard-code the offsets and flavors we need:
5253 //
5254 //
5255
5256 ModuleSP module_sp(GetModule());
5257 if (module_sp) {
5258 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5259 llvm::MachO::load_command load_cmd;
5260 lldb::offset_t offset = MachHeaderSizeFromMagic(magic: m_header.magic);
5261 uint32_t i;
5262 lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
5263 bool done = false;
5264
5265 for (i = 0; i < m_header.ncmds; ++i) {
5266 const lldb::offset_t cmd_offset = offset;
5267 if (m_data.GetU32(offset_ptr: &offset, dst: &load_cmd, count: 2) == nullptr)
5268 break;
5269
5270 switch (load_cmd.cmd) {
5271 case LC_UNIXTHREAD:
5272 case LC_THREAD: {
5273 while (offset < cmd_offset + load_cmd.cmdsize) {
5274 uint32_t flavor = m_data.GetU32(offset_ptr: &offset);
5275 uint32_t count = m_data.GetU32(offset_ptr: &offset);
5276 if (count == 0) {
5277 // We've gotten off somehow, log and exit;
5278 return m_entry_point_address;
5279 }
5280
5281 switch (m_header.cputype) {
5282 case llvm::MachO::CPU_TYPE_ARM:
5283 if (flavor == 1 ||
5284 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32
5285 // from mach/arm/thread_status.h
5286 {
5287 offset += 60; // This is the offset of pc in the GPR thread state
5288 // data structure.
5289 start_address = m_data.GetU32(offset_ptr: &offset);
5290 done = true;
5291 }
5292 break;
5293 case llvm::MachO::CPU_TYPE_ARM64:
5294 case llvm::MachO::CPU_TYPE_ARM64_32:
5295 if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
5296 {
5297 offset += 256; // This is the offset of pc in the GPR thread state
5298 // data structure.
5299 start_address = m_data.GetU64(offset_ptr: &offset);
5300 done = true;
5301 }
5302 break;
5303 case llvm::MachO::CPU_TYPE_I386:
5304 if (flavor ==
5305 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
5306 {
5307 offset += 40; // This is the offset of eip in the GPR thread state
5308 // data structure.
5309 start_address = m_data.GetU32(offset_ptr: &offset);
5310 done = true;
5311 }
5312 break;
5313 case llvm::MachO::CPU_TYPE_X86_64:
5314 if (flavor ==
5315 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
5316 {
5317 offset += 16 * 8; // This is the offset of rip in the GPR thread
5318 // state data structure.
5319 start_address = m_data.GetU64(offset_ptr: &offset);
5320 done = true;
5321 }
5322 break;
5323 default:
5324 return m_entry_point_address;
5325 }
5326 // Haven't found the GPR flavor yet, skip over the data for this
5327 // flavor:
5328 if (done)
5329 break;
5330 offset += count * 4;
5331 }
5332 } break;
5333 case LC_MAIN: {
5334 uint64_t entryoffset = m_data.GetU64(offset_ptr: &offset);
5335 SectionSP text_segment_sp =
5336 GetSectionList()->FindSectionByName(section_dstr: GetSegmentNameTEXT());
5337 if (text_segment_sp) {
5338 done = true;
5339 start_address = text_segment_sp->GetFileAddress() + entryoffset;
5340 }
5341 } break;
5342
5343 default:
5344 break;
5345 }
5346 if (done)
5347 break;
5348
5349 // Go to the next load command:
5350 offset = cmd_offset + load_cmd.cmdsize;
5351 }
5352
5353 if (start_address == LLDB_INVALID_ADDRESS && IsDynamicLoader()) {
5354 if (GetSymtab()) {
5355 Symbol *dyld_start_sym = GetSymtab()->FindFirstSymbolWithNameAndType(
5356 name: ConstString("_dyld_start"), symbol_type: SymbolType::eSymbolTypeCode,
5357 symbol_debug_type: Symtab::eDebugAny, symbol_visibility: Symtab::eVisibilityAny);
5358 if (dyld_start_sym && dyld_start_sym->GetAddress().IsValid()) {
5359 start_address = dyld_start_sym->GetAddress().GetFileAddress();
5360 }
5361 }
5362 }
5363
5364 if (start_address != LLDB_INVALID_ADDRESS) {
5365 // We got the start address from the load commands, so now resolve that
5366 // address in the sections of this ObjectFile:
5367 if (!m_entry_point_address.ResolveAddressUsingFileSections(
5368 addr: start_address, sections: GetSectionList())) {
5369 m_entry_point_address.Clear();
5370 }
5371 } else {
5372 // We couldn't read the UnixThread load command - maybe it wasn't there.
5373 // As a fallback look for the "start" symbol in the main executable.
5374
5375 ModuleSP module_sp(GetModule());
5376
5377 if (module_sp) {
5378 SymbolContextList contexts;
5379 SymbolContext context;
5380 module_sp->FindSymbolsWithNameAndType(name: ConstString("start"),
5381 symbol_type: eSymbolTypeCode, sc_list&: contexts);
5382 if (contexts.GetSize()) {
5383 if (contexts.GetContextAtIndex(idx: 0, sc&: context))
5384 m_entry_point_address = context.symbol->GetAddress();
5385 }
5386 }
5387 }
5388 }
5389
5390 return m_entry_point_address;
5391}
5392
5393lldb_private::Address ObjectFileMachO::GetBaseAddress() {
5394 lldb_private::Address header_addr;
5395 SectionList *section_list = GetSectionList();
5396 if (section_list) {
5397 SectionSP text_segment_sp(
5398 section_list->FindSectionByName(section_dstr: GetSegmentNameTEXT()));
5399 if (text_segment_sp) {
5400 header_addr.SetSection(text_segment_sp);
5401 header_addr.SetOffset(0);
5402 }
5403 }
5404 return header_addr;
5405}
5406
5407uint32_t ObjectFileMachO::GetNumThreadContexts() {
5408 ModuleSP module_sp(GetModule());
5409 if (module_sp) {
5410 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5411 if (!m_thread_context_offsets_valid) {
5412 m_thread_context_offsets_valid = true;
5413 lldb::offset_t offset = MachHeaderSizeFromMagic(magic: m_header.magic);
5414 FileRangeArray::Entry file_range;
5415 llvm::MachO::thread_command thread_cmd;
5416 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5417 const uint32_t cmd_offset = offset;
5418 if (m_data.GetU32(offset_ptr: &offset, dst: &thread_cmd, count: 2) == nullptr)
5419 break;
5420
5421 if (thread_cmd.cmd == LC_THREAD) {
5422 file_range.SetRangeBase(offset);
5423 file_range.SetByteSize(thread_cmd.cmdsize - 8);
5424 m_thread_context_offsets.Append(entry: file_range);
5425 }
5426 offset = cmd_offset + thread_cmd.cmdsize;
5427 }
5428 }
5429 }
5430 return m_thread_context_offsets.GetSize();
5431}
5432
5433std::vector<std::tuple<offset_t, offset_t>>
5434ObjectFileMachO::FindLC_NOTEByName(std::string name) {
5435 std::vector<std::tuple<offset_t, offset_t>> results;
5436 ModuleSP module_sp(GetModule());
5437 if (module_sp) {
5438 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5439
5440 offset_t offset = MachHeaderSizeFromMagic(magic: m_header.magic);
5441 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5442 const uint32_t cmd_offset = offset;
5443 llvm::MachO::load_command lc = {};
5444 if (m_data.GetU32(offset_ptr: &offset, dst: &lc.cmd, count: 2) == nullptr)
5445 break;
5446 if (lc.cmd == LC_NOTE) {
5447 char data_owner[17];
5448 m_data.CopyData(offset, length: 16, dst: data_owner);
5449 data_owner[16] = '\0';
5450 offset += 16;
5451
5452 if (name == data_owner) {
5453 offset_t payload_offset = m_data.GetU64_unchecked(offset_ptr: &offset);
5454 offset_t payload_size = m_data.GetU64_unchecked(offset_ptr: &offset);
5455 results.push_back(x: {payload_offset, payload_size});
5456 }
5457 }
5458 offset = cmd_offset + lc.cmdsize;
5459 }
5460 }
5461 return results;
5462}
5463
5464std::string ObjectFileMachO::GetIdentifierString() {
5465 Log *log(
5466 GetLog(mask: LLDBLog::Symbols | LLDBLog::Process | LLDBLog::DynamicLoader));
5467 ModuleSP module_sp(GetModule());
5468 if (module_sp) {
5469 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5470
5471 auto lc_notes = FindLC_NOTEByName(name: "kern ver str");
5472 for (auto lc_note : lc_notes) {
5473 offset_t payload_offset = std::get<0>(t&: lc_note);
5474 offset_t payload_size = std::get<1>(t&: lc_note);
5475 uint32_t version;
5476 if (m_data.GetU32(offset_ptr: &payload_offset, dst: &version, count: 1) != nullptr) {
5477 if (version == 1) {
5478 uint32_t strsize = payload_size - sizeof(uint32_t);
5479 std::string result(strsize, '\0');
5480 m_data.CopyData(offset: payload_offset, length: strsize, dst: result.data());
5481 LLDB_LOGF(log, "LC_NOTE 'kern ver str' found with text '%s'",
5482 result.c_str());
5483 return result;
5484 }
5485 }
5486 }
5487
5488 // Second, make a pass over the load commands looking for an obsolete
5489 // LC_IDENT load command.
5490 offset_t offset = MachHeaderSizeFromMagic(magic: m_header.magic);
5491 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5492 const uint32_t cmd_offset = offset;
5493 llvm::MachO::ident_command ident_command;
5494 if (m_data.GetU32(offset_ptr: &offset, dst: &ident_command, count: 2) == nullptr)
5495 break;
5496 if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
5497 std::string result(ident_command.cmdsize, '\0');
5498 if (m_data.CopyData(offset, length: ident_command.cmdsize, dst: result.data()) ==
5499 ident_command.cmdsize) {
5500 LLDB_LOGF(log, "LC_IDENT found with text '%s'", result.c_str());
5501 return result;
5502 }
5503 }
5504 offset = cmd_offset + ident_command.cmdsize;
5505 }
5506 }
5507 return {};
5508}
5509
5510AddressableBits ObjectFileMachO::GetAddressableBits() {
5511 AddressableBits addressable_bits;
5512
5513 Log *log(GetLog(mask: LLDBLog::Process));
5514 ModuleSP module_sp(GetModule());
5515 if (module_sp) {
5516 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5517 auto lc_notes = FindLC_NOTEByName(name: "addrable bits");
5518 for (auto lc_note : lc_notes) {
5519 offset_t payload_offset = std::get<0>(t&: lc_note);
5520 uint32_t version;
5521 if (m_data.GetU32(offset_ptr: &payload_offset, dst: &version, count: 1) != nullptr) {
5522 if (version == 3) {
5523 uint32_t num_addr_bits = m_data.GetU32_unchecked(offset_ptr: &payload_offset);
5524 addressable_bits.SetAddressableBits(num_addr_bits);
5525 LLDB_LOGF(log,
5526 "LC_NOTE 'addrable bits' v3 found, value %d "
5527 "bits",
5528 num_addr_bits);
5529 }
5530 if (version == 4) {
5531 uint32_t lo_addr_bits = m_data.GetU32_unchecked(offset_ptr: &payload_offset);
5532 uint32_t hi_addr_bits = m_data.GetU32_unchecked(offset_ptr: &payload_offset);
5533
5534 if (lo_addr_bits == hi_addr_bits)
5535 addressable_bits.SetAddressableBits(lo_addr_bits);
5536 else
5537 addressable_bits.SetAddressableBits(lowmem_addressing_bits: lo_addr_bits, highmem_addressing_bits: hi_addr_bits);
5538 LLDB_LOGF(log, "LC_NOTE 'addrable bits' v4 found, value %d & %d bits",
5539 lo_addr_bits, hi_addr_bits);
5540 }
5541 }
5542 }
5543 }
5544 return addressable_bits;
5545}
5546
5547bool ObjectFileMachO::GetCorefileMainBinaryInfo(addr_t &value,
5548 bool &value_is_offset,
5549 UUID &uuid,
5550 ObjectFile::BinaryType &type) {
5551 Log *log(
5552 GetLog(mask: LLDBLog::Symbols | LLDBLog::Process | LLDBLog::DynamicLoader));
5553 value = LLDB_INVALID_ADDRESS;
5554 value_is_offset = false;
5555 uuid.Clear();
5556 uint32_t log2_pagesize = 0; // not currently passed up to caller
5557 uint32_t platform = 0; // not currently passed up to caller
5558 ModuleSP module_sp(GetModule());
5559 if (module_sp) {
5560 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5561
5562 auto lc_notes = FindLC_NOTEByName(name: "main bin spec");
5563 for (auto lc_note : lc_notes) {
5564 offset_t payload_offset = std::get<0>(t&: lc_note);
5565
5566 // struct main_bin_spec
5567 // {
5568 // uint32_t version; // currently 2
5569 // uint32_t type; // 0 == unspecified, 1 == kernel,
5570 // // 2 == user process,
5571 // // 3 == standalone binary
5572 // uint64_t address; // UINT64_MAX if address not specified
5573 // uint64_t slide; // slide, UINT64_MAX if unspecified
5574 // // 0 if no slide needs to be applied to
5575 // // file address
5576 // uuid_t uuid; // all zero's if uuid not specified
5577 // uint32_t log2_pagesize; // process page size in log base 2,
5578 // // e.g. 4k pages are 12.
5579 // // 0 for unspecified
5580 // uint32_t platform; // The Mach-O platform for this corefile.
5581 // // 0 for unspecified.
5582 // // The values are defined in
5583 // // <mach-o/loader.h>, PLATFORM_*.
5584 // } __attribute((packed));
5585
5586 // "main bin spec" (main binary specification) data payload is
5587 // formatted:
5588 // uint32_t version [currently 1]
5589 // uint32_t type [0 == unspecified, 1 == kernel,
5590 // 2 == user process, 3 == firmware ]
5591 // uint64_t address [ UINT64_MAX if address not specified ]
5592 // uuid_t uuid [ all zero's if uuid not specified ]
5593 // uint32_t log2_pagesize [ process page size in log base
5594 // 2, e.g. 4k pages are 12.
5595 // 0 for unspecified ]
5596 // uint32_t unused [ for alignment ]
5597
5598 uint32_t version;
5599 if (m_data.GetU32(offset_ptr: &payload_offset, dst: &version, count: 1) != nullptr &&
5600 version <= 2) {
5601 uint32_t binspec_type = 0;
5602 uuid_t raw_uuid;
5603 memset(s: raw_uuid, c: 0, n: sizeof(uuid_t));
5604
5605 if (!m_data.GetU32(offset_ptr: &payload_offset, dst: &binspec_type, count: 1))
5606 return false;
5607 if (!m_data.GetU64(offset_ptr: &payload_offset, dst: &value, count: 1))
5608 return false;
5609 uint64_t slide = LLDB_INVALID_ADDRESS;
5610 if (version > 1 && !m_data.GetU64(offset_ptr: &payload_offset, dst: &slide, count: 1))
5611 return false;
5612 if (value == LLDB_INVALID_ADDRESS && slide != LLDB_INVALID_ADDRESS) {
5613 value = slide;
5614 value_is_offset = true;
5615 }
5616
5617 if (m_data.CopyData(offset: payload_offset, length: sizeof(uuid_t), dst: raw_uuid) != 0) {
5618 uuid = UUID(raw_uuid, sizeof(uuid_t));
5619 // convert the "main bin spec" type into our
5620 // ObjectFile::BinaryType enum
5621 const char *typestr = "unrecognized type";
5622 switch (binspec_type) {
5623 case 0:
5624 type = eBinaryTypeUnknown;
5625 typestr = "uknown";
5626 break;
5627 case 1:
5628 type = eBinaryTypeKernel;
5629 typestr = "xnu kernel";
5630 break;
5631 case 2:
5632 type = eBinaryTypeUser;
5633 typestr = "userland dyld";
5634 break;
5635 case 3:
5636 type = eBinaryTypeStandalone;
5637 typestr = "standalone";
5638 break;
5639 }
5640 LLDB_LOGF(log,
5641 "LC_NOTE 'main bin spec' found, version %d type %d "
5642 "(%s), value 0x%" PRIx64 " value-is-slide==%s uuid %s",
5643 version, type, typestr, value,
5644 value_is_offset ? "true" : "false",
5645 uuid.GetAsString().c_str());
5646 if (!m_data.GetU32(offset_ptr: &payload_offset, dst: &log2_pagesize, count: 1))
5647 return false;
5648 if (version > 1 && !m_data.GetU32(offset_ptr: &payload_offset, dst: &platform, count: 1))
5649 return false;
5650 return true;
5651 }
5652 }
5653 }
5654 }
5655 return false;
5656}
5657
5658bool ObjectFileMachO::GetCorefileThreadExtraInfos(std::vector<tid_t> &tids) {
5659 tids.clear();
5660 ModuleSP module_sp(GetModule());
5661 if (module_sp) {
5662 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5663
5664 Log *log(GetLog(mask: LLDBLog::Object | LLDBLog::Process | LLDBLog::Thread));
5665 auto lc_notes = FindLC_NOTEByName(name: "process metadata");
5666 for (auto lc_note : lc_notes) {
5667 offset_t payload_offset = std::get<0>(t&: lc_note);
5668 offset_t strsize = std::get<1>(t&: lc_note);
5669 std::string buf(strsize, '\0');
5670 if (m_data.CopyData(offset: payload_offset, length: strsize, dst: buf.data()) != strsize) {
5671 LLDB_LOGF(log,
5672 "Unable to read %" PRIu64
5673 " bytes of 'process metadata' LC_NOTE JSON contents",
5674 strsize);
5675 return false;
5676 }
5677 while (buf.back() == '\0')
5678 buf.resize(n: buf.size() - 1);
5679 StructuredData::ObjectSP object_sp = StructuredData::ParseJSON(json_text: buf);
5680 StructuredData::Dictionary *dict = object_sp->GetAsDictionary();
5681 if (!dict) {
5682 LLDB_LOGF(log, "Unable to read 'process metadata' LC_NOTE, did not "
5683 "get a dictionary.");
5684 return false;
5685 }
5686 StructuredData::Array *threads;
5687 if (!dict->GetValueForKeyAsArray(key: "threads", result&: threads) || !threads) {
5688 LLDB_LOGF(log,
5689 "'process metadata' LC_NOTE does not have a 'threads' key");
5690 return false;
5691 }
5692 if (threads->GetSize() != GetNumThreadContexts()) {
5693 LLDB_LOGF(log, "Unable to read 'process metadata' LC_NOTE, number of "
5694 "threads does not match number of LC_THREADS.");
5695 return false;
5696 }
5697 const size_t num_threads = threads->GetSize();
5698 for (size_t i = 0; i < num_threads; i++) {
5699 std::optional<StructuredData::Dictionary *> maybe_thread =
5700 threads->GetItemAtIndexAsDictionary(idx: i);
5701 if (!maybe_thread) {
5702 LLDB_LOGF(log,
5703 "Unable to read 'process metadata' LC_NOTE, threads "
5704 "array does not have a dictionary at index %zu.",
5705 i);
5706 return false;
5707 }
5708 StructuredData::Dictionary *thread = *maybe_thread;
5709 tid_t tid = LLDB_INVALID_THREAD_ID;
5710 if (thread->GetValueForKeyAsInteger<tid_t>(key: "thread_id", result&: tid))
5711 if (tid == 0)
5712 tid = LLDB_INVALID_THREAD_ID;
5713 tids.push_back(x: tid);
5714 }
5715
5716 if (log) {
5717 StreamString logmsg;
5718 logmsg.Printf(format: "LC_NOTE 'process metadata' found: ");
5719 dict->Dump(s&: logmsg, /* pretty_print */ false);
5720 LLDB_LOGF(log, "%s", logmsg.GetData());
5721 }
5722 return true;
5723 }
5724 }
5725 return false;
5726}
5727
5728lldb::RegisterContextSP
5729ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
5730 lldb_private::Thread &thread) {
5731 lldb::RegisterContextSP reg_ctx_sp;
5732
5733 ModuleSP module_sp(GetModule());
5734 if (module_sp) {
5735 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5736 if (!m_thread_context_offsets_valid)
5737 GetNumThreadContexts();
5738
5739 const FileRangeArray::Entry *thread_context_file_range =
5740 m_thread_context_offsets.GetEntryAtIndex(i: idx);
5741 if (thread_context_file_range) {
5742
5743 DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
5744 thread_context_file_range->GetByteSize());
5745
5746 switch (m_header.cputype) {
5747 case llvm::MachO::CPU_TYPE_ARM64:
5748 case llvm::MachO::CPU_TYPE_ARM64_32:
5749 reg_ctx_sp =
5750 std::make_shared<RegisterContextDarwin_arm64_Mach>(args&: thread, args&: data);
5751 break;
5752
5753 case llvm::MachO::CPU_TYPE_ARM:
5754 reg_ctx_sp =
5755 std::make_shared<RegisterContextDarwin_arm_Mach>(args&: thread, args&: data);
5756 break;
5757
5758 case llvm::MachO::CPU_TYPE_I386:
5759 reg_ctx_sp =
5760 std::make_shared<RegisterContextDarwin_i386_Mach>(args&: thread, args&: data);
5761 break;
5762
5763 case llvm::MachO::CPU_TYPE_X86_64:
5764 reg_ctx_sp =
5765 std::make_shared<RegisterContextDarwin_x86_64_Mach>(args&: thread, args&: data);
5766 break;
5767 }
5768 }
5769 }
5770 return reg_ctx_sp;
5771}
5772
5773ObjectFile::Type ObjectFileMachO::CalculateType() {
5774 switch (m_header.filetype) {
5775 case MH_OBJECT: // 0x1u
5776 if (GetAddressByteSize() == 4) {
5777 // 32 bit kexts are just object files, but they do have a valid
5778 // UUID load command.
5779 if (GetUUID()) {
5780 // this checking for the UUID load command is not enough we could
5781 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5782 // this is required of kexts
5783 if (m_strata == eStrataInvalid)
5784 m_strata = eStrataKernel;
5785 return eTypeSharedLibrary;
5786 }
5787 }
5788 return eTypeObjectFile;
5789
5790 case MH_EXECUTE:
5791 return eTypeExecutable; // 0x2u
5792 case MH_FVMLIB:
5793 return eTypeSharedLibrary; // 0x3u
5794 case MH_CORE:
5795 return eTypeCoreFile; // 0x4u
5796 case MH_PRELOAD:
5797 return eTypeSharedLibrary; // 0x5u
5798 case MH_DYLIB:
5799 return eTypeSharedLibrary; // 0x6u
5800 case MH_DYLINKER:
5801 return eTypeDynamicLinker; // 0x7u
5802 case MH_BUNDLE:
5803 return eTypeSharedLibrary; // 0x8u
5804 case MH_DYLIB_STUB:
5805 return eTypeStubLibrary; // 0x9u
5806 case MH_DSYM:
5807 return eTypeDebugInfo; // 0xAu
5808 case MH_KEXT_BUNDLE:
5809 return eTypeSharedLibrary; // 0xBu
5810 default:
5811 break;
5812 }
5813 return eTypeUnknown;
5814}
5815
5816ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
5817 switch (m_header.filetype) {
5818 case MH_OBJECT: // 0x1u
5819 {
5820 // 32 bit kexts are just object files, but they do have a valid
5821 // UUID load command.
5822 if (GetUUID()) {
5823 // this checking for the UUID load command is not enough we could
5824 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5825 // this is required of kexts
5826 if (m_type == eTypeInvalid)
5827 m_type = eTypeSharedLibrary;
5828
5829 return eStrataKernel;
5830 }
5831 }
5832 return eStrataUnknown;
5833
5834 case MH_EXECUTE: // 0x2u
5835 // Check for the MH_DYLDLINK bit in the flags
5836 if (m_header.flags & MH_DYLDLINK) {
5837 return eStrataUser;
5838 } else {
5839 SectionList *section_list = GetSectionList();
5840 if (section_list) {
5841 static ConstString g_kld_section_name("__KLD");
5842 if (section_list->FindSectionByName(section_dstr: g_kld_section_name))
5843 return eStrataKernel;
5844 }
5845 }
5846 return eStrataRawImage;
5847
5848 case MH_FVMLIB:
5849 return eStrataUser; // 0x3u
5850 case MH_CORE:
5851 return eStrataUnknown; // 0x4u
5852 case MH_PRELOAD:
5853 return eStrataRawImage; // 0x5u
5854 case MH_DYLIB:
5855 return eStrataUser; // 0x6u
5856 case MH_DYLINKER:
5857 return eStrataUser; // 0x7u
5858 case MH_BUNDLE:
5859 return eStrataUser; // 0x8u
5860 case MH_DYLIB_STUB:
5861 return eStrataUser; // 0x9u
5862 case MH_DSYM:
5863 return eStrataUnknown; // 0xAu
5864 case MH_KEXT_BUNDLE:
5865 return eStrataKernel; // 0xBu
5866 default:
5867 break;
5868 }
5869 return eStrataUnknown;
5870}
5871
5872llvm::VersionTuple ObjectFileMachO::GetVersion() {
5873 ModuleSP module_sp(GetModule());
5874 if (module_sp) {
5875 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5876 llvm::MachO::dylib_command load_cmd;
5877 lldb::offset_t offset = MachHeaderSizeFromMagic(magic: m_header.magic);
5878 uint32_t version_cmd = 0;
5879 uint64_t version = 0;
5880 uint32_t i;
5881 for (i = 0; i < m_header.ncmds; ++i) {
5882 const lldb::offset_t cmd_offset = offset;
5883 if (m_data.GetU32(offset_ptr: &offset, dst: &load_cmd, count: 2) == nullptr)
5884 break;
5885
5886 if (load_cmd.cmd == LC_ID_DYLIB) {
5887 if (version_cmd == 0) {
5888 version_cmd = load_cmd.cmd;
5889 if (m_data.GetU32(offset_ptr: &offset, dst: &load_cmd.dylib, count: 4) == nullptr)
5890 break;
5891 version = load_cmd.dylib.current_version;
5892 }
5893 break; // Break for now unless there is another more complete version
5894 // number load command in the future.
5895 }
5896 offset = cmd_offset + load_cmd.cmdsize;
5897 }
5898
5899 if (version_cmd == LC_ID_DYLIB) {
5900 unsigned major = (version & 0xFFFF0000ull) >> 16;
5901 unsigned minor = (version & 0x0000FF00ull) >> 8;
5902 unsigned subminor = (version & 0x000000FFull);
5903 return llvm::VersionTuple(major, minor, subminor);
5904 }
5905 }
5906 return llvm::VersionTuple();
5907}
5908
5909ArchSpec ObjectFileMachO::GetArchitecture() {
5910 ModuleSP module_sp(GetModule());
5911 ArchSpec arch;
5912 if (module_sp) {
5913 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5914
5915 return GetArchitecture(module_sp, header: m_header, data: m_data,
5916 lc_offset: MachHeaderSizeFromMagic(magic: m_header.magic));
5917 }
5918 return arch;
5919}
5920
5921void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process,
5922 addr_t &base_addr, UUID &uuid) {
5923 uuid.Clear();
5924 base_addr = LLDB_INVALID_ADDRESS;
5925 if (process && process->GetDynamicLoader()) {
5926 DynamicLoader *dl = process->GetDynamicLoader();
5927 LazyBool using_shared_cache;
5928 LazyBool private_shared_cache;
5929 dl->GetSharedCacheInformation(base_address&: base_addr, uuid, using_shared_cache,
5930 private_shared_cache);
5931 }
5932 Log *log(GetLog(mask: LLDBLog::Symbols | LLDBLog::Process));
5933 LLDB_LOGF(
5934 log,
5935 "inferior process shared cache has a UUID of %s, base address 0x%" PRIx64,
5936 uuid.GetAsString().c_str(), base_addr);
5937}
5938
5939// From dyld SPI header dyld_process_info.h
5940typedef void *dyld_process_info;
5941struct lldb_copy__dyld_process_cache_info {
5942 uuid_t cacheUUID; // UUID of cache used by process
5943 uint64_t cacheBaseAddress; // load address of dyld shared cache
5944 bool noCache; // process is running without a dyld cache
5945 bool privateCache; // process is using a private copy of its dyld cache
5946};
5947
5948// #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with
5949// llvm enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile
5950// errors. So we need to use the actual underlying types of task_t and
5951// kern_return_t below.
5952extern "C" unsigned int /*task_t*/ mach_task_self();
5953
5954void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
5955 uuid.Clear();
5956 base_addr = LLDB_INVALID_ADDRESS;
5957
5958#if defined(__APPLE__)
5959 uint8_t *(*dyld_get_all_image_infos)(void);
5960 dyld_get_all_image_infos =
5961 (uint8_t * (*)()) dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5962 if (dyld_get_all_image_infos) {
5963 uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5964 if (dyld_all_image_infos_address) {
5965 uint32_t *version = (uint32_t *)
5966 dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5967 if (*version >= 13) {
5968 uuid_t *sharedCacheUUID_address = 0;
5969 int wordsize = sizeof(uint8_t *);
5970 if (wordsize == 8) {
5971 sharedCacheUUID_address =
5972 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5973 160); // sharedCacheUUID <mach-o/dyld_images.h>
5974 if (*version >= 15)
5975 base_addr =
5976 *(uint64_t
5977 *)((uint8_t *)dyld_all_image_infos_address +
5978 176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5979 } else {
5980 sharedCacheUUID_address =
5981 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5982 84); // sharedCacheUUID <mach-o/dyld_images.h>
5983 if (*version >= 15) {
5984 base_addr = 0;
5985 base_addr =
5986 *(uint32_t
5987 *)((uint8_t *)dyld_all_image_infos_address +
5988 100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5989 }
5990 }
5991 uuid = UUID(sharedCacheUUID_address, sizeof(uuid_t));
5992 }
5993 }
5994 } else {
5995 // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
5996 dyld_process_info (*dyld_process_info_create)(
5997 unsigned int /* task_t */ task, uint64_t timestamp,
5998 unsigned int /*kern_return_t*/ *kernelError);
5999 void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
6000 void (*dyld_process_info_release)(dyld_process_info info);
6001
6002 dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t,
6003 unsigned int /*kern_return_t*/ *))
6004 dlsym(RTLD_DEFAULT, "_dyld_process_info_create");
6005 dyld_process_info_get_cache = (void (*)(void *, void *))dlsym(
6006 RTLD_DEFAULT, "_dyld_process_info_get_cache");
6007 dyld_process_info_release =
6008 (void (*)(void *))dlsym(RTLD_DEFAULT, "_dyld_process_info_release");
6009
6010 if (dyld_process_info_create && dyld_process_info_get_cache) {
6011 unsigned int /*kern_return_t */ kern_ret;
6012 dyld_process_info process_info =
6013 dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
6014 if (process_info) {
6015 struct lldb_copy__dyld_process_cache_info sc_info;
6016 memset(&sc_info, 0, sizeof(struct lldb_copy__dyld_process_cache_info));
6017 dyld_process_info_get_cache(process_info, &sc_info);
6018 if (sc_info.cacheBaseAddress != 0) {
6019 base_addr = sc_info.cacheBaseAddress;
6020 uuid = UUID(sc_info.cacheUUID, sizeof(uuid_t));
6021 }
6022 dyld_process_info_release(process_info);
6023 }
6024 }
6025 }
6026 Log *log(GetLog(LLDBLog::Symbols | LLDBLog::Process));
6027 if (log && uuid.IsValid())
6028 LLDB_LOGF(log,
6029 "lldb's in-memory shared cache has a UUID of %s base address of "
6030 "0x%" PRIx64,
6031 uuid.GetAsString().c_str(), base_addr);
6032#endif
6033}
6034
6035static llvm::VersionTuple FindMinimumVersionInfo(DataExtractor &data,
6036 lldb::offset_t offset,
6037 size_t ncmds) {
6038 for (size_t i = 0; i < ncmds; i++) {
6039 const lldb::offset_t load_cmd_offset = offset;
6040 llvm::MachO::load_command lc = {};
6041 if (data.GetU32(offset_ptr: &offset, dst: &lc.cmd, count: 2) == nullptr)
6042 break;
6043
6044 uint32_t version = 0;
6045 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
6046 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
6047 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
6048 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
6049 // struct version_min_command {
6050 // uint32_t cmd; // LC_VERSION_MIN_*
6051 // uint32_t cmdsize;
6052 // uint32_t version; // X.Y.Z encoded in nibbles xxxx.yy.zz
6053 // uint32_t sdk;
6054 // };
6055 // We want to read version.
6056 version = data.GetU32(offset_ptr: &offset);
6057 } else if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
6058 // struct build_version_command {
6059 // uint32_t cmd; // LC_BUILD_VERSION
6060 // uint32_t cmdsize;
6061 // uint32_t platform;
6062 // uint32_t minos; // X.Y.Z encoded in nibbles xxxx.yy.zz
6063 // uint32_t sdk;
6064 // uint32_t ntools;
6065 // };
6066 // We want to read minos.
6067 offset += sizeof(uint32_t); // Skip over platform
6068 version = data.GetU32(offset_ptr: &offset); // Extract minos
6069 }
6070
6071 if (version) {
6072 const uint32_t xxxx = version >> 16;
6073 const uint32_t yy = (version >> 8) & 0xffu;
6074 const uint32_t zz = version & 0xffu;
6075 if (xxxx)
6076 return llvm::VersionTuple(xxxx, yy, zz);
6077 }
6078 offset = load_cmd_offset + lc.cmdsize;
6079 }
6080 return llvm::VersionTuple();
6081}
6082
6083llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() {
6084 if (!m_min_os_version)
6085 m_min_os_version = FindMinimumVersionInfo(
6086 data&: m_data, offset: MachHeaderSizeFromMagic(magic: m_header.magic), ncmds: m_header.ncmds);
6087 return *m_min_os_version;
6088}
6089
6090llvm::VersionTuple ObjectFileMachO::GetSDKVersion() {
6091 if (!m_sdk_versions)
6092 m_sdk_versions = FindMinimumVersionInfo(
6093 data&: m_data, offset: MachHeaderSizeFromMagic(magic: m_header.magic), ncmds: m_header.ncmds);
6094 return *m_sdk_versions;
6095}
6096
6097bool ObjectFileMachO::GetIsDynamicLinkEditor() {
6098 return m_header.filetype == llvm::MachO::MH_DYLINKER;
6099}
6100
6101bool ObjectFileMachO::CanTrustAddressRanges() {
6102 // Dsymutil guarantees that the .debug_aranges accelerator is complete and can
6103 // be trusted by LLDB.
6104 return m_header.filetype == llvm::MachO::MH_DSYM;
6105}
6106
6107bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
6108 return m_allow_assembly_emulation_unwind_plans;
6109}
6110
6111Section *ObjectFileMachO::GetMachHeaderSection() {
6112 // Find the first address of the mach header which is the first non-zero file
6113 // sized section whose file offset is zero. This is the base file address of
6114 // the mach-o file which can be subtracted from the vmaddr of the other
6115 // segments found in memory and added to the load address
6116 ModuleSP module_sp = GetModule();
6117 if (!module_sp)
6118 return nullptr;
6119 SectionList *section_list = GetSectionList();
6120 if (!section_list)
6121 return nullptr;
6122
6123 // Some binaries can have a TEXT segment with a non-zero file offset.
6124 // Binaries in the shared cache are one example. Some hand-generated
6125 // binaries may not be laid out in the normal TEXT,DATA,LC_SYMTAB order
6126 // in the file, even though they're laid out correctly in vmaddr terms.
6127 SectionSP text_segment_sp =
6128 section_list->FindSectionByName(section_dstr: GetSegmentNameTEXT());
6129 if (text_segment_sp.get() && SectionIsLoadable(section: text_segment_sp.get()))
6130 return text_segment_sp.get();
6131
6132 const size_t num_sections = section_list->GetSize();
6133 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6134 Section *section = section_list->GetSectionAtIndex(idx: sect_idx).get();
6135 if (section->GetFileOffset() == 0 && SectionIsLoadable(section))
6136 return section;
6137 }
6138
6139 return nullptr;
6140}
6141
6142bool ObjectFileMachO::SectionIsLoadable(const Section *section) {
6143 if (!section)
6144 return false;
6145 const bool is_dsym = (m_header.filetype == MH_DSYM);
6146 if (section->GetFileSize() == 0 && !is_dsym &&
6147 section->GetName() != GetSegmentNameDATA())
6148 return false;
6149 if (section->IsThreadSpecific())
6150 return false;
6151 if (GetModule().get() != section->GetModule().get())
6152 return false;
6153 // firmware style binaries with llvm gcov segment do
6154 // not have that segment mapped into memory.
6155 if (section->GetName() == GetSegmentNameLLVM_COV()) {
6156 const Strata strata = GetStrata();
6157 if (strata == eStrataKernel || strata == eStrataRawImage)
6158 return false;
6159 }
6160 // Be careful with __LINKEDIT and __DWARF segments
6161 if (section->GetName() == GetSegmentNameLINKEDIT() ||
6162 section->GetName() == GetSegmentNameDWARF()) {
6163 // Only map __LINKEDIT and __DWARF if we have an in memory image and
6164 // this isn't a kernel binary like a kext or mach_kernel.
6165 const bool is_memory_image = (bool)m_process_wp.lock();
6166 const Strata strata = GetStrata();
6167 if (is_memory_image == false || strata == eStrataKernel)
6168 return false;
6169 }
6170 return true;
6171}
6172
6173lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
6174 lldb::addr_t header_load_address, const Section *header_section,
6175 const Section *section) {
6176 ModuleSP module_sp = GetModule();
6177 if (module_sp && header_section && section &&
6178 header_load_address != LLDB_INVALID_ADDRESS) {
6179 lldb::addr_t file_addr = header_section->GetFileAddress();
6180 if (file_addr != LLDB_INVALID_ADDRESS && SectionIsLoadable(section))
6181 return section->GetFileAddress() - file_addr + header_load_address;
6182 }
6183 return LLDB_INVALID_ADDRESS;
6184}
6185
6186bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
6187 bool value_is_offset) {
6188 ModuleSP module_sp = GetModule();
6189 if (!module_sp)
6190 return false;
6191
6192 SectionList *section_list = GetSectionList();
6193 if (!section_list)
6194 return false;
6195
6196 size_t num_loaded_sections = 0;
6197 const size_t num_sections = section_list->GetSize();
6198
6199 // Warn if some top-level segments map to the same address. The binary may be
6200 // malformed.
6201 const bool warn_multiple = true;
6202
6203 if (value_is_offset) {
6204 // "value" is an offset to apply to each top level segment
6205 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6206 // Iterate through the object file sections to find all of the
6207 // sections that size on disk (to avoid __PAGEZERO) and load them
6208 SectionSP section_sp(section_list->GetSectionAtIndex(idx: sect_idx));
6209 if (SectionIsLoadable(section: section_sp.get()))
6210 if (target.GetSectionLoadList().SetSectionLoadAddress(
6211 section_sp, load_addr: section_sp->GetFileAddress() + value,
6212 warn_multiple))
6213 ++num_loaded_sections;
6214 }
6215 } else {
6216 // "value" is the new base address of the mach_header, adjust each
6217 // section accordingly
6218
6219 Section *mach_header_section = GetMachHeaderSection();
6220 if (mach_header_section) {
6221 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6222 SectionSP section_sp(section_list->GetSectionAtIndex(idx: sect_idx));
6223
6224 lldb::addr_t section_load_addr =
6225 CalculateSectionLoadAddressForMemoryImage(
6226 header_load_address: value, header_section: mach_header_section, section: section_sp.get());
6227 if (section_load_addr != LLDB_INVALID_ADDRESS) {
6228 if (target.GetSectionLoadList().SetSectionLoadAddress(
6229 section_sp, load_addr: section_load_addr, warn_multiple))
6230 ++num_loaded_sections;
6231 }
6232 }
6233 }
6234 }
6235 return num_loaded_sections > 0;
6236}
6237
6238struct all_image_infos_header {
6239 uint32_t version; // currently 1
6240 uint32_t imgcount; // number of binary images
6241 uint64_t entries_fileoff; // file offset in the corefile of where the array of
6242 // struct entry's begin.
6243 uint32_t entries_size; // size of 'struct entry'.
6244 uint32_t unused;
6245};
6246
6247struct image_entry {
6248 uint64_t filepath_offset; // offset in corefile to c-string of the file path,
6249 // UINT64_MAX if unavailable.
6250 uuid_t uuid; // uint8_t[16]. should be set to all zeroes if
6251 // uuid is unknown.
6252 uint64_t load_address; // UINT64_MAX if unknown.
6253 uint64_t seg_addrs_offset; // offset to the array of struct segment_vmaddr's.
6254 uint32_t segment_count; // The number of segments for this binary.
6255 uint32_t unused;
6256
6257 image_entry() {
6258 filepath_offset = UINT64_MAX;
6259 memset(s: &uuid, c: 0, n: sizeof(uuid_t));
6260 segment_count = 0;
6261 load_address = UINT64_MAX;
6262 seg_addrs_offset = UINT64_MAX;
6263 unused = 0;
6264 }
6265 image_entry(const image_entry &rhs) {
6266 filepath_offset = rhs.filepath_offset;
6267 memcpy(dest: &uuid, src: &rhs.uuid, n: sizeof(uuid_t));
6268 segment_count = rhs.segment_count;
6269 seg_addrs_offset = rhs.seg_addrs_offset;
6270 load_address = rhs.load_address;
6271 unused = rhs.unused;
6272 }
6273};
6274
6275struct segment_vmaddr {
6276 char segname[16];
6277 uint64_t vmaddr;
6278 uint64_t unused;
6279
6280 segment_vmaddr() {
6281 memset(s: &segname, c: 0, n: 16);
6282 vmaddr = UINT64_MAX;
6283 unused = 0;
6284 }
6285 segment_vmaddr(const segment_vmaddr &rhs) {
6286 memcpy(dest: &segname, src: &rhs.segname, n: 16);
6287 vmaddr = rhs.vmaddr;
6288 unused = rhs.unused;
6289 }
6290};
6291
6292// Write the payload for the "all image infos" LC_NOTE into
6293// the supplied all_image_infos_payload, assuming that this
6294// will be written into the corefile starting at
6295// initial_file_offset.
6296//
6297// The placement of this payload is a little tricky. We're
6298// laying this out as
6299//
6300// 1. header (struct all_image_info_header)
6301// 2. Array of fixed-size (struct image_entry)'s, one
6302// per binary image present in the process.
6303// 3. Arrays of (struct segment_vmaddr)'s, a varying number
6304// for each binary image.
6305// 4. Variable length c-strings of binary image filepaths,
6306// one per binary.
6307//
6308// To compute where everything will be laid out in the
6309// payload, we need to iterate over the images and calculate
6310// how many segment_vmaddr structures each image will need,
6311// and how long each image's filepath c-string is. There
6312// are some multiple passes over the image list while calculating
6313// everything.
6314
6315static offset_t CreateAllImageInfosPayload(
6316 const lldb::ProcessSP &process_sp, offset_t initial_file_offset,
6317 StreamString &all_image_infos_payload, SaveCoreStyle core_style) {
6318 Target &target = process_sp->GetTarget();
6319 ModuleList modules = target.GetImages();
6320
6321 // stack-only corefiles have no reason to include binaries that
6322 // are not executing; we're trying to make the smallest corefile
6323 // we can, so leave the rest out.
6324 if (core_style == SaveCoreStyle::eSaveCoreStackOnly)
6325 modules.Clear();
6326
6327 std::set<std::string> executing_uuids;
6328 ThreadList &thread_list(process_sp->GetThreadList());
6329 for (uint32_t i = 0; i < thread_list.GetSize(); i++) {
6330 ThreadSP thread_sp = thread_list.GetThreadAtIndex(idx: i);
6331 uint32_t stack_frame_count = thread_sp->GetStackFrameCount();
6332 for (uint32_t j = 0; j < stack_frame_count; j++) {
6333 StackFrameSP stack_frame_sp = thread_sp->GetStackFrameAtIndex(idx: j);
6334 Address pc = stack_frame_sp->GetFrameCodeAddress();
6335 ModuleSP module_sp = pc.GetModule();
6336 if (module_sp) {
6337 UUID uuid = module_sp->GetUUID();
6338 if (uuid.IsValid()) {
6339 executing_uuids.insert(x: uuid.GetAsString());
6340 modules.AppendIfNeeded(new_module: module_sp);
6341 }
6342 }
6343 }
6344 }
6345 size_t modules_count = modules.GetSize();
6346
6347 struct all_image_infos_header infos;
6348 infos.version = 1;
6349 infos.imgcount = modules_count;
6350 infos.entries_size = sizeof(image_entry);
6351 infos.entries_fileoff = initial_file_offset + sizeof(all_image_infos_header);
6352 infos.unused = 0;
6353
6354 all_image_infos_payload.PutHex32(uvalue: infos.version);
6355 all_image_infos_payload.PutHex32(uvalue: infos.imgcount);
6356 all_image_infos_payload.PutHex64(uvalue: infos.entries_fileoff);
6357 all_image_infos_payload.PutHex32(uvalue: infos.entries_size);
6358 all_image_infos_payload.PutHex32(uvalue: infos.unused);
6359
6360 // First create the structures for all of the segment name+vmaddr vectors
6361 // for each module, so we will know the size of them as we add the
6362 // module entries.
6363 std::vector<std::vector<segment_vmaddr>> modules_segment_vmaddrs;
6364 for (size_t i = 0; i < modules_count; i++) {
6365 ModuleSP module = modules.GetModuleAtIndex(idx: i);
6366
6367 SectionList *sections = module->GetSectionList();
6368 size_t sections_count = sections->GetSize();
6369 std::vector<segment_vmaddr> segment_vmaddrs;
6370 for (size_t j = 0; j < sections_count; j++) {
6371 SectionSP section = sections->GetSectionAtIndex(idx: j);
6372 if (!section->GetParent().get()) {
6373 addr_t vmaddr = section->GetLoadBaseAddress(target: &target);
6374 if (vmaddr == LLDB_INVALID_ADDRESS)
6375 continue;
6376 ConstString name = section->GetName();
6377 segment_vmaddr seg_vmaddr;
6378 // This is the uncommon case where strncpy is exactly
6379 // the right one, doesn't need to be nul terminated.
6380 // The segment name in a Mach-O LC_SEGMENT/LC_SEGMENT_64 is char[16] and
6381 // is not guaranteed to be nul-terminated if all 16 characters are
6382 // used.
6383 // coverity[buffer_size_warning]
6384 strncpy(dest: seg_vmaddr.segname, src: name.AsCString(),
6385 n: sizeof(seg_vmaddr.segname));
6386 seg_vmaddr.vmaddr = vmaddr;
6387 seg_vmaddr.unused = 0;
6388 segment_vmaddrs.push_back(x: seg_vmaddr);
6389 }
6390 }
6391 modules_segment_vmaddrs.push_back(x: segment_vmaddrs);
6392 }
6393
6394 offset_t size_of_vmaddr_structs = 0;
6395 for (size_t i = 0; i < modules_segment_vmaddrs.size(); i++) {
6396 size_of_vmaddr_structs +=
6397 modules_segment_vmaddrs[i].size() * sizeof(segment_vmaddr);
6398 }
6399
6400 offset_t size_of_filepath_cstrings = 0;
6401 for (size_t i = 0; i < modules_count; i++) {
6402 ModuleSP module_sp = modules.GetModuleAtIndex(idx: i);
6403 size_of_filepath_cstrings += module_sp->GetFileSpec().GetPath().size() + 1;
6404 }
6405
6406 // Calculate the file offsets of our "all image infos" payload in the
6407 // corefile. initial_file_offset the original value passed in to this method.
6408
6409 offset_t start_of_entries =
6410 initial_file_offset + sizeof(all_image_infos_header);
6411 offset_t start_of_seg_vmaddrs =
6412 start_of_entries + sizeof(image_entry) * modules_count;
6413 offset_t start_of_filenames = start_of_seg_vmaddrs + size_of_vmaddr_structs;
6414
6415 offset_t final_file_offset = start_of_filenames + size_of_filepath_cstrings;
6416
6417 // Now write the one-per-module 'struct image_entry' into the
6418 // StringStream; keep track of where the struct segment_vmaddr
6419 // entries for each module will end up in the corefile.
6420
6421 offset_t current_string_offset = start_of_filenames;
6422 offset_t current_segaddrs_offset = start_of_seg_vmaddrs;
6423 std::vector<struct image_entry> image_entries;
6424 for (size_t i = 0; i < modules_count; i++) {
6425 ModuleSP module_sp = modules.GetModuleAtIndex(idx: i);
6426
6427 struct image_entry ent;
6428 memcpy(dest: &ent.uuid, src: module_sp->GetUUID().GetBytes().data(), n: sizeof(ent.uuid));
6429 if (modules_segment_vmaddrs[i].size() > 0) {
6430 ent.segment_count = modules_segment_vmaddrs[i].size();
6431 ent.seg_addrs_offset = current_segaddrs_offset;
6432 }
6433 ent.filepath_offset = current_string_offset;
6434 ObjectFile *objfile = module_sp->GetObjectFile();
6435 if (objfile) {
6436 Address base_addr(objfile->GetBaseAddress());
6437 if (base_addr.IsValid()) {
6438 ent.load_address = base_addr.GetLoadAddress(target: &target);
6439 }
6440 }
6441
6442 all_image_infos_payload.PutHex64(uvalue: ent.filepath_offset);
6443 all_image_infos_payload.PutRawBytes(s: ent.uuid, src_len: sizeof(ent.uuid));
6444 all_image_infos_payload.PutHex64(uvalue: ent.load_address);
6445 all_image_infos_payload.PutHex64(uvalue: ent.seg_addrs_offset);
6446 all_image_infos_payload.PutHex32(uvalue: ent.segment_count);
6447
6448 if (executing_uuids.find(x: module_sp->GetUUID().GetAsString()) !=
6449 executing_uuids.end())
6450 all_image_infos_payload.PutHex32(uvalue: 1);
6451 else
6452 all_image_infos_payload.PutHex32(uvalue: 0);
6453
6454 current_segaddrs_offset += ent.segment_count * sizeof(segment_vmaddr);
6455 current_string_offset += module_sp->GetFileSpec().GetPath().size() + 1;
6456 }
6457
6458 // Now write the struct segment_vmaddr entries into the StringStream.
6459
6460 for (size_t i = 0; i < modules_segment_vmaddrs.size(); i++) {
6461 if (modules_segment_vmaddrs[i].size() == 0)
6462 continue;
6463 for (struct segment_vmaddr segvm : modules_segment_vmaddrs[i]) {
6464 all_image_infos_payload.PutRawBytes(s: segvm.segname, src_len: sizeof(segvm.segname));
6465 all_image_infos_payload.PutHex64(uvalue: segvm.vmaddr);
6466 all_image_infos_payload.PutHex64(uvalue: segvm.unused);
6467 }
6468 }
6469
6470 for (size_t i = 0; i < modules_count; i++) {
6471 ModuleSP module_sp = modules.GetModuleAtIndex(idx: i);
6472 std::string filepath = module_sp->GetFileSpec().GetPath();
6473 all_image_infos_payload.PutRawBytes(s: filepath.data(), src_len: filepath.size() + 1);
6474 }
6475
6476 return final_file_offset;
6477}
6478
6479// Temp struct used to combine contiguous memory regions with
6480// identical permissions.
6481struct page_object {
6482 addr_t addr;
6483 addr_t size;
6484 uint32_t prot;
6485};
6486
6487bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
6488 const FileSpec &outfile,
6489 lldb::SaveCoreStyle &core_style, Status &error) {
6490 if (!process_sp)
6491 return false;
6492
6493 // Default on macOS is to create a dirty-memory-only corefile.
6494 if (core_style == SaveCoreStyle::eSaveCoreUnspecified)
6495 core_style = SaveCoreStyle::eSaveCoreDirtyOnly;
6496
6497 Target &target = process_sp->GetTarget();
6498 const ArchSpec target_arch = target.GetArchitecture();
6499 const llvm::Triple &target_triple = target_arch.GetTriple();
6500 if (target_triple.getVendor() == llvm::Triple::Apple &&
6501 (target_triple.getOS() == llvm::Triple::MacOSX ||
6502 target_triple.getOS() == llvm::Triple::IOS ||
6503 target_triple.getOS() == llvm::Triple::WatchOS ||
6504 target_triple.getOS() == llvm::Triple::TvOS ||
6505 target_triple.getOS() == llvm::Triple::XROS)) {
6506 // NEED_BRIDGEOS_TRIPLE target_triple.getOS() == llvm::Triple::BridgeOS))
6507 // {
6508 bool make_core = false;
6509 switch (target_arch.GetMachine()) {
6510 case llvm::Triple::aarch64:
6511 case llvm::Triple::aarch64_32:
6512 case llvm::Triple::arm:
6513 case llvm::Triple::thumb:
6514 case llvm::Triple::x86:
6515 case llvm::Triple::x86_64:
6516 make_core = true;
6517 break;
6518 default:
6519 error.SetErrorStringWithFormat("unsupported core architecture: %s",
6520 target_triple.str().c_str());
6521 break;
6522 }
6523
6524 if (make_core) {
6525 Process::CoreFileMemoryRanges core_ranges;
6526 error = process_sp->CalculateCoreFileSaveRanges(core_style, ranges&: core_ranges);
6527 if (error.Success()) {
6528 const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
6529 const ByteOrder byte_order = target_arch.GetByteOrder();
6530 std::vector<llvm::MachO::segment_command_64> segment_load_commands;
6531 for (const auto &core_range : core_ranges) {
6532 uint32_t cmd_type = LC_SEGMENT_64;
6533 uint32_t segment_size = sizeof(llvm::MachO::segment_command_64);
6534 if (addr_byte_size == 4) {
6535 cmd_type = LC_SEGMENT;
6536 segment_size = sizeof(llvm::MachO::segment_command);
6537 }
6538 // Skip any ranges with no read/write/execute permissions and empty
6539 // ranges.
6540 if (core_range.lldb_permissions == 0 || core_range.range.size() == 0)
6541 continue;
6542 uint32_t vm_prot = 0;
6543 if (core_range.lldb_permissions & ePermissionsReadable)
6544 vm_prot |= VM_PROT_READ;
6545 if (core_range.lldb_permissions & ePermissionsWritable)
6546 vm_prot |= VM_PROT_WRITE;
6547 if (core_range.lldb_permissions & ePermissionsExecutable)
6548 vm_prot |= VM_PROT_EXECUTE;
6549 const addr_t vm_addr = core_range.range.start();
6550 const addr_t vm_size = core_range.range.size();
6551 llvm::MachO::segment_command_64 segment = {
6552 .cmd: cmd_type, // uint32_t cmd;
6553 .cmdsize: segment_size, // uint32_t cmdsize;
6554 .segname: {0}, // char segname[16];
6555 .vmaddr: vm_addr, // uint64_t vmaddr; // uint32_t for 32-bit Mach-O
6556 .vmsize: vm_size, // uint64_t vmsize; // uint32_t for 32-bit Mach-O
6557 .fileoff: 0, // uint64_t fileoff; // uint32_t for 32-bit Mach-O
6558 .filesize: vm_size, // uint64_t filesize; // uint32_t for 32-bit Mach-O
6559 .maxprot: vm_prot, // uint32_t maxprot;
6560 .initprot: vm_prot, // uint32_t initprot;
6561 .nsects: 0, // uint32_t nsects;
6562 .flags: 0}; // uint32_t flags;
6563 segment_load_commands.push_back(x: segment);
6564 }
6565
6566 StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
6567
6568 llvm::MachO::mach_header_64 mach_header;
6569 mach_header.magic = addr_byte_size == 8 ? MH_MAGIC_64 : MH_MAGIC;
6570 mach_header.cputype = target_arch.GetMachOCPUType();
6571 mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
6572 mach_header.filetype = MH_CORE;
6573 mach_header.ncmds = segment_load_commands.size();
6574 mach_header.flags = 0;
6575 mach_header.reserved = 0;
6576 ThreadList &thread_list = process_sp->GetThreadList();
6577 const uint32_t num_threads = thread_list.GetSize();
6578
6579 // Make an array of LC_THREAD data items. Each one contains the
6580 // contents of the LC_THREAD load command. The data doesn't contain
6581 // the load command + load command size, we will add the load command
6582 // and load command size as we emit the data.
6583 std::vector<StreamString> LC_THREAD_datas(num_threads);
6584 for (auto &LC_THREAD_data : LC_THREAD_datas) {
6585 LC_THREAD_data.GetFlags().Set(Stream::eBinary);
6586 LC_THREAD_data.SetAddressByteSize(addr_byte_size);
6587 LC_THREAD_data.SetByteOrder(byte_order);
6588 }
6589 for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
6590 ThreadSP thread_sp(thread_list.GetThreadAtIndex(idx: thread_idx));
6591 if (thread_sp) {
6592 switch (mach_header.cputype) {
6593 case llvm::MachO::CPU_TYPE_ARM64:
6594 case llvm::MachO::CPU_TYPE_ARM64_32:
6595 RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
6596 thread: thread_sp.get(), data&: LC_THREAD_datas[thread_idx]);
6597 break;
6598
6599 case llvm::MachO::CPU_TYPE_ARM:
6600 RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
6601 thread: thread_sp.get(), data&: LC_THREAD_datas[thread_idx]);
6602 break;
6603
6604 case llvm::MachO::CPU_TYPE_I386:
6605 RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
6606 thread: thread_sp.get(), data&: LC_THREAD_datas[thread_idx]);
6607 break;
6608
6609 case llvm::MachO::CPU_TYPE_X86_64:
6610 RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
6611 thread: thread_sp.get(), data&: LC_THREAD_datas[thread_idx]);
6612 break;
6613 }
6614 }
6615 }
6616
6617 // The size of the load command is the size of the segments...
6618 if (addr_byte_size == 8) {
6619 mach_header.sizeofcmds = segment_load_commands.size() *
6620 sizeof(llvm::MachO::segment_command_64);
6621 } else {
6622 mach_header.sizeofcmds = segment_load_commands.size() *
6623 sizeof(llvm::MachO::segment_command);
6624 }
6625
6626 // and the size of all LC_THREAD load command
6627 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6628 ++mach_header.ncmds;
6629 mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
6630 }
6631
6632 // Bits will be set to indicate which bits are NOT used in
6633 // addressing in this process or 0 for unknown.
6634 uint64_t address_mask = process_sp->GetCodeAddressMask();
6635 if (address_mask != LLDB_INVALID_ADDRESS_MASK) {
6636 // LC_NOTE "addrable bits"
6637 mach_header.ncmds++;
6638 mach_header.sizeofcmds += sizeof(llvm::MachO::note_command);
6639 }
6640
6641 // LC_NOTE "process metadata"
6642 mach_header.ncmds++;
6643 mach_header.sizeofcmds += sizeof(llvm::MachO::note_command);
6644
6645 // LC_NOTE "all image infos"
6646 mach_header.ncmds++;
6647 mach_header.sizeofcmds += sizeof(llvm::MachO::note_command);
6648
6649 // Write the mach header
6650 buffer.PutHex32(uvalue: mach_header.magic);
6651 buffer.PutHex32(uvalue: mach_header.cputype);
6652 buffer.PutHex32(uvalue: mach_header.cpusubtype);
6653 buffer.PutHex32(uvalue: mach_header.filetype);
6654 buffer.PutHex32(uvalue: mach_header.ncmds);
6655 buffer.PutHex32(uvalue: mach_header.sizeofcmds);
6656 buffer.PutHex32(uvalue: mach_header.flags);
6657 if (addr_byte_size == 8) {
6658 buffer.PutHex32(uvalue: mach_header.reserved);
6659 }
6660
6661 // Skip the mach header and all load commands and align to the next
6662 // 0x1000 byte boundary
6663 addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
6664
6665 file_offset = llvm::alignTo(Value: file_offset, Align: 16);
6666 std::vector<std::unique_ptr<LCNoteEntry>> lc_notes;
6667
6668 // Add "addrable bits" LC_NOTE when an address mask is available
6669 if (address_mask != LLDB_INVALID_ADDRESS_MASK) {
6670 std::unique_ptr<LCNoteEntry> addrable_bits_lcnote_up(
6671 new LCNoteEntry(addr_byte_size, byte_order));
6672 addrable_bits_lcnote_up->name = "addrable bits";
6673 addrable_bits_lcnote_up->payload_file_offset = file_offset;
6674 int bits = std::bitset<64>(~address_mask).count();
6675 addrable_bits_lcnote_up->payload.PutHex32(uvalue: 4); // version
6676 addrable_bits_lcnote_up->payload.PutHex32(
6677 uvalue: bits); // # of bits used for low addresses
6678 addrable_bits_lcnote_up->payload.PutHex32(
6679 uvalue: bits); // # of bits used for high addresses
6680 addrable_bits_lcnote_up->payload.PutHex32(uvalue: 0); // reserved
6681
6682 file_offset += addrable_bits_lcnote_up->payload.GetSize();
6683
6684 lc_notes.push_back(x: std::move(addrable_bits_lcnote_up));
6685 }
6686
6687 // Add "process metadata" LC_NOTE
6688 std::unique_ptr<LCNoteEntry> thread_extrainfo_lcnote_up(
6689 new LCNoteEntry(addr_byte_size, byte_order));
6690 thread_extrainfo_lcnote_up->name = "process metadata";
6691 thread_extrainfo_lcnote_up->payload_file_offset = file_offset;
6692
6693 StructuredData::DictionarySP dict(
6694 std::make_shared<StructuredData::Dictionary>());
6695 StructuredData::ArraySP threads(
6696 std::make_shared<StructuredData::Array>());
6697 for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
6698 ThreadSP thread_sp(thread_list.GetThreadAtIndex(idx: thread_idx));
6699 StructuredData::DictionarySP thread(
6700 std::make_shared<StructuredData::Dictionary>());
6701 thread->AddIntegerItem(key: "thread_id", value: thread_sp->GetID());
6702 threads->AddItem(item: thread);
6703 }
6704 dict->AddItem(key: "threads", value_sp: threads);
6705 StreamString strm;
6706 dict->Dump(s&: strm, /* pretty */ pretty_print: false);
6707 thread_extrainfo_lcnote_up->payload.PutRawBytes(s: strm.GetData(),
6708 src_len: strm.GetSize());
6709
6710 file_offset += thread_extrainfo_lcnote_up->payload.GetSize();
6711 file_offset = llvm::alignTo(Value: file_offset, Align: 16);
6712 lc_notes.push_back(x: std::move(thread_extrainfo_lcnote_up));
6713
6714 // Add "all image infos" LC_NOTE
6715 std::unique_ptr<LCNoteEntry> all_image_infos_lcnote_up(
6716 new LCNoteEntry(addr_byte_size, byte_order));
6717 all_image_infos_lcnote_up->name = "all image infos";
6718 all_image_infos_lcnote_up->payload_file_offset = file_offset;
6719 file_offset = CreateAllImageInfosPayload(
6720 process_sp, initial_file_offset: file_offset, all_image_infos_payload&: all_image_infos_lcnote_up->payload,
6721 core_style);
6722 lc_notes.push_back(x: std::move(all_image_infos_lcnote_up));
6723
6724 // Add LC_NOTE load commands
6725 for (auto &lcnote : lc_notes) {
6726 // Add the LC_NOTE load command to the file.
6727 buffer.PutHex32(uvalue: LC_NOTE);
6728 buffer.PutHex32(uvalue: sizeof(llvm::MachO::note_command));
6729 char namebuf[16];
6730 memset(s: namebuf, c: 0, n: sizeof(namebuf));
6731 // This is the uncommon case where strncpy is exactly
6732 // the right one, doesn't need to be nul terminated.
6733 // LC_NOTE name field is char[16] and is not guaranteed to be
6734 // nul-terminated.
6735 // coverity[buffer_size_warning]
6736 strncpy(dest: namebuf, src: lcnote->name.c_str(), n: sizeof(namebuf));
6737 buffer.PutRawBytes(s: namebuf, src_len: sizeof(namebuf));
6738 buffer.PutHex64(uvalue: lcnote->payload_file_offset);
6739 buffer.PutHex64(uvalue: lcnote->payload.GetSize());
6740 }
6741
6742 // Align to 4096-byte page boundary for the LC_SEGMENTs.
6743 file_offset = llvm::alignTo(Value: file_offset, Align: 4096);
6744
6745 for (auto &segment : segment_load_commands) {
6746 segment.fileoff = file_offset;
6747 file_offset += segment.filesize;
6748 }
6749
6750 // Write out all of the LC_THREAD load commands
6751 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6752 const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6753 buffer.PutHex32(uvalue: LC_THREAD);
6754 buffer.PutHex32(uvalue: 8 + LC_THREAD_data_size); // cmd + cmdsize + data
6755 buffer.Write(src: LC_THREAD_data.GetString().data(), src_len: LC_THREAD_data_size);
6756 }
6757
6758 // Write out all of the segment load commands
6759 for (const auto &segment : segment_load_commands) {
6760 buffer.PutHex32(uvalue: segment.cmd);
6761 buffer.PutHex32(uvalue: segment.cmdsize);
6762 buffer.PutRawBytes(s: segment.segname, src_len: sizeof(segment.segname));
6763 if (addr_byte_size == 8) {
6764 buffer.PutHex64(uvalue: segment.vmaddr);
6765 buffer.PutHex64(uvalue: segment.vmsize);
6766 buffer.PutHex64(uvalue: segment.fileoff);
6767 buffer.PutHex64(uvalue: segment.filesize);
6768 } else {
6769 buffer.PutHex32(uvalue: static_cast<uint32_t>(segment.vmaddr));
6770 buffer.PutHex32(uvalue: static_cast<uint32_t>(segment.vmsize));
6771 buffer.PutHex32(uvalue: static_cast<uint32_t>(segment.fileoff));
6772 buffer.PutHex32(uvalue: static_cast<uint32_t>(segment.filesize));
6773 }
6774 buffer.PutHex32(uvalue: segment.maxprot);
6775 buffer.PutHex32(uvalue: segment.initprot);
6776 buffer.PutHex32(uvalue: segment.nsects);
6777 buffer.PutHex32(uvalue: segment.flags);
6778 }
6779
6780 std::string core_file_path(outfile.GetPath());
6781 auto core_file = FileSystem::Instance().Open(
6782 file_spec: outfile, options: File::eOpenOptionWriteOnly | File::eOpenOptionTruncate |
6783 File::eOpenOptionCanCreate);
6784 if (!core_file) {
6785 error = core_file.takeError();
6786 } else {
6787 // Read 1 page at a time
6788 uint8_t bytes[0x1000];
6789 // Write the mach header and load commands out to the core file
6790 size_t bytes_written = buffer.GetString().size();
6791 error =
6792 core_file.get()->Write(buf: buffer.GetString().data(), num_bytes&: bytes_written);
6793 if (error.Success()) {
6794
6795 for (auto &lcnote : lc_notes) {
6796 if (core_file.get()->SeekFromStart(offset: lcnote->payload_file_offset) ==
6797 -1) {
6798 error.SetErrorStringWithFormat("Unable to seek to corefile pos "
6799 "to write '%s' LC_NOTE payload",
6800 lcnote->name.c_str());
6801 return false;
6802 }
6803 bytes_written = lcnote->payload.GetSize();
6804 error = core_file.get()->Write(buf: lcnote->payload.GetData(),
6805 num_bytes&: bytes_written);
6806 if (!error.Success())
6807 return false;
6808 }
6809
6810 // Now write the file data for all memory segments in the process
6811 for (const auto &segment : segment_load_commands) {
6812 if (core_file.get()->SeekFromStart(offset: segment.fileoff) == -1) {
6813 error.SetErrorStringWithFormat(
6814 "unable to seek to offset 0x%" PRIx64 " in '%s'",
6815 segment.fileoff, core_file_path.c_str());
6816 break;
6817 }
6818
6819 target.GetDebugger().GetAsyncOutputStream()->Printf(
6820 format: "Saving %" PRId64
6821 " bytes of data for memory region at 0x%" PRIx64 "\n",
6822 segment.vmsize, segment.vmaddr);
6823 addr_t bytes_left = segment.vmsize;
6824 addr_t addr = segment.vmaddr;
6825 Status memory_read_error;
6826 while (bytes_left > 0 && error.Success()) {
6827 const size_t bytes_to_read =
6828 bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6829
6830 // In a savecore setting, we don't really care about caching,
6831 // as the data is dumped and very likely never read again,
6832 // so we call ReadMemoryFromInferior to bypass it.
6833 const size_t bytes_read = process_sp->ReadMemoryFromInferior(
6834 vm_addr: addr, buf: bytes, size: bytes_to_read, error&: memory_read_error);
6835
6836 if (bytes_read == bytes_to_read) {
6837 size_t bytes_written = bytes_read;
6838 error = core_file.get()->Write(buf: bytes, num_bytes&: bytes_written);
6839 bytes_left -= bytes_read;
6840 addr += bytes_read;
6841 } else {
6842 // Some pages within regions are not readable, those should
6843 // be zero filled
6844 memset(s: bytes, c: 0, n: bytes_to_read);
6845 size_t bytes_written = bytes_to_read;
6846 error = core_file.get()->Write(buf: bytes, num_bytes&: bytes_written);
6847 bytes_left -= bytes_to_read;
6848 addr += bytes_to_read;
6849 }
6850 }
6851 }
6852 }
6853 }
6854 }
6855 }
6856 return true; // This is the right plug to handle saving core files for
6857 // this process
6858 }
6859 return false;
6860}
6861
6862ObjectFileMachO::MachOCorefileAllImageInfos
6863ObjectFileMachO::GetCorefileAllImageInfos() {
6864 MachOCorefileAllImageInfos image_infos;
6865 Log *log(GetLog(mask: LLDBLog::Object | LLDBLog::Symbols | LLDBLog::Process |
6866 LLDBLog::DynamicLoader));
6867
6868 auto lc_notes = FindLC_NOTEByName(name: "all image infos");
6869 for (auto lc_note : lc_notes) {
6870 offset_t payload_offset = std::get<0>(t&: lc_note);
6871 // Read the struct all_image_infos_header.
6872 uint32_t version = m_data.GetU32(offset_ptr: &payload_offset);
6873 if (version != 1) {
6874 return image_infos;
6875 }
6876 uint32_t imgcount = m_data.GetU32(offset_ptr: &payload_offset);
6877 uint64_t entries_fileoff = m_data.GetU64(offset_ptr: &payload_offset);
6878 // 'entries_size' is not used, nor is the 'unused' entry.
6879 // offset += 4; // uint32_t entries_size;
6880 // offset += 4; // uint32_t unused;
6881
6882 LLDB_LOGF(log, "LC_NOTE 'all image infos' found version %d with %d images",
6883 version, imgcount);
6884 payload_offset = entries_fileoff;
6885 for (uint32_t i = 0; i < imgcount; i++) {
6886 // Read the struct image_entry.
6887 offset_t filepath_offset = m_data.GetU64(offset_ptr: &payload_offset);
6888 uuid_t uuid;
6889 memcpy(dest: &uuid, src: m_data.GetData(offset_ptr: &payload_offset, length: sizeof(uuid_t)),
6890 n: sizeof(uuid_t));
6891 uint64_t load_address = m_data.GetU64(offset_ptr: &payload_offset);
6892 offset_t seg_addrs_offset = m_data.GetU64(offset_ptr: &payload_offset);
6893 uint32_t segment_count = m_data.GetU32(offset_ptr: &payload_offset);
6894 uint32_t currently_executing = m_data.GetU32(offset_ptr: &payload_offset);
6895
6896 MachOCorefileImageEntry image_entry;
6897 image_entry.filename = (const char *)m_data.GetCStr(offset_ptr: &filepath_offset);
6898 image_entry.uuid = UUID(uuid, sizeof(uuid_t));
6899 image_entry.load_address = load_address;
6900 image_entry.currently_executing = currently_executing;
6901
6902 offset_t seg_vmaddrs_offset = seg_addrs_offset;
6903 for (uint32_t j = 0; j < segment_count; j++) {
6904 char segname[17];
6905 m_data.CopyData(offset: seg_vmaddrs_offset, length: 16, dst: segname);
6906 segname[16] = '\0';
6907 seg_vmaddrs_offset += 16;
6908 uint64_t vmaddr = m_data.GetU64(offset_ptr: &seg_vmaddrs_offset);
6909 seg_vmaddrs_offset += 8; /* unused */
6910
6911 std::tuple<ConstString, addr_t> new_seg{ConstString(segname), vmaddr};
6912 image_entry.segment_load_addresses.push_back(x: new_seg);
6913 }
6914 LLDB_LOGF(log, " image entry: %s %s 0x%" PRIx64 " %s",
6915 image_entry.filename.c_str(),
6916 image_entry.uuid.GetAsString().c_str(),
6917 image_entry.load_address,
6918 image_entry.currently_executing ? "currently executing"
6919 : "not currently executing");
6920 image_infos.all_image_infos.push_back(x: image_entry);
6921 }
6922 }
6923
6924 lc_notes = FindLC_NOTEByName(name: "load binary");
6925 for (auto lc_note : lc_notes) {
6926 offset_t payload_offset = std::get<0>(t&: lc_note);
6927 uint32_t version = m_data.GetU32(offset_ptr: &payload_offset);
6928 if (version == 1) {
6929 uuid_t uuid;
6930 memcpy(dest: &uuid, src: m_data.GetData(offset_ptr: &payload_offset, length: sizeof(uuid_t)),
6931 n: sizeof(uuid_t));
6932 uint64_t load_address = m_data.GetU64(offset_ptr: &payload_offset);
6933 uint64_t slide = m_data.GetU64(offset_ptr: &payload_offset);
6934 std::string filename = m_data.GetCStr(offset_ptr: &payload_offset);
6935
6936 MachOCorefileImageEntry image_entry;
6937 image_entry.filename = filename;
6938 image_entry.uuid = UUID(uuid, sizeof(uuid_t));
6939 image_entry.load_address = load_address;
6940 image_entry.slide = slide;
6941 image_entry.currently_executing = true;
6942 image_infos.all_image_infos.push_back(x: image_entry);
6943 LLDB_LOGF(log,
6944 "LC_NOTE 'load binary' found, filename %s uuid %s load "
6945 "address 0x%" PRIx64 " slide 0x%" PRIx64,
6946 filename.c_str(),
6947 image_entry.uuid.IsValid()
6948 ? image_entry.uuid.GetAsString().c_str()
6949 : "00000000-0000-0000-0000-000000000000",
6950 load_address, slide);
6951 }
6952 }
6953
6954 return image_infos;
6955}
6956
6957bool ObjectFileMachO::LoadCoreFileImages(lldb_private::Process &process) {
6958 MachOCorefileAllImageInfos image_infos = GetCorefileAllImageInfos();
6959 Log *log = GetLog(mask: LLDBLog::Object | LLDBLog::DynamicLoader);
6960 Status error;
6961
6962 bool found_platform_binary = false;
6963 ModuleList added_modules;
6964 for (MachOCorefileImageEntry &image : image_infos.all_image_infos) {
6965 ModuleSP module_sp, local_filesystem_module_sp;
6966
6967 // If this is a platform binary, it has been loaded (or registered with
6968 // the DynamicLoader to be loaded), we don't need to do any further
6969 // processing. We're not going to call ModulesDidLoad on this in this
6970 // method, so notify==true.
6971 if (process.GetTarget()
6972 .GetDebugger()
6973 .GetPlatformList()
6974 .LoadPlatformBinaryAndSetup(process: &process, addr: image.load_address,
6975 notify: true /* notify */)) {
6976 LLDB_LOGF(log,
6977 "ObjectFileMachO::%s binary at 0x%" PRIx64
6978 " is a platform binary, has been handled by a Platform plugin.",
6979 __FUNCTION__, image.load_address);
6980 continue;
6981 }
6982
6983 bool value_is_offset = image.load_address == LLDB_INVALID_ADDRESS;
6984 uint64_t value = value_is_offset ? image.slide : image.load_address;
6985 if (value_is_offset && value == LLDB_INVALID_ADDRESS) {
6986 // We have neither address nor slide; so we will find the binary
6987 // by UUID and load it at slide/offset 0.
6988 value = 0;
6989 }
6990
6991 // We have either a UUID, or we have a load address which
6992 // and can try to read load commands and find a UUID.
6993 if (image.uuid.IsValid() ||
6994 (!value_is_offset && value != LLDB_INVALID_ADDRESS)) {
6995 const bool set_load_address = image.segment_load_addresses.size() == 0;
6996 const bool notify = false;
6997 // Userland Darwin binaries will have segment load addresses via
6998 // the `all image infos` LC_NOTE.
6999 const bool allow_memory_image_last_resort =
7000 image.segment_load_addresses.size();
7001 module_sp = DynamicLoader::LoadBinaryWithUUIDAndAddress(
7002 process: &process, name: image.filename, uuid: image.uuid, value, value_is_offset,
7003 force_symbol_search: image.currently_executing, notify, set_address_in_target: set_load_address,
7004 allow_memory_image_last_resort);
7005 }
7006
7007 // We have a ModuleSP to load in the Target. Load it at the
7008 // correct address/slide and notify/load scripting resources.
7009 if (module_sp) {
7010 added_modules.Append(module_sp, notify: false /* notify */);
7011
7012 // We have a list of segment load address
7013 if (image.segment_load_addresses.size() > 0) {
7014 if (log) {
7015 std::string uuidstr = image.uuid.GetAsString();
7016 log->Printf(format: "ObjectFileMachO::LoadCoreFileImages adding binary '%s' "
7017 "UUID %s with section load addresses",
7018 module_sp->GetFileSpec().GetPath().c_str(),
7019 uuidstr.c_str());
7020 }
7021 for (auto name_vmaddr_tuple : image.segment_load_addresses) {
7022 SectionList *sectlist = module_sp->GetObjectFile()->GetSectionList();
7023 if (sectlist) {
7024 SectionSP sect_sp =
7025 sectlist->FindSectionByName(section_dstr: std::get<0>(t&: name_vmaddr_tuple));
7026 if (sect_sp) {
7027 process.GetTarget().SetSectionLoadAddress(
7028 section: sect_sp, load_addr: std::get<1>(t&: name_vmaddr_tuple));
7029 }
7030 }
7031 }
7032 } else {
7033 if (log) {
7034 std::string uuidstr = image.uuid.GetAsString();
7035 log->Printf(format: "ObjectFileMachO::LoadCoreFileImages adding binary '%s' "
7036 "UUID %s with %s 0x%" PRIx64,
7037 module_sp->GetFileSpec().GetPath().c_str(),
7038 uuidstr.c_str(),
7039 value_is_offset ? "slide" : "load address", value);
7040 }
7041 bool changed;
7042 module_sp->SetLoadAddress(target&: process.GetTarget(), value, value_is_offset,
7043 changed);
7044 }
7045 }
7046 }
7047 if (added_modules.GetSize() > 0) {
7048 process.GetTarget().ModulesDidLoad(module_list&: added_modules);
7049 process.Flush();
7050 return true;
7051 }
7052 // Return true if the only binary we found was the platform binary,
7053 // and it was loaded outside the scope of this method.
7054 if (found_platform_binary)
7055 return true;
7056
7057 // No binaries.
7058 return false;
7059}
7060

source code of lldb/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp