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