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