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