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