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