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(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_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(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_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(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_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(lldb_private::GetLogIfAnyCategoriesSet(
2597         LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_UNWIND));
2598 
2599     if (unwind_or_symbol_log)
2600       module_sp->LogMessage(
2601           unwind_or_symbol_log,
2602           "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2603   }
2604 
2605   const user_id_t TEXT_eh_frame_sectID = eh_frame_section_sp.get()
2606                                              ? eh_frame_section_sp->GetID()
2607                                              : static_cast<user_id_t>(NO_SECT);
2608 
2609   uint32_t N_SO_index = UINT32_MAX;
2610 
2611   MachSymtabSectionInfo section_info(section_list);
2612   std::vector<uint32_t> N_FUN_indexes;
2613   std::vector<uint32_t> N_NSYM_indexes;
2614   std::vector<uint32_t> N_INCL_indexes;
2615   std::vector<uint32_t> N_BRAC_indexes;
2616   std::vector<uint32_t> N_COMM_indexes;
2617   typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2618   typedef llvm::DenseMap<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2619   typedef llvm::DenseMap<const char *, uint32_t> ConstNameToSymbolIndexMap;
2620   ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2621   ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2622   ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
2623   // Any symbols that get merged into another will get an entry in this map
2624   // so we know
2625   NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2626   uint32_t nlist_idx = 0;
2627   Symbol *symbol_ptr = nullptr;
2628 
2629   uint32_t sym_idx = 0;
2630   Symbol *sym = nullptr;
2631   size_t num_syms = 0;
2632   std::string memory_symbol_name;
2633   uint32_t unmapped_local_symbols_found = 0;
2634 
2635   std::vector<TrieEntryWithOffset> reexport_trie_entries;
2636   std::vector<TrieEntryWithOffset> external_sym_trie_entries;
2637   std::set<lldb::addr_t> resolver_addresses;
2638 
2639   if (dyld_trie_data.GetByteSize() > 0) {
2640     ConstString text_segment_name("__TEXT");
2641     SectionSP text_segment_sp =
2642         GetSectionList()->FindSectionByName(text_segment_name);
2643     lldb::addr_t text_segment_file_addr = LLDB_INVALID_ADDRESS;
2644     if (text_segment_sp)
2645       text_segment_file_addr = text_segment_sp->GetFileAddress();
2646     std::vector<llvm::StringRef> nameSlices;
2647     ParseTrieEntries(dyld_trie_data, 0, is_arm, text_segment_file_addr,
2648                      nameSlices, resolver_addresses, reexport_trie_entries,
2649                      external_sym_trie_entries);
2650   }
2651 
2652   typedef std::set<ConstString> IndirectSymbols;
2653   IndirectSymbols indirect_symbol_names;
2654 
2655 #if TARGET_OS_IPHONE
2656 
2657   // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
2658   // optimized by moving LOCAL symbols out of the memory mapped portion of
2659   // the DSC. The symbol information has all been retained, but it isn't
2660   // available in the normal nlist data. However, there *are* duplicate
2661   // entries of *some*
2662   // LOCAL symbols in the normal nlist data. To handle this situation
2663   // correctly, we must first attempt
2664   // to parse any DSC unmapped symbol information. If we find any, we set a
2665   // flag that tells the normal nlist parser to ignore all LOCAL symbols.
2666 
2667   if (IsSharedCacheBinary()) {
2668     // Before we can start mapping the DSC, we need to make certain the
2669     // target process is actually using the cache we can find.
2670 
2671     // Next we need to determine the correct path for the dyld shared cache.
2672 
2673     ArchSpec header_arch = GetArchitecture();
2674 
2675     UUID dsc_uuid;
2676     UUID process_shared_cache_uuid;
2677     addr_t process_shared_cache_base_addr;
2678 
2679     if (process) {
2680       GetProcessSharedCacheUUID(process, process_shared_cache_base_addr,
2681                                 process_shared_cache_uuid);
2682     }
2683 
2684     __block bool found_image = false;
2685     __block void *nlist_buffer = nullptr;
2686     __block unsigned nlist_count = 0;
2687     __block char *string_table = nullptr;
2688     __block vm_offset_t vm_nlist_memory = 0;
2689     __block mach_msg_type_number_t vm_nlist_bytes_read = 0;
2690     __block vm_offset_t vm_string_memory = 0;
2691     __block mach_msg_type_number_t vm_string_bytes_read = 0;
2692 
2693     auto _ = llvm::make_scope_exit(^{
2694       if (vm_nlist_memory)
2695         vm_deallocate(mach_task_self(), vm_nlist_memory, vm_nlist_bytes_read);
2696       if (vm_string_memory)
2697         vm_deallocate(mach_task_self(), vm_string_memory, vm_string_bytes_read);
2698     });
2699 
2700     typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
2701     typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
2702     UndefinedNameToDescMap undefined_name_to_desc;
2703     SymbolIndexToName reexport_shlib_needs_fixup;
2704 
2705     dyld_for_each_installed_shared_cache(^(dyld_shared_cache_t shared_cache) {
2706       uuid_t cache_uuid;
2707       dyld_shared_cache_copy_uuid(shared_cache, &cache_uuid);
2708       if (found_image)
2709         return;
2710 
2711         if (process_shared_cache_uuid.IsValid() &&
2712           process_shared_cache_uuid != UUID::fromOptionalData(&cache_uuid, 16))
2713         return;
2714 
2715       dyld_shared_cache_for_each_image(shared_cache, ^(dyld_image_t image) {
2716         uuid_t dsc_image_uuid;
2717         if (found_image)
2718           return;
2719 
2720         dyld_image_copy_uuid(image, &dsc_image_uuid);
2721         if (image_uuid != UUID::fromOptionalData(dsc_image_uuid, 16))
2722           return;
2723 
2724         found_image = true;
2725 
2726         // Compute the size of the string table. We need to ask dyld for a
2727         // new SPI to avoid this step.
2728         dyld_image_local_nlist_content_4Symbolication(
2729             image, ^(const void *nlistStart, uint64_t nlistCount,
2730                      const char *stringTable) {
2731               if (!nlistStart || !nlistCount)
2732                 return;
2733 
2734               // The buffers passed here are valid only inside the block.
2735               // Use vm_read to make a cheap copy of them available for our
2736               // processing later.
2737               kern_return_t ret =
2738                   vm_read(mach_task_self(), (vm_address_t)nlistStart,
2739                           nlist_byte_size * nlistCount, &vm_nlist_memory,
2740                           &vm_nlist_bytes_read);
2741               if (ret != KERN_SUCCESS)
2742                 return;
2743               assert(vm_nlist_bytes_read == nlist_byte_size * nlistCount);
2744 
2745               // We don't know the size of the string table. It's cheaper
2746               // to map the whol VM region than to determine the size by
2747               // parsing all teh nlist entries.
2748               vm_address_t string_address = (vm_address_t)stringTable;
2749               vm_size_t region_size;
2750               mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT_64;
2751               vm_region_basic_info_data_t info;
2752               memory_object_name_t object;
2753               ret = vm_region_64(mach_task_self(), &string_address,
2754                                  &region_size, VM_REGION_BASIC_INFO_64,
2755                                  (vm_region_info_t)&info, &info_count, &object);
2756               if (ret != KERN_SUCCESS)
2757                 return;
2758 
2759               ret = vm_read(mach_task_self(), (vm_address_t)stringTable,
2760                             region_size -
2761                                 ((vm_address_t)stringTable - string_address),
2762                             &vm_string_memory, &vm_string_bytes_read);
2763               if (ret != KERN_SUCCESS)
2764                 return;
2765 
2766               nlist_buffer = (void *)vm_nlist_memory;
2767               string_table = (char *)vm_string_memory;
2768               nlist_count = nlistCount;
2769             });
2770       });
2771     });
2772     if (nlist_buffer) {
2773       DataExtractor dsc_local_symbols_data(nlist_buffer,
2774                                            nlist_count * nlist_byte_size,
2775                                            byte_order, addr_byte_size);
2776       unmapped_local_symbols_found = nlist_count;
2777 
2778                 // The normal nlist code cannot correctly size the Symbols
2779                 // array, we need to allocate it here.
2780                 sym = symtab.Resize(
2781                     symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2782                     unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2783                 num_syms = symtab.GetNumSymbols();
2784 
2785       lldb::offset_t nlist_data_offset = 0;
2786 
2787                 for (uint32_t nlist_index = 0;
2788                      nlist_index < nlist_count;
2789                      nlist_index++) {
2790                   /////////////////////////////
2791                   {
2792                     llvm::Optional<struct nlist_64> nlist_maybe =
2793                         ParseNList(dsc_local_symbols_data, nlist_data_offset,
2794                                    nlist_byte_size);
2795                     if (!nlist_maybe)
2796                       break;
2797                     struct nlist_64 nlist = *nlist_maybe;
2798 
2799                     SymbolType type = eSymbolTypeInvalid;
2800           const char *symbol_name = string_table + nlist.n_strx;
2801 
2802                     if (symbol_name == NULL) {
2803                       // No symbol should be NULL, even the symbols with no
2804                       // string values should have an offset zero which
2805                       // points to an empty C-string
2806                       Host::SystemLog(
2807                           Host::eSystemLogError,
2808                           "error: DSC unmapped local symbol[%u] has invalid "
2809                           "string table offset 0x%x in %s, ignoring symbol\n",
2810                           nlist_index, nlist.n_strx,
2811                           module_sp->GetFileSpec().GetPath().c_str());
2812                       continue;
2813                     }
2814                     if (symbol_name[0] == '\0')
2815                       symbol_name = NULL;
2816 
2817                     const char *symbol_name_non_abi_mangled = NULL;
2818 
2819                     SectionSP symbol_section;
2820                     uint32_t symbol_byte_size = 0;
2821                     bool add_nlist = true;
2822                     bool is_debug = ((nlist.n_type & N_STAB) != 0);
2823                     bool demangled_is_synthesized = false;
2824                     bool is_gsym = false;
2825                     bool set_value = true;
2826 
2827                     assert(sym_idx < num_syms);
2828 
2829                     sym[sym_idx].SetDebug(is_debug);
2830 
2831                     if (is_debug) {
2832                       switch (nlist.n_type) {
2833                       case N_GSYM:
2834                         // global symbol: name,,NO_SECT,type,0
2835                         // Sometimes the N_GSYM value contains the address.
2836 
2837                         // FIXME: In the .o files, we have a GSYM and a debug
2838                         // symbol for all the ObjC data.  They
2839                         // have the same address, but we want to ensure that
2840                         // we always find only the real symbol, 'cause we
2841                         // don't currently correctly attribute the
2842                         // GSYM one to the ObjCClass/Ivar/MetaClass
2843                         // symbol type.  This is a temporary hack to make
2844                         // sure the ObjectiveC symbols get treated correctly.
2845                         // To do this right, we should coalesce all the GSYM
2846                         // & global symbols that have the same address.
2847 
2848                         is_gsym = true;
2849                         sym[sym_idx].SetExternal(true);
2850 
2851                         if (symbol_name && symbol_name[0] == '_' &&
2852                             symbol_name[1] == 'O') {
2853                           llvm::StringRef symbol_name_ref(symbol_name);
2854                           if (symbol_name_ref.startswith(
2855                                   g_objc_v2_prefix_class)) {
2856                             symbol_name_non_abi_mangled = symbol_name + 1;
2857                             symbol_name =
2858                                 symbol_name + g_objc_v2_prefix_class.size();
2859                             type = eSymbolTypeObjCClass;
2860                             demangled_is_synthesized = true;
2861 
2862                           } else if (symbol_name_ref.startswith(
2863                                          g_objc_v2_prefix_metaclass)) {
2864                             symbol_name_non_abi_mangled = symbol_name + 1;
2865                             symbol_name =
2866                                 symbol_name + g_objc_v2_prefix_metaclass.size();
2867                             type = eSymbolTypeObjCMetaClass;
2868                             demangled_is_synthesized = true;
2869                           } else if (symbol_name_ref.startswith(
2870                                          g_objc_v2_prefix_ivar)) {
2871                             symbol_name_non_abi_mangled = symbol_name + 1;
2872                             symbol_name =
2873                                 symbol_name + g_objc_v2_prefix_ivar.size();
2874                             type = eSymbolTypeObjCIVar;
2875                             demangled_is_synthesized = true;
2876                           }
2877                         } else {
2878                           if (nlist.n_value != 0)
2879                             symbol_section = section_info.GetSection(
2880                                 nlist.n_sect, nlist.n_value);
2881                           type = eSymbolTypeData;
2882                         }
2883                         break;
2884 
2885                       case N_FNAME:
2886                         // procedure name (f77 kludge): name,,NO_SECT,0,0
2887                         type = eSymbolTypeCompiler;
2888                         break;
2889 
2890                       case N_FUN:
2891                         // procedure: name,,n_sect,linenumber,address
2892                         if (symbol_name) {
2893                           type = eSymbolTypeCode;
2894                           symbol_section = section_info.GetSection(
2895                               nlist.n_sect, nlist.n_value);
2896 
2897                           N_FUN_addr_to_sym_idx.insert(
2898                               std::make_pair(nlist.n_value, sym_idx));
2899                           // We use the current number of symbols in the
2900                           // symbol table in lieu of using nlist_idx in case
2901                           // we ever start trimming entries out
2902                           N_FUN_indexes.push_back(sym_idx);
2903                         } else {
2904                           type = eSymbolTypeCompiler;
2905 
2906                           if (!N_FUN_indexes.empty()) {
2907                             // Copy the size of the function into the
2908                             // original
2909                             // STAB entry so we don't have
2910                             // to hunt for it later
2911                             symtab.SymbolAtIndex(N_FUN_indexes.back())
2912                                 ->SetByteSize(nlist.n_value);
2913                             N_FUN_indexes.pop_back();
2914                             // We don't really need the end function STAB as
2915                             // it contains the size which we already placed
2916                             // with the original symbol, so don't add it if
2917                             // we want a minimal symbol table
2918                             add_nlist = false;
2919                           }
2920                         }
2921                         break;
2922 
2923                       case N_STSYM:
2924                         // static symbol: name,,n_sect,type,address
2925                         N_STSYM_addr_to_sym_idx.insert(
2926                             std::make_pair(nlist.n_value, sym_idx));
2927                         symbol_section = section_info.GetSection(nlist.n_sect,
2928                                                                  nlist.n_value);
2929                         if (symbol_name && symbol_name[0]) {
2930                           type = ObjectFile::GetSymbolTypeFromName(
2931                               symbol_name + 1, eSymbolTypeData);
2932                         }
2933                         break;
2934 
2935                       case N_LCSYM:
2936                         // .lcomm symbol: name,,n_sect,type,address
2937                         symbol_section = section_info.GetSection(nlist.n_sect,
2938                                                                  nlist.n_value);
2939                         type = eSymbolTypeCommonBlock;
2940                         break;
2941 
2942                       case N_BNSYM:
2943                         // We use the current number of symbols in the symbol
2944                         // table in lieu of using nlist_idx in case we ever
2945                         // start trimming entries out Skip these if we want
2946                         // minimal symbol tables
2947                         add_nlist = false;
2948                         break;
2949 
2950                       case N_ENSYM:
2951                         // Set the size of the N_BNSYM to the terminating
2952                         // index of this N_ENSYM so that we can always skip
2953                         // the entire symbol if we need to navigate more
2954                         // quickly at the source level when parsing STABS
2955                         // Skip these if we want minimal symbol tables
2956                         add_nlist = false;
2957                         break;
2958 
2959                       case N_OPT:
2960                         // emitted with gcc2_compiled and in gcc source
2961                         type = eSymbolTypeCompiler;
2962                         break;
2963 
2964                       case N_RSYM:
2965                         // register sym: name,,NO_SECT,type,register
2966                         type = eSymbolTypeVariable;
2967                         break;
2968 
2969                       case N_SLINE:
2970                         // src line: 0,,n_sect,linenumber,address
2971                         symbol_section = section_info.GetSection(nlist.n_sect,
2972                                                                  nlist.n_value);
2973                         type = eSymbolTypeLineEntry;
2974                         break;
2975 
2976                       case N_SSYM:
2977                         // structure elt: name,,NO_SECT,type,struct_offset
2978                         type = eSymbolTypeVariableType;
2979                         break;
2980 
2981                       case N_SO:
2982                         // source file name
2983                         type = eSymbolTypeSourceFile;
2984                         if (symbol_name == NULL) {
2985                           add_nlist = false;
2986                           if (N_SO_index != UINT32_MAX) {
2987                             // Set the size of the N_SO to the terminating
2988                             // index of this N_SO so that we can always skip
2989                             // the entire N_SO if we need to navigate more
2990                             // quickly at the source level when parsing STABS
2991                             symbol_ptr = symtab.SymbolAtIndex(N_SO_index);
2992                             symbol_ptr->SetByteSize(sym_idx);
2993                             symbol_ptr->SetSizeIsSibling(true);
2994                           }
2995                           N_NSYM_indexes.clear();
2996                           N_INCL_indexes.clear();
2997                           N_BRAC_indexes.clear();
2998                           N_COMM_indexes.clear();
2999                           N_FUN_indexes.clear();
3000                           N_SO_index = UINT32_MAX;
3001                         } else {
3002                           // We use the current number of symbols in the
3003                           // symbol table in lieu of using nlist_idx in case
3004                           // we ever start trimming entries out
3005                           const bool N_SO_has_full_path = symbol_name[0] == '/';
3006                           if (N_SO_has_full_path) {
3007                             if ((N_SO_index == sym_idx - 1) &&
3008                                 ((sym_idx - 1) < num_syms)) {
3009                               // We have two consecutive N_SO entries where
3010                               // the first contains a directory and the
3011                               // second contains a full path.
3012                               sym[sym_idx - 1].GetMangled().SetValue(
3013                                   ConstString(symbol_name), false);
3014                               m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3015                               add_nlist = false;
3016                             } else {
3017                               // This is the first entry in a N_SO that
3018                               // contains a directory or
3019                               // a full path to the source file
3020                               N_SO_index = sym_idx;
3021                             }
3022                           } else if ((N_SO_index == sym_idx - 1) &&
3023                                      ((sym_idx - 1) < num_syms)) {
3024                             // This is usually the second N_SO entry that
3025                             // contains just the filename, so here we combine
3026                             // it with the first one if we are minimizing the
3027                             // symbol table
3028                             const char *so_path = sym[sym_idx - 1]
3029                                                       .GetMangled()
3030                                                       .GetDemangledName()
3031                                                       .AsCString();
3032                             if (so_path && so_path[0]) {
3033                               std::string full_so_path(so_path);
3034                               const size_t double_slash_pos =
3035                                   full_so_path.find("//");
3036                               if (double_slash_pos != std::string::npos) {
3037                                 // The linker has been generating bad N_SO
3038                                 // entries with doubled up paths
3039                                 // in the format "%s%s" where the first
3040                                 // string in the DW_AT_comp_dir, and the
3041                                 // second is the directory for the source
3042                                 // file so you end up with a path that looks
3043                                 // like "/tmp/src//tmp/src/"
3044                                 FileSpec so_dir(so_path);
3045                                 if (!FileSystem::Instance().Exists(so_dir)) {
3046                                   so_dir.SetFile(
3047                                       &full_so_path[double_slash_pos + 1],
3048                                       FileSpec::Style::native);
3049                                   if (FileSystem::Instance().Exists(so_dir)) {
3050                                     // Trim off the incorrect path
3051                                     full_so_path.erase(0, double_slash_pos + 1);
3052                                   }
3053                                 }
3054                               }
3055                               if (*full_so_path.rbegin() != '/')
3056                                 full_so_path += '/';
3057                               full_so_path += symbol_name;
3058                               sym[sym_idx - 1].GetMangled().SetValue(
3059                                   ConstString(full_so_path.c_str()), false);
3060                               add_nlist = false;
3061                               m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3062                             }
3063                           } else {
3064                             // This could be a relative path to a N_SO
3065                             N_SO_index = sym_idx;
3066                           }
3067                         }
3068                         break;
3069 
3070                       case N_OSO:
3071                         // object file name: name,,0,0,st_mtime
3072                         type = eSymbolTypeObjectFile;
3073                         break;
3074 
3075                       case N_LSYM:
3076                         // local sym: name,,NO_SECT,type,offset
3077                         type = eSymbolTypeLocal;
3078                         break;
3079 
3080                       // INCL scopes
3081                       case N_BINCL:
3082                         // include file beginning: name,,NO_SECT,0,sum We use
3083                         // the current number of symbols in the symbol table
3084                         // in lieu of using nlist_idx in case we ever start
3085                         // trimming entries out
3086                         N_INCL_indexes.push_back(sym_idx);
3087                         type = eSymbolTypeScopeBegin;
3088                         break;
3089 
3090                       case N_EINCL:
3091                         // include file end: name,,NO_SECT,0,0
3092                         // Set the size of the N_BINCL to the terminating
3093                         // index of this N_EINCL so that we can always skip
3094                         // the entire symbol if we need to navigate more
3095                         // quickly at the source level when parsing STABS
3096                         if (!N_INCL_indexes.empty()) {
3097                           symbol_ptr =
3098                               symtab.SymbolAtIndex(N_INCL_indexes.back());
3099                           symbol_ptr->SetByteSize(sym_idx + 1);
3100                           symbol_ptr->SetSizeIsSibling(true);
3101                           N_INCL_indexes.pop_back();
3102                         }
3103                         type = eSymbolTypeScopeEnd;
3104                         break;
3105 
3106                       case N_SOL:
3107                         // #included file name: name,,n_sect,0,address
3108                         type = eSymbolTypeHeaderFile;
3109 
3110                         // We currently don't use the header files on darwin
3111                         add_nlist = false;
3112                         break;
3113 
3114                       case N_PARAMS:
3115                         // compiler parameters: name,,NO_SECT,0,0
3116                         type = eSymbolTypeCompiler;
3117                         break;
3118 
3119                       case N_VERSION:
3120                         // compiler version: name,,NO_SECT,0,0
3121                         type = eSymbolTypeCompiler;
3122                         break;
3123 
3124                       case N_OLEVEL:
3125                         // compiler -O level: name,,NO_SECT,0,0
3126                         type = eSymbolTypeCompiler;
3127                         break;
3128 
3129                       case N_PSYM:
3130                         // parameter: name,,NO_SECT,type,offset
3131                         type = eSymbolTypeVariable;
3132                         break;
3133 
3134                       case N_ENTRY:
3135                         // alternate entry: name,,n_sect,linenumber,address
3136                         symbol_section = section_info.GetSection(nlist.n_sect,
3137                                                                  nlist.n_value);
3138                         type = eSymbolTypeLineEntry;
3139                         break;
3140 
3141                       // Left and Right Braces
3142                       case N_LBRAC:
3143                         // left bracket: 0,,NO_SECT,nesting level,address We
3144                         // use the current number of symbols in the symbol
3145                         // table in lieu of using nlist_idx in case we ever
3146                         // start trimming entries out
3147                         symbol_section = section_info.GetSection(nlist.n_sect,
3148                                                                  nlist.n_value);
3149                         N_BRAC_indexes.push_back(sym_idx);
3150                         type = eSymbolTypeScopeBegin;
3151                         break;
3152 
3153                       case N_RBRAC:
3154                         // right bracket: 0,,NO_SECT,nesting level,address
3155                         // Set the size of the N_LBRAC to the terminating
3156                         // index of this N_RBRAC so that we can always skip
3157                         // the entire symbol if we need to navigate more
3158                         // quickly at the source level when parsing STABS
3159                         symbol_section = section_info.GetSection(nlist.n_sect,
3160                                                                  nlist.n_value);
3161                         if (!N_BRAC_indexes.empty()) {
3162                           symbol_ptr =
3163                               symtab.SymbolAtIndex(N_BRAC_indexes.back());
3164                           symbol_ptr->SetByteSize(sym_idx + 1);
3165                           symbol_ptr->SetSizeIsSibling(true);
3166                           N_BRAC_indexes.pop_back();
3167                         }
3168                         type = eSymbolTypeScopeEnd;
3169                         break;
3170 
3171                       case N_EXCL:
3172                         // deleted include file: name,,NO_SECT,0,sum
3173                         type = eSymbolTypeHeaderFile;
3174                         break;
3175 
3176                       // COMM scopes
3177                       case N_BCOMM:
3178                         // begin common: name,,NO_SECT,0,0
3179                         // We use the current number of symbols in the symbol
3180                         // table in lieu of using nlist_idx in case we ever
3181                         // start trimming entries out
3182                         type = eSymbolTypeScopeBegin;
3183                         N_COMM_indexes.push_back(sym_idx);
3184                         break;
3185 
3186                       case N_ECOML:
3187                         // end common (local name): 0,,n_sect,0,address
3188                         symbol_section = section_info.GetSection(nlist.n_sect,
3189                                                                  nlist.n_value);
3190                         // Fall through
3191 
3192                       case N_ECOMM:
3193                         // end common: name,,n_sect,0,0
3194                         // Set the size of the N_BCOMM to the terminating
3195                         // index of this N_ECOMM/N_ECOML so that we can
3196                         // always skip the entire symbol if we need to
3197                         // navigate more quickly at the source level when
3198                         // parsing STABS
3199                         if (!N_COMM_indexes.empty()) {
3200                           symbol_ptr =
3201                               symtab.SymbolAtIndex(N_COMM_indexes.back());
3202                           symbol_ptr->SetByteSize(sym_idx + 1);
3203                           symbol_ptr->SetSizeIsSibling(true);
3204                           N_COMM_indexes.pop_back();
3205                         }
3206                         type = eSymbolTypeScopeEnd;
3207                         break;
3208 
3209                       case N_LENG:
3210                         // second stab entry with length information
3211                         type = eSymbolTypeAdditional;
3212                         break;
3213 
3214                       default:
3215                         break;
3216                       }
3217                     } else {
3218                       // uint8_t n_pext    = N_PEXT & nlist.n_type;
3219                       uint8_t n_type = N_TYPE & nlist.n_type;
3220                       sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
3221 
3222                       switch (n_type) {
3223                       case N_INDR: {
3224                         const char *reexport_name_cstr =
3225                             strtab_data.PeekCStr(nlist.n_value);
3226                         if (reexport_name_cstr && reexport_name_cstr[0]) {
3227                           type = eSymbolTypeReExported;
3228                           ConstString reexport_name(
3229                               reexport_name_cstr +
3230                               ((reexport_name_cstr[0] == '_') ? 1 : 0));
3231                           sym[sym_idx].SetReExportedSymbolName(reexport_name);
3232                           set_value = false;
3233                           reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3234                           indirect_symbol_names.insert(ConstString(
3235                               symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
3236                         } else
3237                           type = eSymbolTypeUndefined;
3238                       } break;
3239 
3240                       case N_UNDF:
3241                         if (symbol_name && symbol_name[0]) {
3242                           ConstString undefined_name(
3243                               symbol_name + ((symbol_name[0] == '_') ? 1 : 0));
3244                           undefined_name_to_desc[undefined_name] = nlist.n_desc;
3245                         }
3246                       // Fall through
3247                       case N_PBUD:
3248                         type = eSymbolTypeUndefined;
3249                         break;
3250 
3251                       case N_ABS:
3252                         type = eSymbolTypeAbsolute;
3253                         break;
3254 
3255                       case N_SECT: {
3256                         symbol_section = section_info.GetSection(nlist.n_sect,
3257                                                                  nlist.n_value);
3258 
3259                         if (symbol_section == NULL) {
3260                           // TODO: warn about this?
3261                           add_nlist = false;
3262                           break;
3263                         }
3264 
3265                         if (TEXT_eh_frame_sectID == nlist.n_sect) {
3266                           type = eSymbolTypeException;
3267                         } else {
3268                           uint32_t section_type =
3269                               symbol_section->Get() & SECTION_TYPE;
3270 
3271                           switch (section_type) {
3272                           case S_CSTRING_LITERALS:
3273                             type = eSymbolTypeData;
3274                             break; // section with only literal C strings
3275                           case S_4BYTE_LITERALS:
3276                             type = eSymbolTypeData;
3277                             break; // section with only 4 byte literals
3278                           case S_8BYTE_LITERALS:
3279                             type = eSymbolTypeData;
3280                             break; // section with only 8 byte literals
3281                           case S_LITERAL_POINTERS:
3282                             type = eSymbolTypeTrampoline;
3283                             break; // section with only pointers to literals
3284                           case S_NON_LAZY_SYMBOL_POINTERS:
3285                             type = eSymbolTypeTrampoline;
3286                             break; // section with only non-lazy symbol
3287                                    // pointers
3288                           case S_LAZY_SYMBOL_POINTERS:
3289                             type = eSymbolTypeTrampoline;
3290                             break; // section with only lazy symbol pointers
3291                           case S_SYMBOL_STUBS:
3292                             type = eSymbolTypeTrampoline;
3293                             break; // section with only symbol stubs, byte
3294                                    // size of stub in the reserved2 field
3295                           case S_MOD_INIT_FUNC_POINTERS:
3296                             type = eSymbolTypeCode;
3297                             break; // section with only function pointers for
3298                                    // initialization
3299                           case S_MOD_TERM_FUNC_POINTERS:
3300                             type = eSymbolTypeCode;
3301                             break; // section with only function pointers for
3302                                    // termination
3303                           case S_INTERPOSING:
3304                             type = eSymbolTypeTrampoline;
3305                             break; // section with only pairs of function
3306                                    // pointers for interposing
3307                           case S_16BYTE_LITERALS:
3308                             type = eSymbolTypeData;
3309                             break; // section with only 16 byte literals
3310                           case S_DTRACE_DOF:
3311                             type = eSymbolTypeInstrumentation;
3312                             break;
3313                           case S_LAZY_DYLIB_SYMBOL_POINTERS:
3314                             type = eSymbolTypeTrampoline;
3315                             break;
3316                           default:
3317                             switch (symbol_section->GetType()) {
3318                             case lldb::eSectionTypeCode:
3319                               type = eSymbolTypeCode;
3320                               break;
3321                             case eSectionTypeData:
3322                             case eSectionTypeDataCString: // Inlined C string
3323                                                           // data
3324                             case eSectionTypeDataCStringPointers: // Pointers
3325                                                                   // to C
3326                                                                   // string
3327                                                                   // data
3328                             case eSectionTypeDataSymbolAddress:   // Address of
3329                                                                   // a symbol in
3330                                                                   // the symbol
3331                                                                   // table
3332                             case eSectionTypeData4:
3333                             case eSectionTypeData8:
3334                             case eSectionTypeData16:
3335                               type = eSymbolTypeData;
3336                               break;
3337                             default:
3338                               break;
3339                             }
3340                             break;
3341                           }
3342 
3343                           if (type == eSymbolTypeInvalid) {
3344                             const char *symbol_sect_name =
3345                                 symbol_section->GetName().AsCString();
3346                             if (symbol_section->IsDescendant(
3347                                     text_section_sp.get())) {
3348                               if (symbol_section->IsClear(
3349                                       S_ATTR_PURE_INSTRUCTIONS |
3350                                       S_ATTR_SELF_MODIFYING_CODE |
3351                                       S_ATTR_SOME_INSTRUCTIONS))
3352                                 type = eSymbolTypeData;
3353                               else
3354                                 type = eSymbolTypeCode;
3355                             } else if (symbol_section->IsDescendant(
3356                                            data_section_sp.get()) ||
3357                                        symbol_section->IsDescendant(
3358                                            data_dirty_section_sp.get()) ||
3359                                        symbol_section->IsDescendant(
3360                                            data_const_section_sp.get())) {
3361                               if (symbol_sect_name &&
3362                                   ::strstr(symbol_sect_name, "__objc") ==
3363                                       symbol_sect_name) {
3364                                 type = eSymbolTypeRuntime;
3365 
3366                                 if (symbol_name) {
3367                                   llvm::StringRef symbol_name_ref(symbol_name);
3368                                   if (symbol_name_ref.startswith("_OBJC_")) {
3369                                     llvm::StringRef
3370                                         g_objc_v2_prefix_class(
3371                                             "_OBJC_CLASS_$_");
3372                                     llvm::StringRef
3373                                         g_objc_v2_prefix_metaclass(
3374                                             "_OBJC_METACLASS_$_");
3375                                     llvm::StringRef
3376                                         g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
3377                                     if (symbol_name_ref.startswith(
3378                                             g_objc_v2_prefix_class)) {
3379                                       symbol_name_non_abi_mangled =
3380                                           symbol_name + 1;
3381                                       symbol_name =
3382                                           symbol_name +
3383                                           g_objc_v2_prefix_class.size();
3384                                       type = eSymbolTypeObjCClass;
3385                                       demangled_is_synthesized = true;
3386                                     } else if (
3387                                         symbol_name_ref.startswith(
3388                                             g_objc_v2_prefix_metaclass)) {
3389                                       symbol_name_non_abi_mangled =
3390                                           symbol_name + 1;
3391                                       symbol_name =
3392                                           symbol_name +
3393                                           g_objc_v2_prefix_metaclass.size();
3394                                       type = eSymbolTypeObjCMetaClass;
3395                                       demangled_is_synthesized = true;
3396                                     } else if (symbol_name_ref.startswith(
3397                                                    g_objc_v2_prefix_ivar)) {
3398                                       symbol_name_non_abi_mangled =
3399                                           symbol_name + 1;
3400                                       symbol_name =
3401                                           symbol_name +
3402                                           g_objc_v2_prefix_ivar.size();
3403                                       type = eSymbolTypeObjCIVar;
3404                                       demangled_is_synthesized = true;
3405                                     }
3406                                   }
3407                                 }
3408                               } else if (symbol_sect_name &&
3409                                          ::strstr(symbol_sect_name,
3410                                                   "__gcc_except_tab") ==
3411                                              symbol_sect_name) {
3412                                 type = eSymbolTypeException;
3413                               } else {
3414                                 type = eSymbolTypeData;
3415                               }
3416                             } else if (symbol_sect_name &&
3417                                        ::strstr(symbol_sect_name, "__IMPORT") ==
3418                                            symbol_sect_name) {
3419                               type = eSymbolTypeTrampoline;
3420                             } else if (symbol_section->IsDescendant(
3421                                            objc_section_sp.get())) {
3422                               type = eSymbolTypeRuntime;
3423                               if (symbol_name && symbol_name[0] == '.') {
3424                                 llvm::StringRef symbol_name_ref(symbol_name);
3425                                 llvm::StringRef
3426                                     g_objc_v1_prefix_class(".objc_class_name_");
3427                                 if (symbol_name_ref.startswith(
3428                                         g_objc_v1_prefix_class)) {
3429                                   symbol_name_non_abi_mangled = symbol_name;
3430                                   symbol_name = symbol_name +
3431                                                 g_objc_v1_prefix_class.size();
3432                                   type = eSymbolTypeObjCClass;
3433                                   demangled_is_synthesized = true;
3434                                 }
3435                               }
3436                             }
3437                           }
3438                         }
3439                       } break;
3440                       }
3441                     }
3442 
3443                     if (add_nlist) {
3444                       uint64_t symbol_value = nlist.n_value;
3445                       if (symbol_name_non_abi_mangled) {
3446                         sym[sym_idx].GetMangled().SetMangledName(
3447                             ConstString(symbol_name_non_abi_mangled));
3448                         sym[sym_idx].GetMangled().SetDemangledName(
3449                             ConstString(symbol_name));
3450                       } else {
3451                         bool symbol_name_is_mangled = false;
3452 
3453                         if (symbol_name && symbol_name[0] == '_') {
3454                           symbol_name_is_mangled = symbol_name[1] == '_';
3455                           symbol_name++; // Skip the leading underscore
3456                         }
3457 
3458                         if (symbol_name) {
3459                           ConstString const_symbol_name(symbol_name);
3460                           sym[sym_idx].GetMangled().SetValue(
3461                               const_symbol_name, symbol_name_is_mangled);
3462                           if (is_gsym && is_debug) {
3463                             const char *gsym_name =
3464                                 sym[sym_idx]
3465                                     .GetMangled()
3466                                     .GetName(Mangled::ePreferMangled)
3467                                     .GetCString();
3468                             if (gsym_name)
3469                               N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3470                           }
3471                         }
3472                       }
3473                       if (symbol_section) {
3474                         const addr_t section_file_addr =
3475                             symbol_section->GetFileAddress();
3476                         if (symbol_byte_size == 0 &&
3477                             function_starts_count > 0) {
3478                           addr_t symbol_lookup_file_addr = nlist.n_value;
3479                           // Do an exact address match for non-ARM addresses,
3480                           // else get the closest since the symbol might be a
3481                           // thumb symbol which has an address with bit zero
3482                           // set
3483                           FunctionStarts::Entry *func_start_entry =
3484                               function_starts.FindEntry(symbol_lookup_file_addr,
3485                                                         !is_arm);
3486                           if (is_arm && func_start_entry) {
3487                             // Verify that the function start address is the
3488                             // symbol address (ARM) or the symbol address + 1
3489                             // (thumb)
3490                             if (func_start_entry->addr !=
3491                                     symbol_lookup_file_addr &&
3492                                 func_start_entry->addr !=
3493                                     (symbol_lookup_file_addr + 1)) {
3494                               // Not the right entry, NULL it out...
3495                               func_start_entry = NULL;
3496                             }
3497                           }
3498                           if (func_start_entry) {
3499                             func_start_entry->data = true;
3500 
3501                             addr_t symbol_file_addr = func_start_entry->addr;
3502                             uint32_t symbol_flags = 0;
3503                             if (is_arm) {
3504                               if (symbol_file_addr & 1)
3505                                 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3506                               symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3507                             }
3508 
3509                             const FunctionStarts::Entry *next_func_start_entry =
3510                                 function_starts.FindNextEntry(func_start_entry);
3511                             const addr_t section_end_file_addr =
3512                                 section_file_addr +
3513                                 symbol_section->GetByteSize();
3514                             if (next_func_start_entry) {
3515                               addr_t next_symbol_file_addr =
3516                                   next_func_start_entry->addr;
3517                               // Be sure the clear the Thumb address bit when
3518                               // we calculate the size from the current and
3519                               // next address
3520                               if (is_arm)
3521                                 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3522                               symbol_byte_size = std::min<lldb::addr_t>(
3523                                   next_symbol_file_addr - symbol_file_addr,
3524                                   section_end_file_addr - symbol_file_addr);
3525                             } else {
3526                               symbol_byte_size =
3527                                   section_end_file_addr - symbol_file_addr;
3528                             }
3529                           }
3530                         }
3531                         symbol_value -= section_file_addr;
3532                       }
3533 
3534                       if (is_debug == false) {
3535                         if (type == eSymbolTypeCode) {
3536                           // See if we can find a N_FUN entry for any code
3537                           // symbols. If we do find a match, and the name
3538                           // matches, then we can merge the two into just the
3539                           // function symbol to avoid duplicate entries in
3540                           // the symbol table
3541                           auto range =
3542                               N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
3543                           if (range.first != range.second) {
3544                             bool found_it = false;
3545                             for (auto pos = range.first; pos != range.second;
3546                                  ++pos) {
3547                               if (sym[sym_idx].GetMangled().GetName(
3548                                       Mangled::ePreferMangled) ==
3549                                   sym[pos->second].GetMangled().GetName(
3550                                       Mangled::ePreferMangled)) {
3551                                 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3552                                 // We just need the flags from the linker
3553                                 // symbol, so put these flags
3554                                 // into the N_FUN flags to avoid duplicate
3555                                 // symbols in the symbol table
3556                                 sym[pos->second].SetExternal(
3557                                     sym[sym_idx].IsExternal());
3558                                 sym[pos->second].SetFlags(nlist.n_type << 16 |
3559                                                           nlist.n_desc);
3560                                 if (resolver_addresses.find(nlist.n_value) !=
3561                                     resolver_addresses.end())
3562                                   sym[pos->second].SetType(eSymbolTypeResolver);
3563                                 sym[sym_idx].Clear();
3564                                 found_it = true;
3565                                 break;
3566                               }
3567                             }
3568                             if (found_it)
3569                               continue;
3570                           } else {
3571                             if (resolver_addresses.find(nlist.n_value) !=
3572                                 resolver_addresses.end())
3573                               type = eSymbolTypeResolver;
3574                           }
3575                         } else if (type == eSymbolTypeData ||
3576                                    type == eSymbolTypeObjCClass ||
3577                                    type == eSymbolTypeObjCMetaClass ||
3578                                    type == eSymbolTypeObjCIVar) {
3579                           // See if we can find a N_STSYM entry for any data
3580                           // symbols. If we do find a match, and the name
3581                           // matches, then we can merge the two into just the
3582                           // Static symbol to avoid duplicate entries in the
3583                           // symbol table
3584                           auto range = N_STSYM_addr_to_sym_idx.equal_range(
3585                               nlist.n_value);
3586                           if (range.first != range.second) {
3587                             bool found_it = false;
3588                             for (auto pos = range.first; pos != range.second;
3589                                  ++pos) {
3590                               if (sym[sym_idx].GetMangled().GetName(
3591                                       Mangled::ePreferMangled) ==
3592                                   sym[pos->second].GetMangled().GetName(
3593                                       Mangled::ePreferMangled)) {
3594                                 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3595                                 // We just need the flags from the linker
3596                                 // symbol, so put these flags
3597                                 // into the N_STSYM flags to avoid duplicate
3598                                 // symbols in the symbol table
3599                                 sym[pos->second].SetExternal(
3600                                     sym[sym_idx].IsExternal());
3601                                 sym[pos->second].SetFlags(nlist.n_type << 16 |
3602                                                           nlist.n_desc);
3603                                 sym[sym_idx].Clear();
3604                                 found_it = true;
3605                                 break;
3606                               }
3607                             }
3608                             if (found_it)
3609                               continue;
3610                           } else {
3611                             const char *gsym_name =
3612                                 sym[sym_idx]
3613                                     .GetMangled()
3614                                     .GetName(Mangled::ePreferMangled)
3615                                     .GetCString();
3616                             if (gsym_name) {
3617                               // Combine N_GSYM stab entries with the non
3618                               // stab symbol
3619                               ConstNameToSymbolIndexMap::const_iterator pos =
3620                                   N_GSYM_name_to_sym_idx.find(gsym_name);
3621                               if (pos != N_GSYM_name_to_sym_idx.end()) {
3622                                 const uint32_t GSYM_sym_idx = pos->second;
3623                                 m_nlist_idx_to_sym_idx[nlist_idx] =
3624                                     GSYM_sym_idx;
3625                                 // Copy the address, because often the N_GSYM
3626                                 // address has an invalid address of zero
3627                                 // when the global is a common symbol
3628                                 sym[GSYM_sym_idx].GetAddressRef().SetSection(
3629                                     symbol_section);
3630                                 sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3631                                     symbol_value);
3632                                 add_symbol_addr(sym[GSYM_sym_idx]
3633                                                     .GetAddress()
3634                                                     .GetFileAddress());
3635                                 // We just need the flags from the linker
3636                                 // symbol, so put these flags
3637                                 // into the N_GSYM flags to avoid duplicate
3638                                 // symbols in the symbol table
3639                                 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
3640                                                            nlist.n_desc);
3641                                 sym[sym_idx].Clear();
3642                                 continue;
3643                               }
3644                             }
3645                           }
3646                         }
3647                       }
3648 
3649                       sym[sym_idx].SetID(nlist_idx);
3650                       sym[sym_idx].SetType(type);
3651                       if (set_value) {
3652                         sym[sym_idx].GetAddressRef().SetSection(symbol_section);
3653                         sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
3654                         add_symbol_addr(
3655                             sym[sym_idx].GetAddress().GetFileAddress());
3656                       }
3657                       sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
3658 
3659                       if (symbol_byte_size > 0)
3660                         sym[sym_idx].SetByteSize(symbol_byte_size);
3661 
3662                       if (demangled_is_synthesized)
3663                         sym[sym_idx].SetDemangledNameIsSynthesized(true);
3664                       ++sym_idx;
3665                     } else {
3666                       sym[sym_idx].Clear();
3667                     }
3668                   }
3669                   /////////////////////////////
3670                 }
3671             }
3672 
3673             for (const auto &pos : reexport_shlib_needs_fixup) {
3674               const auto undef_pos = undefined_name_to_desc.find(pos.second);
3675               if (undef_pos != undefined_name_to_desc.end()) {
3676                 const uint8_t dylib_ordinal =
3677                     llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3678                 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
3679                   sym[pos.first].SetReExportedSymbolSharedLibrary(
3680                       dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3681               }
3682             }
3683           }
3684 
3685 #endif
3686   lldb::offset_t nlist_data_offset = 0;
3687 
3688   if (nlist_data.GetByteSize() > 0) {
3689 
3690     // If the sym array was not created while parsing the DSC unmapped
3691     // symbols, create it now.
3692     if (sym == nullptr) {
3693       sym =
3694           symtab.Resize(symtab_load_command.nsyms + m_dysymtab.nindirectsyms);
3695       num_syms = symtab.GetNumSymbols();
3696     }
3697 
3698     if (unmapped_local_symbols_found) {
3699       assert(m_dysymtab.ilocalsym == 0);
3700       nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3701       nlist_idx = m_dysymtab.nlocalsym;
3702     } else {
3703       nlist_idx = 0;
3704     }
3705 
3706     typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
3707     typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
3708     UndefinedNameToDescMap undefined_name_to_desc;
3709     SymbolIndexToName reexport_shlib_needs_fixup;
3710 
3711     // Symtab parsing is a huge mess. Everything is entangled and the code
3712     // requires access to a ridiculous amount of variables. LLDB depends
3713     // heavily on the proper merging of symbols and to get that right we need
3714     // to make sure we have parsed all the debug symbols first. Therefore we
3715     // invoke the lambda twice, once to parse only the debug symbols and then
3716     // once more to parse the remaining symbols.
3717     auto ParseSymbolLambda = [&](struct nlist_64 &nlist, uint32_t nlist_idx,
3718                                  bool debug_only) {
3719       const bool is_debug = ((nlist.n_type & N_STAB) != 0);
3720       if (is_debug != debug_only)
3721         return true;
3722 
3723       const char *symbol_name_non_abi_mangled = nullptr;
3724       const char *symbol_name = nullptr;
3725 
3726       if (have_strtab_data) {
3727         symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3728 
3729         if (symbol_name == nullptr) {
3730           // No symbol should be NULL, even the symbols with no string values
3731           // should have an offset zero which points to an empty C-string
3732           Host::SystemLog(Host::eSystemLogError,
3733                           "error: symbol[%u] has invalid string table offset "
3734                           "0x%x in %s, ignoring symbol\n",
3735                           nlist_idx, nlist.n_strx,
3736                           module_sp->GetFileSpec().GetPath().c_str());
3737           return true;
3738         }
3739         if (symbol_name[0] == '\0')
3740           symbol_name = nullptr;
3741       } else {
3742         const addr_t str_addr = strtab_addr + nlist.n_strx;
3743         Status str_error;
3744         if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
3745                                            str_error))
3746           symbol_name = memory_symbol_name.c_str();
3747       }
3748 
3749       SymbolType type = eSymbolTypeInvalid;
3750       SectionSP symbol_section;
3751       lldb::addr_t symbol_byte_size = 0;
3752       bool add_nlist = true;
3753       bool is_gsym = false;
3754       bool demangled_is_synthesized = false;
3755       bool set_value = true;
3756 
3757       assert(sym_idx < num_syms);
3758       sym[sym_idx].SetDebug(is_debug);
3759 
3760       if (is_debug) {
3761         switch (nlist.n_type) {
3762         case N_GSYM:
3763           // global symbol: name,,NO_SECT,type,0
3764           // Sometimes the N_GSYM value contains the address.
3765 
3766           // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3767           // the ObjC data.  They
3768           // have the same address, but we want to ensure that we always find
3769           // only the real symbol, 'cause we don't currently correctly
3770           // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3771           // type.  This is a temporary hack to make sure the ObjectiveC
3772           // symbols get treated correctly.  To do this right, we should
3773           // coalesce all the GSYM & global symbols that have the same
3774           // address.
3775           is_gsym = true;
3776           sym[sym_idx].SetExternal(true);
3777 
3778           if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3779             llvm::StringRef symbol_name_ref(symbol_name);
3780             if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
3781               symbol_name_non_abi_mangled = symbol_name + 1;
3782               symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3783               type = eSymbolTypeObjCClass;
3784               demangled_is_synthesized = true;
3785 
3786             } else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass)) {
3787               symbol_name_non_abi_mangled = symbol_name + 1;
3788               symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3789               type = eSymbolTypeObjCMetaClass;
3790               demangled_is_synthesized = true;
3791             } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
3792               symbol_name_non_abi_mangled = symbol_name + 1;
3793               symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3794               type = eSymbolTypeObjCIVar;
3795               demangled_is_synthesized = true;
3796             }
3797           } else {
3798             if (nlist.n_value != 0)
3799               symbol_section =
3800                   section_info.GetSection(nlist.n_sect, nlist.n_value);
3801             type = eSymbolTypeData;
3802           }
3803           break;
3804 
3805         case N_FNAME:
3806           // procedure name (f77 kludge): name,,NO_SECT,0,0
3807           type = eSymbolTypeCompiler;
3808           break;
3809 
3810         case N_FUN:
3811           // procedure: name,,n_sect,linenumber,address
3812           if (symbol_name) {
3813             type = eSymbolTypeCode;
3814             symbol_section =
3815                 section_info.GetSection(nlist.n_sect, nlist.n_value);
3816 
3817             N_FUN_addr_to_sym_idx.insert(
3818                 std::make_pair(nlist.n_value, sym_idx));
3819             // We use the current number of symbols in the symbol table in
3820             // lieu of using nlist_idx in case we ever start trimming entries
3821             // out
3822             N_FUN_indexes.push_back(sym_idx);
3823           } else {
3824             type = eSymbolTypeCompiler;
3825 
3826             if (!N_FUN_indexes.empty()) {
3827               // Copy the size of the function into the original STAB entry
3828               // so we don't have to hunt for it later
3829               symtab.SymbolAtIndex(N_FUN_indexes.back())
3830                   ->SetByteSize(nlist.n_value);
3831               N_FUN_indexes.pop_back();
3832               // We don't really need the end function STAB as it contains
3833               // the size which we already placed with the original symbol,
3834               // so don't add it if we want a minimal symbol table
3835               add_nlist = false;
3836             }
3837           }
3838           break;
3839 
3840         case N_STSYM:
3841           // static symbol: name,,n_sect,type,address
3842           N_STSYM_addr_to_sym_idx.insert(
3843               std::make_pair(nlist.n_value, sym_idx));
3844           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3845           if (symbol_name && symbol_name[0]) {
3846             type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
3847                                                      eSymbolTypeData);
3848           }
3849           break;
3850 
3851         case N_LCSYM:
3852           // .lcomm symbol: name,,n_sect,type,address
3853           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3854           type = eSymbolTypeCommonBlock;
3855           break;
3856 
3857         case N_BNSYM:
3858           // We use the current number of symbols in the symbol table in lieu
3859           // of using nlist_idx in case we ever start trimming entries out
3860           // Skip these if we want minimal symbol tables
3861           add_nlist = false;
3862           break;
3863 
3864         case N_ENSYM:
3865           // Set the size of the N_BNSYM to the terminating index of this
3866           // N_ENSYM so that we can always skip the entire symbol if we need
3867           // to navigate more quickly at the source level when parsing STABS
3868           // Skip these if we want minimal symbol tables
3869           add_nlist = false;
3870           break;
3871 
3872         case N_OPT:
3873           // emitted with gcc2_compiled and in gcc source
3874           type = eSymbolTypeCompiler;
3875           break;
3876 
3877         case N_RSYM:
3878           // register sym: name,,NO_SECT,type,register
3879           type = eSymbolTypeVariable;
3880           break;
3881 
3882         case N_SLINE:
3883           // src line: 0,,n_sect,linenumber,address
3884           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3885           type = eSymbolTypeLineEntry;
3886           break;
3887 
3888         case N_SSYM:
3889           // structure elt: name,,NO_SECT,type,struct_offset
3890           type = eSymbolTypeVariableType;
3891           break;
3892 
3893         case N_SO:
3894           // source file name
3895           type = eSymbolTypeSourceFile;
3896           if (symbol_name == nullptr) {
3897             add_nlist = false;
3898             if (N_SO_index != UINT32_MAX) {
3899               // Set the size of the N_SO to the terminating index of this
3900               // N_SO so that we can always skip the entire N_SO if we need
3901               // to navigate more quickly at the source level when parsing
3902               // STABS
3903               symbol_ptr = symtab.SymbolAtIndex(N_SO_index);
3904               symbol_ptr->SetByteSize(sym_idx);
3905               symbol_ptr->SetSizeIsSibling(true);
3906             }
3907             N_NSYM_indexes.clear();
3908             N_INCL_indexes.clear();
3909             N_BRAC_indexes.clear();
3910             N_COMM_indexes.clear();
3911             N_FUN_indexes.clear();
3912             N_SO_index = UINT32_MAX;
3913           } else {
3914             // We use the current number of symbols in the symbol table in
3915             // lieu of using nlist_idx in case we ever start trimming entries
3916             // out
3917             const bool N_SO_has_full_path = symbol_name[0] == '/';
3918             if (N_SO_has_full_path) {
3919               if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3920                 // We have two consecutive N_SO entries where the first
3921                 // contains a directory and the second contains a full path.
3922                 sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name),
3923                                                        false);
3924                 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3925                 add_nlist = false;
3926               } else {
3927                 // This is the first entry in a N_SO that contains a
3928                 // directory or a full path to the source file
3929                 N_SO_index = sym_idx;
3930               }
3931             } else if ((N_SO_index == sym_idx - 1) &&
3932                        ((sym_idx - 1) < num_syms)) {
3933               // This is usually the second N_SO entry that contains just the
3934               // filename, so here we combine it with the first one if we are
3935               // minimizing the symbol table
3936               const char *so_path =
3937                   sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString();
3938               if (so_path && so_path[0]) {
3939                 std::string full_so_path(so_path);
3940                 const size_t double_slash_pos = full_so_path.find("//");
3941                 if (double_slash_pos != std::string::npos) {
3942                   // The linker has been generating bad N_SO entries with
3943                   // doubled up paths in the format "%s%s" where the first
3944                   // string in the DW_AT_comp_dir, and the second is the
3945                   // directory for the source file so you end up with a path
3946                   // that looks like "/tmp/src//tmp/src/"
3947                   FileSpec so_dir(so_path);
3948                   if (!FileSystem::Instance().Exists(so_dir)) {
3949                     so_dir.SetFile(&full_so_path[double_slash_pos + 1],
3950                                    FileSpec::Style::native);
3951                     if (FileSystem::Instance().Exists(so_dir)) {
3952                       // Trim off the incorrect path
3953                       full_so_path.erase(0, double_slash_pos + 1);
3954                     }
3955                   }
3956                 }
3957                 if (*full_so_path.rbegin() != '/')
3958                   full_so_path += '/';
3959                 full_so_path += symbol_name;
3960                 sym[sym_idx - 1].GetMangled().SetValue(
3961                     ConstString(full_so_path.c_str()), false);
3962                 add_nlist = false;
3963                 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3964               }
3965             } else {
3966               // This could be a relative path to a N_SO
3967               N_SO_index = sym_idx;
3968             }
3969           }
3970           break;
3971 
3972         case N_OSO:
3973           // object file name: name,,0,0,st_mtime
3974           type = eSymbolTypeObjectFile;
3975           break;
3976 
3977         case N_LSYM:
3978           // local sym: name,,NO_SECT,type,offset
3979           type = eSymbolTypeLocal;
3980           break;
3981 
3982         // INCL scopes
3983         case N_BINCL:
3984           // include file beginning: name,,NO_SECT,0,sum We use the current
3985           // number of symbols in the symbol table in lieu of using nlist_idx
3986           // in case we ever start trimming entries out
3987           N_INCL_indexes.push_back(sym_idx);
3988           type = eSymbolTypeScopeBegin;
3989           break;
3990 
3991         case N_EINCL:
3992           // include file end: name,,NO_SECT,0,0
3993           // Set the size of the N_BINCL to the terminating index of this
3994           // N_EINCL so that we can always skip the entire symbol if we need
3995           // to navigate more quickly at the source level when parsing STABS
3996           if (!N_INCL_indexes.empty()) {
3997             symbol_ptr = symtab.SymbolAtIndex(N_INCL_indexes.back());
3998             symbol_ptr->SetByteSize(sym_idx + 1);
3999             symbol_ptr->SetSizeIsSibling(true);
4000             N_INCL_indexes.pop_back();
4001           }
4002           type = eSymbolTypeScopeEnd;
4003           break;
4004 
4005         case N_SOL:
4006           // #included file name: name,,n_sect,0,address
4007           type = eSymbolTypeHeaderFile;
4008 
4009           // We currently don't use the header files on darwin
4010           add_nlist = false;
4011           break;
4012 
4013         case N_PARAMS:
4014           // compiler parameters: name,,NO_SECT,0,0
4015           type = eSymbolTypeCompiler;
4016           break;
4017 
4018         case N_VERSION:
4019           // compiler version: name,,NO_SECT,0,0
4020           type = eSymbolTypeCompiler;
4021           break;
4022 
4023         case N_OLEVEL:
4024           // compiler -O level: name,,NO_SECT,0,0
4025           type = eSymbolTypeCompiler;
4026           break;
4027 
4028         case N_PSYM:
4029           // parameter: name,,NO_SECT,type,offset
4030           type = eSymbolTypeVariable;
4031           break;
4032 
4033         case N_ENTRY:
4034           // alternate entry: name,,n_sect,linenumber,address
4035           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4036           type = eSymbolTypeLineEntry;
4037           break;
4038 
4039         // Left and Right Braces
4040         case N_LBRAC:
4041           // left bracket: 0,,NO_SECT,nesting level,address We use the
4042           // current number of symbols in the symbol table in lieu of using
4043           // nlist_idx in case we ever start trimming entries out
4044           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4045           N_BRAC_indexes.push_back(sym_idx);
4046           type = eSymbolTypeScopeBegin;
4047           break;
4048 
4049         case N_RBRAC:
4050           // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4051           // the N_LBRAC to the terminating index of this N_RBRAC so that we
4052           // can always skip the entire symbol if we need to navigate more
4053           // quickly at the source level when parsing STABS
4054           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4055           if (!N_BRAC_indexes.empty()) {
4056             symbol_ptr = symtab.SymbolAtIndex(N_BRAC_indexes.back());
4057             symbol_ptr->SetByteSize(sym_idx + 1);
4058             symbol_ptr->SetSizeIsSibling(true);
4059             N_BRAC_indexes.pop_back();
4060           }
4061           type = eSymbolTypeScopeEnd;
4062           break;
4063 
4064         case N_EXCL:
4065           // deleted include file: name,,NO_SECT,0,sum
4066           type = eSymbolTypeHeaderFile;
4067           break;
4068 
4069         // COMM scopes
4070         case N_BCOMM:
4071           // begin common: name,,NO_SECT,0,0
4072           // We use the current number of symbols in the symbol table in lieu
4073           // of using nlist_idx in case we ever start trimming entries out
4074           type = eSymbolTypeScopeBegin;
4075           N_COMM_indexes.push_back(sym_idx);
4076           break;
4077 
4078         case N_ECOML:
4079           // end common (local name): 0,,n_sect,0,address
4080           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4081           LLVM_FALLTHROUGH;
4082 
4083         case N_ECOMM:
4084           // end common: name,,n_sect,0,0
4085           // Set the size of the N_BCOMM to the terminating index of this
4086           // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4087           // we need to navigate more quickly at the source level when
4088           // parsing STABS
4089           if (!N_COMM_indexes.empty()) {
4090             symbol_ptr = symtab.SymbolAtIndex(N_COMM_indexes.back());
4091             symbol_ptr->SetByteSize(sym_idx + 1);
4092             symbol_ptr->SetSizeIsSibling(true);
4093             N_COMM_indexes.pop_back();
4094           }
4095           type = eSymbolTypeScopeEnd;
4096           break;
4097 
4098         case N_LENG:
4099           // second stab entry with length information
4100           type = eSymbolTypeAdditional;
4101           break;
4102 
4103         default:
4104           break;
4105         }
4106       } else {
4107         uint8_t n_type = N_TYPE & nlist.n_type;
4108         sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4109 
4110         switch (n_type) {
4111         case N_INDR: {
4112           const char *reexport_name_cstr = strtab_data.PeekCStr(nlist.n_value);
4113           if (reexport_name_cstr && reexport_name_cstr[0]) {
4114             type = eSymbolTypeReExported;
4115             ConstString reexport_name(reexport_name_cstr +
4116                                       ((reexport_name_cstr[0] == '_') ? 1 : 0));
4117             sym[sym_idx].SetReExportedSymbolName(reexport_name);
4118             set_value = false;
4119             reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4120             indirect_symbol_names.insert(
4121                 ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4122           } else
4123             type = eSymbolTypeUndefined;
4124         } break;
4125 
4126         case N_UNDF:
4127           if (symbol_name && symbol_name[0]) {
4128             ConstString undefined_name(symbol_name +
4129                                        ((symbol_name[0] == '_') ? 1 : 0));
4130             undefined_name_to_desc[undefined_name] = nlist.n_desc;
4131           }
4132           LLVM_FALLTHROUGH;
4133 
4134         case N_PBUD:
4135           type = eSymbolTypeUndefined;
4136           break;
4137 
4138         case N_ABS:
4139           type = eSymbolTypeAbsolute;
4140           break;
4141 
4142         case N_SECT: {
4143           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4144 
4145           if (!symbol_section) {
4146             // TODO: warn about this?
4147             add_nlist = false;
4148             break;
4149           }
4150 
4151           if (TEXT_eh_frame_sectID == nlist.n_sect) {
4152             type = eSymbolTypeException;
4153           } else {
4154             uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4155 
4156             switch (section_type) {
4157             case S_CSTRING_LITERALS:
4158               type = eSymbolTypeData;
4159               break; // section with only literal C strings
4160             case S_4BYTE_LITERALS:
4161               type = eSymbolTypeData;
4162               break; // section with only 4 byte literals
4163             case S_8BYTE_LITERALS:
4164               type = eSymbolTypeData;
4165               break; // section with only 8 byte literals
4166             case S_LITERAL_POINTERS:
4167               type = eSymbolTypeTrampoline;
4168               break; // section with only pointers to literals
4169             case S_NON_LAZY_SYMBOL_POINTERS:
4170               type = eSymbolTypeTrampoline;
4171               break; // section with only non-lazy symbol pointers
4172             case S_LAZY_SYMBOL_POINTERS:
4173               type = eSymbolTypeTrampoline;
4174               break; // section with only lazy symbol pointers
4175             case S_SYMBOL_STUBS:
4176               type = eSymbolTypeTrampoline;
4177               break; // section with only symbol stubs, byte size of stub in
4178                      // the reserved2 field
4179             case S_MOD_INIT_FUNC_POINTERS:
4180               type = eSymbolTypeCode;
4181               break; // section with only function pointers for initialization
4182             case S_MOD_TERM_FUNC_POINTERS:
4183               type = eSymbolTypeCode;
4184               break; // section with only function pointers for termination
4185             case S_INTERPOSING:
4186               type = eSymbolTypeTrampoline;
4187               break; // section with only pairs of function pointers for
4188                      // interposing
4189             case S_16BYTE_LITERALS:
4190               type = eSymbolTypeData;
4191               break; // section with only 16 byte literals
4192             case S_DTRACE_DOF:
4193               type = eSymbolTypeInstrumentation;
4194               break;
4195             case S_LAZY_DYLIB_SYMBOL_POINTERS:
4196               type = eSymbolTypeTrampoline;
4197               break;
4198             default:
4199               switch (symbol_section->GetType()) {
4200               case lldb::eSectionTypeCode:
4201                 type = eSymbolTypeCode;
4202                 break;
4203               case eSectionTypeData:
4204               case eSectionTypeDataCString:         // Inlined C string data
4205               case eSectionTypeDataCStringPointers: // Pointers to C string
4206                                                     // data
4207               case eSectionTypeDataSymbolAddress:   // Address of a symbol in
4208                                                     // the symbol table
4209               case eSectionTypeData4:
4210               case eSectionTypeData8:
4211               case eSectionTypeData16:
4212                 type = eSymbolTypeData;
4213                 break;
4214               default:
4215                 break;
4216               }
4217               break;
4218             }
4219 
4220             if (type == eSymbolTypeInvalid) {
4221               const char *symbol_sect_name =
4222                   symbol_section->GetName().AsCString();
4223               if (symbol_section->IsDescendant(text_section_sp.get())) {
4224                 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4225                                             S_ATTR_SELF_MODIFYING_CODE |
4226                                             S_ATTR_SOME_INSTRUCTIONS))
4227                   type = eSymbolTypeData;
4228                 else
4229                   type = eSymbolTypeCode;
4230               } else if (symbol_section->IsDescendant(data_section_sp.get()) ||
4231                          symbol_section->IsDescendant(
4232                              data_dirty_section_sp.get()) ||
4233                          symbol_section->IsDescendant(
4234                              data_const_section_sp.get())) {
4235                 if (symbol_sect_name &&
4236                     ::strstr(symbol_sect_name, "__objc") == symbol_sect_name) {
4237                   type = eSymbolTypeRuntime;
4238 
4239                   if (symbol_name) {
4240                     llvm::StringRef symbol_name_ref(symbol_name);
4241                     if (symbol_name_ref.startswith("_OBJC_")) {
4242                       llvm::StringRef g_objc_v2_prefix_class(
4243                           "_OBJC_CLASS_$_");
4244                       llvm::StringRef g_objc_v2_prefix_metaclass(
4245                           "_OBJC_METACLASS_$_");
4246                       llvm::StringRef g_objc_v2_prefix_ivar(
4247                           "_OBJC_IVAR_$_");
4248                       if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
4249                         symbol_name_non_abi_mangled = symbol_name + 1;
4250                         symbol_name =
4251                             symbol_name + g_objc_v2_prefix_class.size();
4252                         type = eSymbolTypeObjCClass;
4253                         demangled_is_synthesized = true;
4254                       } else if (symbol_name_ref.startswith(
4255                                      g_objc_v2_prefix_metaclass)) {
4256                         symbol_name_non_abi_mangled = symbol_name + 1;
4257                         symbol_name =
4258                             symbol_name + g_objc_v2_prefix_metaclass.size();
4259                         type = eSymbolTypeObjCMetaClass;
4260                         demangled_is_synthesized = true;
4261                       } else if (symbol_name_ref.startswith(
4262                                      g_objc_v2_prefix_ivar)) {
4263                         symbol_name_non_abi_mangled = symbol_name + 1;
4264                         symbol_name =
4265                             symbol_name + g_objc_v2_prefix_ivar.size();
4266                         type = eSymbolTypeObjCIVar;
4267                         demangled_is_synthesized = true;
4268                       }
4269                     }
4270                   }
4271                 } else if (symbol_sect_name &&
4272                            ::strstr(symbol_sect_name, "__gcc_except_tab") ==
4273                                symbol_sect_name) {
4274                   type = eSymbolTypeException;
4275                 } else {
4276                   type = eSymbolTypeData;
4277                 }
4278               } else if (symbol_sect_name &&
4279                          ::strstr(symbol_sect_name, "__IMPORT") ==
4280                              symbol_sect_name) {
4281                 type = eSymbolTypeTrampoline;
4282               } else if (symbol_section->IsDescendant(objc_section_sp.get())) {
4283                 type = eSymbolTypeRuntime;
4284                 if (symbol_name && symbol_name[0] == '.') {
4285                   llvm::StringRef symbol_name_ref(symbol_name);
4286                   llvm::StringRef g_objc_v1_prefix_class(
4287                       ".objc_class_name_");
4288                   if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) {
4289                     symbol_name_non_abi_mangled = symbol_name;
4290                     symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4291                     type = eSymbolTypeObjCClass;
4292                     demangled_is_synthesized = true;
4293                   }
4294                 }
4295               }
4296             }
4297           }
4298         } break;
4299         }
4300       }
4301 
4302       if (!add_nlist) {
4303         sym[sym_idx].Clear();
4304         return true;
4305       }
4306 
4307       uint64_t symbol_value = nlist.n_value;
4308 
4309       if (symbol_name_non_abi_mangled) {
4310         sym[sym_idx].GetMangled().SetMangledName(
4311             ConstString(symbol_name_non_abi_mangled));
4312         sym[sym_idx].GetMangled().SetDemangledName(ConstString(symbol_name));
4313       } else {
4314         bool symbol_name_is_mangled = false;
4315 
4316         if (symbol_name && symbol_name[0] == '_') {
4317           symbol_name_is_mangled = symbol_name[1] == '_';
4318           symbol_name++; // Skip the leading underscore
4319         }
4320 
4321         if (symbol_name) {
4322           ConstString const_symbol_name(symbol_name);
4323           sym[sym_idx].GetMangled().SetValue(const_symbol_name,
4324                                              symbol_name_is_mangled);
4325         }
4326       }
4327 
4328       if (is_gsym) {
4329         const char *gsym_name = sym[sym_idx]
4330                                     .GetMangled()
4331                                     .GetName(Mangled::ePreferMangled)
4332                                     .GetCString();
4333         if (gsym_name)
4334           N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4335       }
4336 
4337       if (symbol_section) {
4338         const addr_t section_file_addr = symbol_section->GetFileAddress();
4339         if (symbol_byte_size == 0 && function_starts_count > 0) {
4340           addr_t symbol_lookup_file_addr = nlist.n_value;
4341           // Do an exact address match for non-ARM addresses, else get the
4342           // closest since the symbol might be a thumb symbol which has an
4343           // address with bit zero set.
4344           FunctionStarts::Entry *func_start_entry =
4345               function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
4346           if (is_arm && func_start_entry) {
4347             // Verify that the function start address is the symbol address
4348             // (ARM) or the symbol address + 1 (thumb).
4349             if (func_start_entry->addr != symbol_lookup_file_addr &&
4350                 func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4351               // Not the right entry, NULL it out...
4352               func_start_entry = nullptr;
4353             }
4354           }
4355           if (func_start_entry) {
4356             func_start_entry->data = true;
4357 
4358             addr_t symbol_file_addr = func_start_entry->addr;
4359             if (is_arm)
4360               symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4361 
4362             const FunctionStarts::Entry *next_func_start_entry =
4363                 function_starts.FindNextEntry(func_start_entry);
4364             const addr_t section_end_file_addr =
4365                 section_file_addr + symbol_section->GetByteSize();
4366             if (next_func_start_entry) {
4367               addr_t next_symbol_file_addr = next_func_start_entry->addr;
4368               // Be sure the clear the Thumb address bit when we calculate the
4369               // size from the current and next address
4370               if (is_arm)
4371                 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4372               symbol_byte_size = std::min<lldb::addr_t>(
4373                   next_symbol_file_addr - symbol_file_addr,
4374                   section_end_file_addr - symbol_file_addr);
4375             } else {
4376               symbol_byte_size = section_end_file_addr - symbol_file_addr;
4377             }
4378           }
4379         }
4380         symbol_value -= section_file_addr;
4381       }
4382 
4383       if (!is_debug) {
4384         if (type == eSymbolTypeCode) {
4385           // See if we can find a N_FUN entry for any code symbols. If we do
4386           // find a match, and the name matches, then we can merge the two into
4387           // just the function symbol to avoid duplicate entries in the symbol
4388           // table.
4389           std::pair<ValueToSymbolIndexMap::const_iterator,
4390                     ValueToSymbolIndexMap::const_iterator>
4391               range;
4392           range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4393           if (range.first != range.second) {
4394             for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4395                  pos != range.second; ++pos) {
4396               if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) ==
4397                   sym[pos->second].GetMangled().GetName(
4398                       Mangled::ePreferMangled)) {
4399                 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4400                 // We just need the flags from the linker symbol, so put these
4401                 // flags into the N_FUN flags to avoid duplicate symbols in the
4402                 // symbol table.
4403                 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4404                 sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4405                 if (resolver_addresses.find(nlist.n_value) !=
4406                     resolver_addresses.end())
4407                   sym[pos->second].SetType(eSymbolTypeResolver);
4408                 sym[sym_idx].Clear();
4409                 return true;
4410               }
4411             }
4412           } else {
4413             if (resolver_addresses.find(nlist.n_value) !=
4414                 resolver_addresses.end())
4415               type = eSymbolTypeResolver;
4416           }
4417         } else if (type == eSymbolTypeData || type == eSymbolTypeObjCClass ||
4418                    type == eSymbolTypeObjCMetaClass ||
4419                    type == eSymbolTypeObjCIVar) {
4420           // See if we can find a N_STSYM entry for any data symbols. If we do
4421           // find a match, and the name matches, then we can merge the two into
4422           // just the Static symbol to avoid duplicate entries in the symbol
4423           // table.
4424           std::pair<ValueToSymbolIndexMap::const_iterator,
4425                     ValueToSymbolIndexMap::const_iterator>
4426               range;
4427           range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4428           if (range.first != range.second) {
4429             for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4430                  pos != range.second; ++pos) {
4431               if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) ==
4432                   sym[pos->second].GetMangled().GetName(
4433                       Mangled::ePreferMangled)) {
4434                 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4435                 // We just need the flags from the linker symbol, so put these
4436                 // flags into the N_STSYM flags to avoid duplicate symbols in
4437                 // the symbol table.
4438                 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4439                 sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4440                 sym[sym_idx].Clear();
4441                 return true;
4442               }
4443             }
4444           } else {
4445             // Combine N_GSYM stab entries with the non stab symbol.
4446             const char *gsym_name = sym[sym_idx]
4447                                         .GetMangled()
4448                                         .GetName(Mangled::ePreferMangled)
4449                                         .GetCString();
4450             if (gsym_name) {
4451               ConstNameToSymbolIndexMap::const_iterator pos =
4452                   N_GSYM_name_to_sym_idx.find(gsym_name);
4453               if (pos != N_GSYM_name_to_sym_idx.end()) {
4454                 const uint32_t GSYM_sym_idx = pos->second;
4455                 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
4456                 // Copy the address, because often the N_GSYM address has an
4457                 // invalid address of zero when the global is a common symbol.
4458                 sym[GSYM_sym_idx].GetAddressRef().SetSection(symbol_section);
4459                 sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4460                 add_symbol_addr(
4461                     sym[GSYM_sym_idx].GetAddress().GetFileAddress());
4462                 // We just need the flags from the linker symbol, so put these
4463                 // flags into the N_GSYM flags to avoid duplicate symbols in
4464                 // the symbol table.
4465                 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4466                 sym[sym_idx].Clear();
4467                 return true;
4468               }
4469             }
4470           }
4471         }
4472       }
4473 
4474       sym[sym_idx].SetID(nlist_idx);
4475       sym[sym_idx].SetType(type);
4476       if (set_value) {
4477         sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4478         sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4479         if (symbol_section)
4480           add_symbol_addr(sym[sym_idx].GetAddress().GetFileAddress());
4481       }
4482       sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4483       if (nlist.n_desc & N_WEAK_REF)
4484         sym[sym_idx].SetIsWeak(true);
4485 
4486       if (symbol_byte_size > 0)
4487         sym[sym_idx].SetByteSize(symbol_byte_size);
4488 
4489       if (demangled_is_synthesized)
4490         sym[sym_idx].SetDemangledNameIsSynthesized(true);
4491 
4492       ++sym_idx;
4493       return true;
4494     };
4495 
4496     // First parse all the nlists but don't process them yet. See the next
4497     // comment for an explanation why.
4498     std::vector<struct nlist_64> nlists;
4499     nlists.reserve(symtab_load_command.nsyms);
4500     for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
4501       if (auto nlist =
4502               ParseNList(nlist_data, nlist_data_offset, nlist_byte_size))
4503         nlists.push_back(*nlist);
4504       else
4505         break;
4506     }
4507 
4508     // Now parse all the debug symbols. This is needed to merge non-debug
4509     // symbols in the next step. Non-debug symbols are always coalesced into
4510     // the debug symbol. Doing this in one step would mean that some symbols
4511     // won't be merged.
4512     nlist_idx = 0;
4513     for (auto &nlist : nlists) {
4514       if (!ParseSymbolLambda(nlist, nlist_idx++, DebugSymbols))
4515         break;
4516     }
4517 
4518     // Finally parse all the non debug symbols.
4519     nlist_idx = 0;
4520     for (auto &nlist : nlists) {
4521       if (!ParseSymbolLambda(nlist, nlist_idx++, NonDebugSymbols))
4522         break;
4523     }
4524 
4525     for (const auto &pos : reexport_shlib_needs_fixup) {
4526       const auto undef_pos = undefined_name_to_desc.find(pos.second);
4527       if (undef_pos != undefined_name_to_desc.end()) {
4528         const uint8_t dylib_ordinal =
4529             llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4530         if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4531           sym[pos.first].SetReExportedSymbolSharedLibrary(
4532               dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
4533       }
4534     }
4535   }
4536 
4537   // Count how many trie symbols we'll add to the symbol table
4538   int trie_symbol_table_augment_count = 0;
4539   for (auto &e : external_sym_trie_entries) {
4540     if (symbols_added.find(e.entry.address) == symbols_added.end())
4541       trie_symbol_table_augment_count++;
4542   }
4543 
4544   if (num_syms < sym_idx + trie_symbol_table_augment_count) {
4545     num_syms = sym_idx + trie_symbol_table_augment_count;
4546     sym = symtab.Resize(num_syms);
4547   }
4548   uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4549 
4550   // Add symbols from the trie to the symbol table.
4551   for (auto &e : external_sym_trie_entries) {
4552     if (symbols_added.contains(e.entry.address))
4553       continue;
4554 
4555     // Find the section that this trie address is in, use that to annotate
4556     // symbol type as we add the trie address and name to the symbol table.
4557     Address symbol_addr;
4558     if (module_sp->ResolveFileAddress(e.entry.address, symbol_addr)) {
4559       SectionSP symbol_section(symbol_addr.GetSection());
4560       const char *symbol_name = e.entry.name.GetCString();
4561       bool demangled_is_synthesized = false;
4562       SymbolType type =
4563           GetSymbolType(symbol_name, demangled_is_synthesized, text_section_sp,
4564                         data_section_sp, data_dirty_section_sp,
4565                         data_const_section_sp, symbol_section);
4566 
4567       sym[sym_idx].SetType(type);
4568       if (symbol_section) {
4569         sym[sym_idx].SetID(synthetic_sym_id++);
4570         sym[sym_idx].GetMangled().SetMangledName(ConstString(symbol_name));
4571         if (demangled_is_synthesized)
4572           sym[sym_idx].SetDemangledNameIsSynthesized(true);
4573         sym[sym_idx].SetIsSynthetic(true);
4574         sym[sym_idx].SetExternal(true);
4575         sym[sym_idx].GetAddressRef() = symbol_addr;
4576         add_symbol_addr(symbol_addr.GetFileAddress());
4577         if (e.entry.flags & TRIE_SYMBOL_IS_THUMB)
4578           sym[sym_idx].SetFlags(MACHO_NLIST_ARM_SYMBOL_IS_THUMB);
4579         ++sym_idx;
4580       }
4581     }
4582   }
4583 
4584   if (function_starts_count > 0) {
4585     uint32_t num_synthetic_function_symbols = 0;
4586     for (i = 0; i < function_starts_count; ++i) {
4587       if (symbols_added.find(function_starts.GetEntryRef(i).addr) ==
4588           symbols_added.end())
4589         ++num_synthetic_function_symbols;
4590     }
4591 
4592     if (num_synthetic_function_symbols > 0) {
4593       if (num_syms < sym_idx + num_synthetic_function_symbols) {
4594         num_syms = sym_idx + num_synthetic_function_symbols;
4595         sym = symtab.Resize(num_syms);
4596       }
4597       for (i = 0; i < function_starts_count; ++i) {
4598         const FunctionStarts::Entry *func_start_entry =
4599             function_starts.GetEntryAtIndex(i);
4600         if (symbols_added.find(func_start_entry->addr) == symbols_added.end()) {
4601           addr_t symbol_file_addr = func_start_entry->addr;
4602           uint32_t symbol_flags = 0;
4603           if (func_start_entry->data)
4604             symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4605           Address symbol_addr;
4606           if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
4607             SectionSP symbol_section(symbol_addr.GetSection());
4608             uint32_t symbol_byte_size = 0;
4609             if (symbol_section) {
4610               const addr_t section_file_addr = symbol_section->GetFileAddress();
4611               const FunctionStarts::Entry *next_func_start_entry =
4612                   function_starts.FindNextEntry(func_start_entry);
4613               const addr_t section_end_file_addr =
4614                   section_file_addr + symbol_section->GetByteSize();
4615               if (next_func_start_entry) {
4616                 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4617                 if (is_arm)
4618                   next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4619                 symbol_byte_size = std::min<lldb::addr_t>(
4620                     next_symbol_file_addr - symbol_file_addr,
4621                     section_end_file_addr - symbol_file_addr);
4622               } else {
4623                 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4624               }
4625               sym[sym_idx].SetID(synthetic_sym_id++);
4626               // Don't set the name for any synthetic symbols, the Symbol
4627               // object will generate one if needed when the name is accessed
4628               // via accessors.
4629               sym[sym_idx].GetMangled().SetDemangledName(ConstString());
4630               sym[sym_idx].SetType(eSymbolTypeCode);
4631               sym[sym_idx].SetIsSynthetic(true);
4632               sym[sym_idx].GetAddressRef() = symbol_addr;
4633               add_symbol_addr(symbol_addr.GetFileAddress());
4634               if (symbol_flags)
4635                 sym[sym_idx].SetFlags(symbol_flags);
4636               if (symbol_byte_size)
4637                 sym[sym_idx].SetByteSize(symbol_byte_size);
4638               ++sym_idx;
4639             }
4640           }
4641         }
4642       }
4643     }
4644   }
4645 
4646   // Trim our symbols down to just what we ended up with after removing any
4647   // symbols.
4648   if (sym_idx < num_syms) {
4649     num_syms = sym_idx;
4650     sym = symtab.Resize(num_syms);
4651   }
4652 
4653   // Now synthesize indirect symbols
4654   if (m_dysymtab.nindirectsyms != 0) {
4655     if (indirect_symbol_index_data.GetByteSize()) {
4656       NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4657           m_nlist_idx_to_sym_idx.end();
4658 
4659       for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4660            ++sect_idx) {
4661         if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4662             S_SYMBOL_STUBS) {
4663           uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2;
4664           if (symbol_stub_byte_size == 0)
4665             continue;
4666 
4667           const uint32_t num_symbol_stubs =
4668               m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4669 
4670           if (num_symbol_stubs == 0)
4671             continue;
4672 
4673           const uint32_t symbol_stub_index_offset =
4674               m_mach_sections[sect_idx].reserved1;
4675           for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx) {
4676             const uint32_t symbol_stub_index =
4677                 symbol_stub_index_offset + stub_idx;
4678             const lldb::addr_t symbol_stub_addr =
4679                 m_mach_sections[sect_idx].addr +
4680                 (stub_idx * symbol_stub_byte_size);
4681             lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4682             if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4683                     symbol_stub_offset, 4)) {
4684               const uint32_t stub_sym_id =
4685                   indirect_symbol_index_data.GetU32(&symbol_stub_offset);
4686               if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4687                 continue;
4688 
4689               NListIndexToSymbolIndexMap::const_iterator index_pos =
4690                   m_nlist_idx_to_sym_idx.find(stub_sym_id);
4691               Symbol *stub_symbol = nullptr;
4692               if (index_pos != end_index_pos) {
4693                 // We have a remapping from the original nlist index to a
4694                 // current symbol index, so just look this up by index
4695                 stub_symbol = symtab.SymbolAtIndex(index_pos->second);
4696               } else {
4697                 // We need to lookup a symbol using the original nlist symbol
4698                 // index since this index is coming from the S_SYMBOL_STUBS
4699                 stub_symbol = symtab.FindSymbolByID(stub_sym_id);
4700               }
4701 
4702               if (stub_symbol) {
4703                 Address so_addr(symbol_stub_addr, section_list);
4704 
4705                 if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4706                   // Change the external symbol into a trampoline that makes
4707                   // sense These symbols were N_UNDF N_EXT, and are useless
4708                   // to us, so we can re-use them so we don't have to make up
4709                   // a synthetic symbol for no good reason.
4710                   if (resolver_addresses.find(symbol_stub_addr) ==
4711                       resolver_addresses.end())
4712                     stub_symbol->SetType(eSymbolTypeTrampoline);
4713                   else
4714                     stub_symbol->SetType(eSymbolTypeResolver);
4715                   stub_symbol->SetExternal(false);
4716                   stub_symbol->GetAddressRef() = so_addr;
4717                   stub_symbol->SetByteSize(symbol_stub_byte_size);
4718                 } else {
4719                   // Make a synthetic symbol to describe the trampoline stub
4720                   Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4721                   if (sym_idx >= num_syms) {
4722                     sym = symtab.Resize(++num_syms);
4723                     stub_symbol = nullptr; // this pointer no longer valid
4724                   }
4725                   sym[sym_idx].SetID(synthetic_sym_id++);
4726                   sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4727                   if (resolver_addresses.find(symbol_stub_addr) ==
4728                       resolver_addresses.end())
4729                     sym[sym_idx].SetType(eSymbolTypeTrampoline);
4730                   else
4731                     sym[sym_idx].SetType(eSymbolTypeResolver);
4732                   sym[sym_idx].SetIsSynthetic(true);
4733                   sym[sym_idx].GetAddressRef() = so_addr;
4734                   add_symbol_addr(so_addr.GetFileAddress());
4735                   sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4736                   ++sym_idx;
4737                 }
4738               } else {
4739                 if (log)
4740                   log->Warning("symbol stub referencing symbol table symbol "
4741                                "%u that isn't in our minimal symbol table, "
4742                                "fix this!!!",
4743                                stub_sym_id);
4744               }
4745             }
4746           }
4747         }
4748       }
4749     }
4750   }
4751 
4752   if (!reexport_trie_entries.empty()) {
4753     for (const auto &e : reexport_trie_entries) {
4754       if (e.entry.import_name) {
4755         // Only add indirect symbols from the Trie entries if we didn't have
4756         // a N_INDR nlist entry for this already
4757         if (indirect_symbol_names.find(e.entry.name) ==
4758             indirect_symbol_names.end()) {
4759           // Make a synthetic symbol to describe re-exported symbol.
4760           if (sym_idx >= num_syms)
4761             sym = symtab.Resize(++num_syms);
4762           sym[sym_idx].SetID(synthetic_sym_id++);
4763           sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4764           sym[sym_idx].SetType(eSymbolTypeReExported);
4765           sym[sym_idx].SetIsSynthetic(true);
4766           sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4767           if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4768             sym[sym_idx].SetReExportedSymbolSharedLibrary(
4769                 dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
4770           }
4771           ++sym_idx;
4772         }
4773       }
4774     }
4775   }
4776 }
4777 
4778 void ObjectFileMachO::Dump(Stream *s) {
4779   ModuleSP module_sp(GetModule());
4780   if (module_sp) {
4781     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4782     s->Printf("%p: ", static_cast<void *>(this));
4783     s->Indent();
4784     if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4785       s->PutCString("ObjectFileMachO64");
4786     else
4787       s->PutCString("ObjectFileMachO32");
4788 
4789     *s << ", file = '" << m_file;
4790     ModuleSpecList all_specs;
4791     ModuleSpec base_spec;
4792     GetAllArchSpecs(m_header, m_data, MachHeaderSizeFromMagic(m_header.magic),
4793                     base_spec, all_specs);
4794     for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
4795       *s << "', triple";
4796       if (e)
4797         s->Printf("[%d]", i);
4798       *s << " = ";
4799       *s << all_specs.GetModuleSpecRefAtIndex(i)
4800                 .GetArchitecture()
4801                 .GetTriple()
4802                 .getTriple();
4803     }
4804     *s << "\n";
4805     SectionList *sections = GetSectionList();
4806     if (sections)
4807       sections->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
4808                      UINT32_MAX);
4809 
4810     if (m_symtab_up)
4811       m_symtab_up->Dump(s, nullptr, eSortOrderNone);
4812   }
4813 }
4814 
4815 UUID ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4816                               const lldb_private::DataExtractor &data,
4817                               lldb::offset_t lc_offset) {
4818   uint32_t i;
4819   llvm::MachO::uuid_command load_cmd;
4820 
4821   lldb::offset_t offset = lc_offset;
4822   for (i = 0; i < header.ncmds; ++i) {
4823     const lldb::offset_t cmd_offset = offset;
4824     if (data.GetU32(&offset, &load_cmd, 2) == nullptr)
4825       break;
4826 
4827     if (load_cmd.cmd == LC_UUID) {
4828       const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4829 
4830       if (uuid_bytes) {
4831         // OpenCL on Mac OS X uses the same UUID for each of its object files.
4832         // We pretend these object files have no UUID to prevent crashing.
4833 
4834         const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4835                                        0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4836                                        0xbb, 0x14, 0xf0, 0x0d};
4837 
4838         if (!memcmp(uuid_bytes, opencl_uuid, 16))
4839           return UUID();
4840 
4841         return UUID::fromOptionalData(uuid_bytes, 16);
4842       }
4843       return UUID();
4844     }
4845     offset = cmd_offset + load_cmd.cmdsize;
4846   }
4847   return UUID();
4848 }
4849 
4850 static llvm::StringRef GetOSName(uint32_t cmd) {
4851   switch (cmd) {
4852   case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
4853     return llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4854   case llvm::MachO::LC_VERSION_MIN_MACOSX:
4855     return llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4856   case llvm::MachO::LC_VERSION_MIN_TVOS:
4857     return llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4858   case llvm::MachO::LC_VERSION_MIN_WATCHOS:
4859     return llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4860   default:
4861     llvm_unreachable("unexpected LC_VERSION load command");
4862   }
4863 }
4864 
4865 namespace {
4866 struct OSEnv {
4867   llvm::StringRef os_type;
4868   llvm::StringRef environment;
4869   OSEnv(uint32_t cmd) {
4870     switch (cmd) {
4871     case llvm::MachO::PLATFORM_MACOS:
4872       os_type = llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4873       return;
4874     case llvm::MachO::PLATFORM_IOS:
4875       os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4876       return;
4877     case llvm::MachO::PLATFORM_TVOS:
4878       os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4879       return;
4880     case llvm::MachO::PLATFORM_WATCHOS:
4881       os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4882       return;
4883     // TODO: add BridgeOS & DriverKit once in llvm/lib/Support/Triple.cpp
4884     // NEED_BRIDGEOS_TRIPLE
4885     // case llvm::MachO::PLATFORM_BRIDGEOS:
4886     //   os_type = llvm::Triple::getOSTypeName(llvm::Triple::BridgeOS);
4887     //   return;
4888     // case llvm::MachO::PLATFORM_DRIVERKIT:
4889     //   os_type = llvm::Triple::getOSTypeName(llvm::Triple::DriverKit);
4890     //   return;
4891     case llvm::MachO::PLATFORM_MACCATALYST:
4892       os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4893       environment = llvm::Triple::getEnvironmentTypeName(llvm::Triple::MacABI);
4894       return;
4895     case llvm::MachO::PLATFORM_IOSSIMULATOR:
4896       os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4897       environment =
4898           llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4899       return;
4900     case llvm::MachO::PLATFORM_TVOSSIMULATOR:
4901       os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4902       environment =
4903           llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4904       return;
4905     case llvm::MachO::PLATFORM_WATCHOSSIMULATOR:
4906       os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4907       environment =
4908           llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4909       return;
4910     default: {
4911       Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
4912                                                       LIBLLDB_LOG_PROCESS));
4913       LLDB_LOGF(log, "unsupported platform in LC_BUILD_VERSION");
4914     }
4915     }
4916   }
4917 };
4918 
4919 struct MinOS {
4920   uint32_t major_version, minor_version, patch_version;
4921   MinOS(uint32_t version)
4922       : major_version(version >> 16), minor_version((version >> 8) & 0xffu),
4923         patch_version(version & 0xffu) {}
4924 };
4925 } // namespace
4926 
4927 void ObjectFileMachO::GetAllArchSpecs(const llvm::MachO::mach_header &header,
4928                                       const lldb_private::DataExtractor &data,
4929                                       lldb::offset_t lc_offset,
4930                                       ModuleSpec &base_spec,
4931                                       lldb_private::ModuleSpecList &all_specs) {
4932   auto &base_arch = base_spec.GetArchitecture();
4933   base_arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
4934   if (!base_arch.IsValid())
4935     return;
4936 
4937   bool found_any = false;
4938   auto add_triple = [&](const llvm::Triple &triple) {
4939     auto spec = base_spec;
4940     spec.GetArchitecture().GetTriple() = triple;
4941     if (spec.GetArchitecture().IsValid()) {
4942       spec.GetUUID() = ObjectFileMachO::GetUUID(header, data, lc_offset);
4943       all_specs.Append(spec);
4944       found_any = true;
4945     }
4946   };
4947 
4948   // Set OS to an unspecified unknown or a "*" so it can match any OS
4949   llvm::Triple base_triple = base_arch.GetTriple();
4950   base_triple.setOS(llvm::Triple::UnknownOS);
4951   base_triple.setOSName(llvm::StringRef());
4952 
4953   if (header.filetype == MH_PRELOAD) {
4954     if (header.cputype == CPU_TYPE_ARM) {
4955       // If this is a 32-bit arm binary, and it's a standalone binary, force
4956       // the Vendor to Apple so we don't accidentally pick up the generic
4957       // armv7 ABI at runtime.  Apple's armv7 ABI always uses r7 for the
4958       // frame pointer register; most other armv7 ABIs use a combination of
4959       // r7 and r11.
4960       base_triple.setVendor(llvm::Triple::Apple);
4961     } else {
4962       // Set vendor to an unspecified unknown or a "*" so it can match any
4963       // vendor This is required for correct behavior of EFI debugging on
4964       // x86_64
4965       base_triple.setVendor(llvm::Triple::UnknownVendor);
4966       base_triple.setVendorName(llvm::StringRef());
4967     }
4968     return add_triple(base_triple);
4969   }
4970 
4971   llvm::MachO::load_command load_cmd;
4972 
4973   // See if there is an LC_VERSION_MIN_* load command that can give
4974   // us the OS type.
4975   lldb::offset_t offset = lc_offset;
4976   for (uint32_t i = 0; i < header.ncmds; ++i) {
4977     const lldb::offset_t cmd_offset = offset;
4978     if (data.GetU32(&offset, &load_cmd, 2) == nullptr)
4979       break;
4980 
4981     llvm::MachO::version_min_command version_min;
4982     switch (load_cmd.cmd) {
4983     case llvm::MachO::LC_VERSION_MIN_MACOSX:
4984     case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
4985     case llvm::MachO::LC_VERSION_MIN_TVOS:
4986     case llvm::MachO::LC_VERSION_MIN_WATCHOS: {
4987       if (load_cmd.cmdsize != sizeof(version_min))
4988         break;
4989       if (data.ExtractBytes(cmd_offset, sizeof(version_min),
4990                             data.GetByteOrder(), &version_min) == 0)
4991         break;
4992       MinOS min_os(version_min.version);
4993       llvm::SmallString<32> os_name;
4994       llvm::raw_svector_ostream os(os_name);
4995       os << GetOSName(load_cmd.cmd) << min_os.major_version << '.'
4996          << min_os.minor_version << '.' << min_os.patch_version;
4997 
4998       auto triple = base_triple;
4999       triple.setOSName(os.str());
5000 
5001       // Disambiguate legacy simulator platforms.
5002       if (load_cmd.cmd != llvm::MachO::LC_VERSION_MIN_MACOSX &&
5003           (base_triple.getArch() == llvm::Triple::x86_64 ||
5004            base_triple.getArch() == llvm::Triple::x86)) {
5005         // The combination of legacy LC_VERSION_MIN load command and
5006         // x86 architecture always indicates a simulator environment.
5007         // The combination of LC_VERSION_MIN and arm architecture only
5008         // appears for native binaries. Back-deploying simulator
5009         // binaries on Apple Silicon Macs use the modern unambigous
5010         // LC_BUILD_VERSION load commands; no special handling required.
5011         triple.setEnvironment(llvm::Triple::Simulator);
5012       }
5013       add_triple(triple);
5014       break;
5015     }
5016     default:
5017       break;
5018     }
5019 
5020     offset = cmd_offset + load_cmd.cmdsize;
5021   }
5022 
5023   // See if there are LC_BUILD_VERSION load commands that can give
5024   // us the OS type.
5025   offset = lc_offset;
5026   for (uint32_t i = 0; i < header.ncmds; ++i) {
5027     const lldb::offset_t cmd_offset = offset;
5028     if (data.GetU32(&offset, &load_cmd, 2) == nullptr)
5029       break;
5030 
5031     do {
5032       if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) {
5033         llvm::MachO::build_version_command build_version;
5034         if (load_cmd.cmdsize < sizeof(build_version)) {
5035           // Malformed load command.
5036           break;
5037         }
5038         if (data.ExtractBytes(cmd_offset, sizeof(build_version),
5039                               data.GetByteOrder(), &build_version) == 0)
5040           break;
5041         MinOS min_os(build_version.minos);
5042         OSEnv os_env(build_version.platform);
5043         llvm::SmallString<16> os_name;
5044         llvm::raw_svector_ostream os(os_name);
5045         os << os_env.os_type << min_os.major_version << '.'
5046            << min_os.minor_version << '.' << min_os.patch_version;
5047         auto triple = base_triple;
5048         triple.setOSName(os.str());
5049         os_name.clear();
5050         if (!os_env.environment.empty())
5051           triple.setEnvironmentName(os_env.environment);
5052         add_triple(triple);
5053       }
5054     } while (false);
5055     offset = cmd_offset + load_cmd.cmdsize;
5056   }
5057 
5058   if (!found_any) {
5059     add_triple(base_triple);
5060   }
5061 }
5062 
5063 ArchSpec ObjectFileMachO::GetArchitecture(
5064     ModuleSP module_sp, const llvm::MachO::mach_header &header,
5065     const lldb_private::DataExtractor &data, lldb::offset_t lc_offset) {
5066   ModuleSpecList all_specs;
5067   ModuleSpec base_spec;
5068   GetAllArchSpecs(header, data, MachHeaderSizeFromMagic(header.magic),
5069                   base_spec, all_specs);
5070 
5071   // If the object file offers multiple alternative load commands,
5072   // pick the one that matches the module.
5073   if (module_sp) {
5074     const ArchSpec &module_arch = module_sp->GetArchitecture();
5075     for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
5076       ArchSpec mach_arch =
5077           all_specs.GetModuleSpecRefAtIndex(i).GetArchitecture();
5078       if (module_arch.IsCompatibleMatch(mach_arch))
5079         return mach_arch;
5080     }
5081   }
5082 
5083   // Return the first arch we found.
5084   if (all_specs.GetSize() == 0)
5085     return {};
5086   return all_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
5087 }
5088 
5089 UUID ObjectFileMachO::GetUUID() {
5090   ModuleSP module_sp(GetModule());
5091   if (module_sp) {
5092     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5093     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5094     return GetUUID(m_header, m_data, offset);
5095   }
5096   return UUID();
5097 }
5098 
5099 uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) {
5100   uint32_t count = 0;
5101   ModuleSP module_sp(GetModule());
5102   if (module_sp) {
5103     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5104     llvm::MachO::load_command load_cmd;
5105     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5106     std::vector<std::string> rpath_paths;
5107     std::vector<std::string> rpath_relative_paths;
5108     std::vector<std::string> at_exec_relative_paths;
5109     uint32_t i;
5110     for (i = 0; i < m_header.ncmds; ++i) {
5111       const uint32_t cmd_offset = offset;
5112       if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
5113         break;
5114 
5115       switch (load_cmd.cmd) {
5116       case LC_RPATH:
5117       case LC_LOAD_DYLIB:
5118       case LC_LOAD_WEAK_DYLIB:
5119       case LC_REEXPORT_DYLIB:
5120       case LC_LOAD_DYLINKER:
5121       case LC_LOADFVMLIB:
5122       case LC_LOAD_UPWARD_DYLIB: {
5123         uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
5124         const char *path = m_data.PeekCStr(name_offset);
5125         if (path) {
5126           if (load_cmd.cmd == LC_RPATH)
5127             rpath_paths.push_back(path);
5128           else {
5129             if (path[0] == '@') {
5130               if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
5131                 rpath_relative_paths.push_back(path + strlen("@rpath"));
5132               else if (strncmp(path, "@executable_path",
5133                                strlen("@executable_path")) == 0)
5134                 at_exec_relative_paths.push_back(path +
5135                                                  strlen("@executable_path"));
5136             } else {
5137               FileSpec file_spec(path);
5138               if (files.AppendIfUnique(file_spec))
5139                 count++;
5140             }
5141           }
5142         }
5143       } break;
5144 
5145       default:
5146         break;
5147       }
5148       offset = cmd_offset + load_cmd.cmdsize;
5149     }
5150 
5151     FileSpec this_file_spec(m_file);
5152     FileSystem::Instance().Resolve(this_file_spec);
5153 
5154     if (!rpath_paths.empty()) {
5155       // Fixup all LC_RPATH values to be absolute paths
5156       std::string loader_path("@loader_path");
5157       std::string executable_path("@executable_path");
5158       for (auto &rpath : rpath_paths) {
5159         if (llvm::StringRef(rpath).startswith(loader_path)) {
5160           rpath.erase(0, loader_path.size());
5161           rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5162         } else if (llvm::StringRef(rpath).startswith(executable_path)) {
5163           rpath.erase(0, executable_path.size());
5164           rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5165         }
5166       }
5167 
5168       for (const auto &rpath_relative_path : rpath_relative_paths) {
5169         for (const auto &rpath : rpath_paths) {
5170           std::string path = rpath;
5171           path += rpath_relative_path;
5172           // It is OK to resolve this path because we must find a file on disk
5173           // for us to accept it anyway if it is rpath relative.
5174           FileSpec file_spec(path);
5175           FileSystem::Instance().Resolve(file_spec);
5176           if (FileSystem::Instance().Exists(file_spec) &&
5177               files.AppendIfUnique(file_spec)) {
5178             count++;
5179             break;
5180           }
5181         }
5182       }
5183     }
5184 
5185     // We may have @executable_paths but no RPATHS.  Figure those out here.
5186     // Only do this if this object file is the executable.  We have no way to
5187     // get back to the actual executable otherwise, so we won't get the right
5188     // path.
5189     if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
5190       FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
5191       for (const auto &at_exec_relative_path : at_exec_relative_paths) {
5192         FileSpec file_spec =
5193             exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
5194         if (FileSystem::Instance().Exists(file_spec) &&
5195             files.AppendIfUnique(file_spec))
5196           count++;
5197       }
5198     }
5199   }
5200   return count;
5201 }
5202 
5203 lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
5204   // If the object file is not an executable it can't hold the entry point.
5205   // m_entry_point_address is initialized to an invalid address, so we can just
5206   // return that. If m_entry_point_address is valid it means we've found it
5207   // already, so return the cached value.
5208 
5209   if ((!IsExecutable() && !IsDynamicLoader()) ||
5210       m_entry_point_address.IsValid()) {
5211     return m_entry_point_address;
5212   }
5213 
5214   // Otherwise, look for the UnixThread or Thread command.  The data for the
5215   // Thread command is given in /usr/include/mach-o.h, but it is basically:
5216   //
5217   //  uint32_t flavor  - this is the flavor argument you would pass to
5218   //  thread_get_state
5219   //  uint32_t count   - this is the count of longs in the thread state data
5220   //  struct XXX_thread_state state - this is the structure from
5221   //  <machine/thread_status.h> corresponding to the flavor.
5222   //  <repeat this trio>
5223   //
5224   // So we just keep reading the various register flavors till we find the GPR
5225   // one, then read the PC out of there.
5226   // FIXME: We will need to have a "RegisterContext data provider" class at some
5227   // point that can get all the registers
5228   // out of data in this form & attach them to a given thread.  That should
5229   // underlie the MacOS X User process plugin, and we'll also need it for the
5230   // MacOS X Core File process plugin.  When we have that we can also use it
5231   // here.
5232   //
5233   // For now we hard-code the offsets and flavors we need:
5234   //
5235   //
5236 
5237   ModuleSP module_sp(GetModule());
5238   if (module_sp) {
5239     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5240     llvm::MachO::load_command load_cmd;
5241     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5242     uint32_t i;
5243     lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
5244     bool done = false;
5245 
5246     for (i = 0; i < m_header.ncmds; ++i) {
5247       const lldb::offset_t cmd_offset = offset;
5248       if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
5249         break;
5250 
5251       switch (load_cmd.cmd) {
5252       case LC_UNIXTHREAD:
5253       case LC_THREAD: {
5254         while (offset < cmd_offset + load_cmd.cmdsize) {
5255           uint32_t flavor = m_data.GetU32(&offset);
5256           uint32_t count = m_data.GetU32(&offset);
5257           if (count == 0) {
5258             // We've gotten off somehow, log and exit;
5259             return m_entry_point_address;
5260           }
5261 
5262           switch (m_header.cputype) {
5263           case llvm::MachO::CPU_TYPE_ARM:
5264             if (flavor == 1 ||
5265                 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32
5266                              // from mach/arm/thread_status.h
5267             {
5268               offset += 60; // This is the offset of pc in the GPR thread state
5269                             // data structure.
5270               start_address = m_data.GetU32(&offset);
5271               done = true;
5272             }
5273             break;
5274           case llvm::MachO::CPU_TYPE_ARM64:
5275           case llvm::MachO::CPU_TYPE_ARM64_32:
5276             if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
5277             {
5278               offset += 256; // This is the offset of pc in the GPR thread state
5279                              // data structure.
5280               start_address = m_data.GetU64(&offset);
5281               done = true;
5282             }
5283             break;
5284           case llvm::MachO::CPU_TYPE_I386:
5285             if (flavor ==
5286                 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
5287             {
5288               offset += 40; // This is the offset of eip in the GPR thread state
5289                             // data structure.
5290               start_address = m_data.GetU32(&offset);
5291               done = true;
5292             }
5293             break;
5294           case llvm::MachO::CPU_TYPE_X86_64:
5295             if (flavor ==
5296                 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
5297             {
5298               offset += 16 * 8; // This is the offset of rip in the GPR thread
5299                                 // state data structure.
5300               start_address = m_data.GetU64(&offset);
5301               done = true;
5302             }
5303             break;
5304           default:
5305             return m_entry_point_address;
5306           }
5307           // Haven't found the GPR flavor yet, skip over the data for this
5308           // flavor:
5309           if (done)
5310             break;
5311           offset += count * 4;
5312         }
5313       } break;
5314       case LC_MAIN: {
5315         ConstString text_segment_name("__TEXT");
5316         uint64_t entryoffset = m_data.GetU64(&offset);
5317         SectionSP text_segment_sp =
5318             GetSectionList()->FindSectionByName(text_segment_name);
5319         if (text_segment_sp) {
5320           done = true;
5321           start_address = text_segment_sp->GetFileAddress() + entryoffset;
5322         }
5323       } break;
5324 
5325       default:
5326         break;
5327       }
5328       if (done)
5329         break;
5330 
5331       // Go to the next load command:
5332       offset = cmd_offset + load_cmd.cmdsize;
5333     }
5334 
5335     if (start_address == LLDB_INVALID_ADDRESS && IsDynamicLoader()) {
5336       if (GetSymtab()) {
5337         Symbol *dyld_start_sym = GetSymtab()->FindFirstSymbolWithNameAndType(
5338             ConstString("_dyld_start"), SymbolType::eSymbolTypeCode,
5339             Symtab::eDebugAny, Symtab::eVisibilityAny);
5340         if (dyld_start_sym && dyld_start_sym->GetAddress().IsValid()) {
5341           start_address = dyld_start_sym->GetAddress().GetFileAddress();
5342         }
5343       }
5344     }
5345 
5346     if (start_address != LLDB_INVALID_ADDRESS) {
5347       // We got the start address from the load commands, so now resolve that
5348       // address in the sections of this ObjectFile:
5349       if (!m_entry_point_address.ResolveAddressUsingFileSections(
5350               start_address, GetSectionList())) {
5351         m_entry_point_address.Clear();
5352       }
5353     } else {
5354       // We couldn't read the UnixThread load command - maybe it wasn't there.
5355       // As a fallback look for the "start" symbol in the main executable.
5356 
5357       ModuleSP module_sp(GetModule());
5358 
5359       if (module_sp) {
5360         SymbolContextList contexts;
5361         SymbolContext context;
5362         module_sp->FindSymbolsWithNameAndType(ConstString("start"),
5363                                               eSymbolTypeCode, contexts);
5364         if (contexts.GetSize()) {
5365           if (contexts.GetContextAtIndex(0, context))
5366             m_entry_point_address = context.symbol->GetAddress();
5367         }
5368       }
5369     }
5370   }
5371 
5372   return m_entry_point_address;
5373 }
5374 
5375 lldb_private::Address ObjectFileMachO::GetBaseAddress() {
5376   lldb_private::Address header_addr;
5377   SectionList *section_list = GetSectionList();
5378   if (section_list) {
5379     SectionSP text_segment_sp(
5380         section_list->FindSectionByName(GetSegmentNameTEXT()));
5381     if (text_segment_sp) {
5382       header_addr.SetSection(text_segment_sp);
5383       header_addr.SetOffset(0);
5384     }
5385   }
5386   return header_addr;
5387 }
5388 
5389 uint32_t ObjectFileMachO::GetNumThreadContexts() {
5390   ModuleSP module_sp(GetModule());
5391   if (module_sp) {
5392     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5393     if (!m_thread_context_offsets_valid) {
5394       m_thread_context_offsets_valid = true;
5395       lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5396       FileRangeArray::Entry file_range;
5397       llvm::MachO::thread_command thread_cmd;
5398       for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5399         const uint32_t cmd_offset = offset;
5400         if (m_data.GetU32(&offset, &thread_cmd, 2) == nullptr)
5401           break;
5402 
5403         if (thread_cmd.cmd == LC_THREAD) {
5404           file_range.SetRangeBase(offset);
5405           file_range.SetByteSize(thread_cmd.cmdsize - 8);
5406           m_thread_context_offsets.Append(file_range);
5407         }
5408         offset = cmd_offset + thread_cmd.cmdsize;
5409       }
5410     }
5411   }
5412   return m_thread_context_offsets.GetSize();
5413 }
5414 
5415 std::string ObjectFileMachO::GetIdentifierString() {
5416   std::string result;
5417   ModuleSP module_sp(GetModule());
5418   if (module_sp) {
5419     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5420 
5421     // First, look over the load commands for an LC_NOTE load command with
5422     // data_owner string "kern ver str" & use that if found.
5423     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5424     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5425       const uint32_t cmd_offset = offset;
5426       llvm::MachO::load_command lc;
5427       if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5428         break;
5429       if (lc.cmd == LC_NOTE) {
5430         char data_owner[17];
5431         m_data.CopyData(offset, 16, data_owner);
5432         data_owner[16] = '\0';
5433         offset += 16;
5434         uint64_t fileoff = m_data.GetU64_unchecked(&offset);
5435         uint64_t size = m_data.GetU64_unchecked(&offset);
5436 
5437         // "kern ver str" has a uint32_t version and then a nul terminated
5438         // c-string.
5439         if (strcmp("kern ver str", data_owner) == 0) {
5440           offset = fileoff;
5441           uint32_t version;
5442           if (m_data.GetU32(&offset, &version, 1) != nullptr) {
5443             if (version == 1) {
5444               uint32_t strsize = size - sizeof(uint32_t);
5445               char *buf = (char *)malloc(strsize);
5446               if (buf) {
5447                 m_data.CopyData(offset, strsize, buf);
5448                 buf[strsize - 1] = '\0';
5449                 result = buf;
5450                 if (buf)
5451                   free(buf);
5452                 return result;
5453               }
5454             }
5455           }
5456         }
5457       }
5458       offset = cmd_offset + lc.cmdsize;
5459     }
5460 
5461     // Second, make a pass over the load commands looking for an obsolete
5462     // LC_IDENT load command.
5463     offset = MachHeaderSizeFromMagic(m_header.magic);
5464     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5465       const uint32_t cmd_offset = offset;
5466       llvm::MachO::ident_command ident_command;
5467       if (m_data.GetU32(&offset, &ident_command, 2) == nullptr)
5468         break;
5469       if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
5470         char *buf = (char *)malloc(ident_command.cmdsize);
5471         if (buf != nullptr && m_data.CopyData(offset, ident_command.cmdsize,
5472                                               buf) == ident_command.cmdsize) {
5473           buf[ident_command.cmdsize - 1] = '\0';
5474           result = buf;
5475         }
5476         if (buf)
5477           free(buf);
5478       }
5479       offset = cmd_offset + ident_command.cmdsize;
5480     }
5481   }
5482   return result;
5483 }
5484 
5485 addr_t ObjectFileMachO::GetAddressMask() {
5486   addr_t mask = 0;
5487   ModuleSP module_sp(GetModule());
5488   if (module_sp) {
5489     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5490     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5491     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5492       const uint32_t cmd_offset = offset;
5493       llvm::MachO::load_command lc;
5494       if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5495         break;
5496       if (lc.cmd == LC_NOTE) {
5497         char data_owner[17];
5498         m_data.CopyData(offset, 16, data_owner);
5499         data_owner[16] = '\0';
5500         offset += 16;
5501         uint64_t fileoff = m_data.GetU64_unchecked(&offset);
5502 
5503         // "addrable bits" has a uint32_t version and a uint32_t
5504         // number of bits used in addressing.
5505         if (strcmp("addrable bits", data_owner) == 0) {
5506           offset = fileoff;
5507           uint32_t version;
5508           if (m_data.GetU32(&offset, &version, 1) != nullptr) {
5509             if (version == 3) {
5510               uint32_t num_addr_bits = m_data.GetU32_unchecked(&offset);
5511               if (num_addr_bits != 0) {
5512                 mask = ~((1ULL << num_addr_bits) - 1);
5513               }
5514               break;
5515             }
5516           }
5517         }
5518       }
5519       offset = cmd_offset + lc.cmdsize;
5520     }
5521   }
5522   return mask;
5523 }
5524 
5525 bool ObjectFileMachO::GetCorefileMainBinaryInfo(addr_t &value,
5526                                                 bool &value_is_offset,
5527                                                 UUID &uuid,
5528                                                 ObjectFile::BinaryType &type) {
5529   value = LLDB_INVALID_ADDRESS;
5530   value_is_offset = false;
5531   uuid.Clear();
5532   uint32_t log2_pagesize = 0; // not currently passed up to caller
5533   uint32_t platform = 0;      // not currently passed up to caller
5534   ModuleSP module_sp(GetModule());
5535   if (module_sp) {
5536     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5537     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5538     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5539       const uint32_t cmd_offset = offset;
5540       llvm::MachO::load_command lc;
5541       if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5542         break;
5543       if (lc.cmd == LC_NOTE) {
5544         char data_owner[17];
5545         memset(data_owner, 0, sizeof(data_owner));
5546         m_data.CopyData(offset, 16, data_owner);
5547         offset += 16;
5548         uint64_t fileoff = m_data.GetU64_unchecked(&offset);
5549         uint64_t size = m_data.GetU64_unchecked(&offset);
5550 
5551         // struct main_bin_spec
5552         // {
5553         //     uint32_t version;       // currently 2
5554         //     uint32_t type;          // 0 == unspecified, 1 == kernel,
5555         //                             // 2 == user process,
5556         //                             // 3 == standalone binary
5557         //     uint64_t address;       // UINT64_MAX if address not specified
5558         //     uint64_t slide;         // slide, UINT64_MAX if unspecified
5559         //                             // 0 if no slide needs to be applied to
5560         //                             // file address
5561         //     uuid_t   uuid;          // all zero's if uuid not specified
5562         //     uint32_t log2_pagesize; // process page size in log base 2,
5563         //                             // e.g. 4k pages are 12.
5564         //                             // 0 for unspecified
5565         //     uint32_t platform;      // The Mach-O platform for this corefile.
5566         //                             // 0 for unspecified.
5567         //                             // The values are defined in
5568         //                             // <mach-o/loader.h>, PLATFORM_*.
5569         // } __attribute((packed));
5570 
5571         // "main bin spec" (main binary specification) data payload is
5572         // formatted:
5573         //    uint32_t version       [currently 1]
5574         //    uint32_t type          [0 == unspecified, 1 == kernel,
5575         //                            2 == user process, 3 == firmware ]
5576         //    uint64_t address       [ UINT64_MAX if address not specified ]
5577         //    uuid_t   uuid          [ all zero's if uuid not specified ]
5578         //    uint32_t log2_pagesize [ process page size in log base
5579         //                             2, e.g. 4k pages are 12.
5580         //                             0 for unspecified ]
5581         //    uint32_t unused        [ for alignment ]
5582 
5583         if (strcmp("main bin spec", data_owner) == 0 && size >= 32) {
5584           offset = fileoff;
5585           uint32_t version;
5586           if (m_data.GetU32(&offset, &version, 1) != nullptr && version <= 2) {
5587             uint32_t binspec_type = 0;
5588             uuid_t raw_uuid;
5589             memset(raw_uuid, 0, sizeof(uuid_t));
5590 
5591             if (!m_data.GetU32(&offset, &binspec_type, 1))
5592               return false;
5593             if (!m_data.GetU64(&offset, &value, 1))
5594               return false;
5595             uint64_t slide = LLDB_INVALID_ADDRESS;
5596             if (version > 1 && !m_data.GetU64(&offset, &slide, 1))
5597               return false;
5598             if (value == LLDB_INVALID_ADDRESS &&
5599                 slide != LLDB_INVALID_ADDRESS) {
5600               value = slide;
5601               value_is_offset = true;
5602             }
5603 
5604             if (m_data.CopyData(offset, sizeof(uuid_t), raw_uuid) != 0) {
5605               uuid = UUID::fromOptionalData(raw_uuid, sizeof(uuid_t));
5606               // convert the "main bin spec" type into our
5607               // ObjectFile::BinaryType enum
5608               switch (binspec_type) {
5609               case 0:
5610                 type = eBinaryTypeUnknown;
5611                 break;
5612               case 1:
5613                 type = eBinaryTypeKernel;
5614                 break;
5615               case 2:
5616                 type = eBinaryTypeUser;
5617                 break;
5618               case 3:
5619                 type = eBinaryTypeStandalone;
5620                 break;
5621               }
5622               if (!m_data.GetU32(&offset, &log2_pagesize, 1))
5623                 return false;
5624               if (version > 1 && !m_data.GetU32(&offset, &platform, 1))
5625                 return false;
5626               return true;
5627             }
5628           }
5629         }
5630       }
5631       offset = cmd_offset + lc.cmdsize;
5632     }
5633   }
5634   return false;
5635 }
5636 
5637 lldb::RegisterContextSP
5638 ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
5639                                          lldb_private::Thread &thread) {
5640   lldb::RegisterContextSP reg_ctx_sp;
5641 
5642   ModuleSP module_sp(GetModule());
5643   if (module_sp) {
5644     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5645     if (!m_thread_context_offsets_valid)
5646       GetNumThreadContexts();
5647 
5648     const FileRangeArray::Entry *thread_context_file_range =
5649         m_thread_context_offsets.GetEntryAtIndex(idx);
5650     if (thread_context_file_range) {
5651 
5652       DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
5653                          thread_context_file_range->GetByteSize());
5654 
5655       switch (m_header.cputype) {
5656       case llvm::MachO::CPU_TYPE_ARM64:
5657       case llvm::MachO::CPU_TYPE_ARM64_32:
5658         reg_ctx_sp =
5659             std::make_shared<RegisterContextDarwin_arm64_Mach>(thread, data);
5660         break;
5661 
5662       case llvm::MachO::CPU_TYPE_ARM:
5663         reg_ctx_sp =
5664             std::make_shared<RegisterContextDarwin_arm_Mach>(thread, data);
5665         break;
5666 
5667       case llvm::MachO::CPU_TYPE_I386:
5668         reg_ctx_sp =
5669             std::make_shared<RegisterContextDarwin_i386_Mach>(thread, data);
5670         break;
5671 
5672       case llvm::MachO::CPU_TYPE_X86_64:
5673         reg_ctx_sp =
5674             std::make_shared<RegisterContextDarwin_x86_64_Mach>(thread, data);
5675         break;
5676       }
5677     }
5678   }
5679   return reg_ctx_sp;
5680 }
5681 
5682 ObjectFile::Type ObjectFileMachO::CalculateType() {
5683   switch (m_header.filetype) {
5684   case MH_OBJECT: // 0x1u
5685     if (GetAddressByteSize() == 4) {
5686       // 32 bit kexts are just object files, but they do have a valid
5687       // UUID load command.
5688       if (GetUUID()) {
5689         // this checking for the UUID load command is not enough we could
5690         // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5691         // this is required of kexts
5692         if (m_strata == eStrataInvalid)
5693           m_strata = eStrataKernel;
5694         return eTypeSharedLibrary;
5695       }
5696     }
5697     return eTypeObjectFile;
5698 
5699   case MH_EXECUTE:
5700     return eTypeExecutable; // 0x2u
5701   case MH_FVMLIB:
5702     return eTypeSharedLibrary; // 0x3u
5703   case MH_CORE:
5704     return eTypeCoreFile; // 0x4u
5705   case MH_PRELOAD:
5706     return eTypeSharedLibrary; // 0x5u
5707   case MH_DYLIB:
5708     return eTypeSharedLibrary; // 0x6u
5709   case MH_DYLINKER:
5710     return eTypeDynamicLinker; // 0x7u
5711   case MH_BUNDLE:
5712     return eTypeSharedLibrary; // 0x8u
5713   case MH_DYLIB_STUB:
5714     return eTypeStubLibrary; // 0x9u
5715   case MH_DSYM:
5716     return eTypeDebugInfo; // 0xAu
5717   case MH_KEXT_BUNDLE:
5718     return eTypeSharedLibrary; // 0xBu
5719   default:
5720     break;
5721   }
5722   return eTypeUnknown;
5723 }
5724 
5725 ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
5726   switch (m_header.filetype) {
5727   case MH_OBJECT: // 0x1u
5728   {
5729     // 32 bit kexts are just object files, but they do have a valid
5730     // UUID load command.
5731     if (GetUUID()) {
5732       // this checking for the UUID load command is not enough we could
5733       // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5734       // this is required of kexts
5735       if (m_type == eTypeInvalid)
5736         m_type = eTypeSharedLibrary;
5737 
5738       return eStrataKernel;
5739     }
5740   }
5741     return eStrataUnknown;
5742 
5743   case MH_EXECUTE: // 0x2u
5744     // Check for the MH_DYLDLINK bit in the flags
5745     if (m_header.flags & MH_DYLDLINK) {
5746       return eStrataUser;
5747     } else {
5748       SectionList *section_list = GetSectionList();
5749       if (section_list) {
5750         static ConstString g_kld_section_name("__KLD");
5751         if (section_list->FindSectionByName(g_kld_section_name))
5752           return eStrataKernel;
5753       }
5754     }
5755     return eStrataRawImage;
5756 
5757   case MH_FVMLIB:
5758     return eStrataUser; // 0x3u
5759   case MH_CORE:
5760     return eStrataUnknown; // 0x4u
5761   case MH_PRELOAD:
5762     return eStrataRawImage; // 0x5u
5763   case MH_DYLIB:
5764     return eStrataUser; // 0x6u
5765   case MH_DYLINKER:
5766     return eStrataUser; // 0x7u
5767   case MH_BUNDLE:
5768     return eStrataUser; // 0x8u
5769   case MH_DYLIB_STUB:
5770     return eStrataUser; // 0x9u
5771   case MH_DSYM:
5772     return eStrataUnknown; // 0xAu
5773   case MH_KEXT_BUNDLE:
5774     return eStrataKernel; // 0xBu
5775   default:
5776     break;
5777   }
5778   return eStrataUnknown;
5779 }
5780 
5781 llvm::VersionTuple ObjectFileMachO::GetVersion() {
5782   ModuleSP module_sp(GetModule());
5783   if (module_sp) {
5784     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5785     llvm::MachO::dylib_command load_cmd;
5786     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5787     uint32_t version_cmd = 0;
5788     uint64_t version = 0;
5789     uint32_t i;
5790     for (i = 0; i < m_header.ncmds; ++i) {
5791       const lldb::offset_t cmd_offset = offset;
5792       if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
5793         break;
5794 
5795       if (load_cmd.cmd == LC_ID_DYLIB) {
5796         if (version_cmd == 0) {
5797           version_cmd = load_cmd.cmd;
5798           if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == nullptr)
5799             break;
5800           version = load_cmd.dylib.current_version;
5801         }
5802         break; // Break for now unless there is another more complete version
5803                // number load command in the future.
5804       }
5805       offset = cmd_offset + load_cmd.cmdsize;
5806     }
5807 
5808     if (version_cmd == LC_ID_DYLIB) {
5809       unsigned major = (version & 0xFFFF0000ull) >> 16;
5810       unsigned minor = (version & 0x0000FF00ull) >> 8;
5811       unsigned subminor = (version & 0x000000FFull);
5812       return llvm::VersionTuple(major, minor, subminor);
5813     }
5814   }
5815   return llvm::VersionTuple();
5816 }
5817 
5818 ArchSpec ObjectFileMachO::GetArchitecture() {
5819   ModuleSP module_sp(GetModule());
5820   ArchSpec arch;
5821   if (module_sp) {
5822     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5823 
5824     return GetArchitecture(module_sp, m_header, m_data,
5825                            MachHeaderSizeFromMagic(m_header.magic));
5826   }
5827   return arch;
5828 }
5829 
5830 void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process,
5831                                                 addr_t &base_addr, UUID &uuid) {
5832   uuid.Clear();
5833   base_addr = LLDB_INVALID_ADDRESS;
5834   if (process && process->GetDynamicLoader()) {
5835     DynamicLoader *dl = process->GetDynamicLoader();
5836     LazyBool using_shared_cache;
5837     LazyBool private_shared_cache;
5838     dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache,
5839                                   private_shared_cache);
5840   }
5841   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
5842                                                   LIBLLDB_LOG_PROCESS));
5843   LLDB_LOGF(
5844       log,
5845       "inferior process shared cache has a UUID of %s, base address 0x%" PRIx64,
5846       uuid.GetAsString().c_str(), base_addr);
5847 }
5848 
5849 // From dyld SPI header dyld_process_info.h
5850 typedef void *dyld_process_info;
5851 struct lldb_copy__dyld_process_cache_info {
5852   uuid_t cacheUUID;          // UUID of cache used by process
5853   uint64_t cacheBaseAddress; // load address of dyld shared cache
5854   bool noCache;              // process is running without a dyld cache
5855   bool privateCache; // process is using a private copy of its dyld cache
5856 };
5857 
5858 // #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with
5859 // llvm enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile
5860 // errors. So we need to use the actual underlying types of task_t and
5861 // kern_return_t below.
5862 extern "C" unsigned int /*task_t*/ mach_task_self();
5863 
5864 void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
5865   uuid.Clear();
5866   base_addr = LLDB_INVALID_ADDRESS;
5867 
5868 #if defined(__APPLE__)
5869   uint8_t *(*dyld_get_all_image_infos)(void);
5870   dyld_get_all_image_infos =
5871       (uint8_t * (*)()) dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5872   if (dyld_get_all_image_infos) {
5873     uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5874     if (dyld_all_image_infos_address) {
5875       uint32_t *version = (uint32_t *)
5876           dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5877       if (*version >= 13) {
5878         uuid_t *sharedCacheUUID_address = 0;
5879         int wordsize = sizeof(uint8_t *);
5880         if (wordsize == 8) {
5881           sharedCacheUUID_address =
5882               (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5883                          160); // sharedCacheUUID <mach-o/dyld_images.h>
5884           if (*version >= 15)
5885             base_addr =
5886                 *(uint64_t
5887                       *)((uint8_t *)dyld_all_image_infos_address +
5888                          176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5889         } else {
5890           sharedCacheUUID_address =
5891               (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5892                          84); // sharedCacheUUID <mach-o/dyld_images.h>
5893           if (*version >= 15) {
5894             base_addr = 0;
5895             base_addr =
5896                 *(uint32_t
5897                       *)((uint8_t *)dyld_all_image_infos_address +
5898                          100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5899           }
5900         }
5901         uuid = UUID::fromOptionalData(sharedCacheUUID_address, sizeof(uuid_t));
5902       }
5903     }
5904   } else {
5905     // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
5906     dyld_process_info (*dyld_process_info_create)(
5907         unsigned int /* task_t */ task, uint64_t timestamp,
5908         unsigned int /*kern_return_t*/ *kernelError);
5909     void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
5910     void (*dyld_process_info_release)(dyld_process_info info);
5911 
5912     dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t,
5913                                           unsigned int /*kern_return_t*/ *))
5914         dlsym(RTLD_DEFAULT, "_dyld_process_info_create");
5915     dyld_process_info_get_cache = (void (*)(void *, void *))dlsym(
5916         RTLD_DEFAULT, "_dyld_process_info_get_cache");
5917     dyld_process_info_release =
5918         (void (*)(void *))dlsym(RTLD_DEFAULT, "_dyld_process_info_release");
5919 
5920     if (dyld_process_info_create && dyld_process_info_get_cache) {
5921       unsigned int /*kern_return_t */ kern_ret;
5922       dyld_process_info process_info =
5923           dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
5924       if (process_info) {
5925         struct lldb_copy__dyld_process_cache_info sc_info;
5926         memset(&sc_info, 0, sizeof(struct lldb_copy__dyld_process_cache_info));
5927         dyld_process_info_get_cache(process_info, &sc_info);
5928         if (sc_info.cacheBaseAddress != 0) {
5929           base_addr = sc_info.cacheBaseAddress;
5930           uuid = UUID::fromOptionalData(sc_info.cacheUUID, sizeof(uuid_t));
5931         }
5932         dyld_process_info_release(process_info);
5933       }
5934     }
5935   }
5936   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
5937                                                   LIBLLDB_LOG_PROCESS));
5938   if (log && uuid.IsValid())
5939     LLDB_LOGF(log,
5940               "lldb's in-memory shared cache has a UUID of %s base address of "
5941               "0x%" PRIx64,
5942               uuid.GetAsString().c_str(), base_addr);
5943 #endif
5944 }
5945 
5946 llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() {
5947   if (!m_min_os_version) {
5948     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5949     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5950       const lldb::offset_t load_cmd_offset = offset;
5951 
5952       llvm::MachO::version_min_command lc;
5953       if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5954         break;
5955       if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5956           lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5957           lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5958           lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5959         if (m_data.GetU32(&offset, &lc.version,
5960                           (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5961           const uint32_t xxxx = lc.version >> 16;
5962           const uint32_t yy = (lc.version >> 8) & 0xffu;
5963           const uint32_t zz = lc.version & 0xffu;
5964           if (xxxx) {
5965             m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5966             break;
5967           }
5968         }
5969       } else if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5970         // struct build_version_command {
5971         //     uint32_t    cmd;            /* LC_BUILD_VERSION */
5972         //     uint32_t    cmdsize;        /* sizeof(struct
5973         //     build_version_command) plus */
5974         //                                 /* ntools * sizeof(struct
5975         //                                 build_tool_version) */
5976         //     uint32_t    platform;       /* platform */
5977         //     uint32_t    minos;          /* X.Y.Z is encoded in nibbles
5978         //     xxxx.yy.zz */ uint32_t    sdk;            /* X.Y.Z is encoded in
5979         //     nibbles xxxx.yy.zz */ uint32_t    ntools;         /* number of
5980         //     tool entries following this */
5981         // };
5982 
5983         offset += 4; // skip platform
5984         uint32_t minos = m_data.GetU32(&offset);
5985 
5986         const uint32_t xxxx = minos >> 16;
5987         const uint32_t yy = (minos >> 8) & 0xffu;
5988         const uint32_t zz = minos & 0xffu;
5989         if (xxxx) {
5990           m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5991           break;
5992         }
5993       }
5994 
5995       offset = load_cmd_offset + lc.cmdsize;
5996     }
5997 
5998     if (!m_min_os_version) {
5999       // Set version to an empty value so we don't keep trying to
6000       m_min_os_version = llvm::VersionTuple();
6001     }
6002   }
6003 
6004   return *m_min_os_version;
6005 }
6006 
6007 llvm::VersionTuple ObjectFileMachO::GetSDKVersion() {
6008   if (!m_sdk_versions.hasValue()) {
6009     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
6010     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
6011       const lldb::offset_t load_cmd_offset = offset;
6012 
6013       llvm::MachO::version_min_command lc;
6014       if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
6015         break;
6016       if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
6017           lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
6018           lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
6019           lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
6020         if (m_data.GetU32(&offset, &lc.version,
6021                           (sizeof(lc) / sizeof(uint32_t)) - 2)) {
6022           const uint32_t xxxx = lc.sdk >> 16;
6023           const uint32_t yy = (lc.sdk >> 8) & 0xffu;
6024           const uint32_t zz = lc.sdk & 0xffu;
6025           if (xxxx) {
6026             m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz);
6027             break;
6028           } else {
6029             GetModule()->ReportWarning("minimum OS version load command with "
6030                                        "invalid (0) version found.");
6031           }
6032         }
6033       }
6034       offset = load_cmd_offset + lc.cmdsize;
6035     }
6036 
6037     if (!m_sdk_versions.hasValue()) {
6038       offset = MachHeaderSizeFromMagic(m_header.magic);
6039       for (uint32_t i = 0; i < m_header.ncmds; ++i) {
6040         const lldb::offset_t load_cmd_offset = offset;
6041 
6042         llvm::MachO::version_min_command lc;
6043         if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
6044           break;
6045         if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
6046           // struct build_version_command {
6047           //     uint32_t    cmd;            /* LC_BUILD_VERSION */
6048           //     uint32_t    cmdsize;        /* sizeof(struct
6049           //     build_version_command) plus */
6050           //                                 /* ntools * sizeof(struct
6051           //                                 build_tool_version) */
6052           //     uint32_t    platform;       /* platform */
6053           //     uint32_t    minos;          /* X.Y.Z is encoded in nibbles
6054           //     xxxx.yy.zz */ uint32_t    sdk;            /* X.Y.Z is encoded
6055           //     in nibbles xxxx.yy.zz */ uint32_t    ntools;         /* number
6056           //     of tool entries following this */
6057           // };
6058 
6059           offset += 4; // skip platform
6060           uint32_t minos = m_data.GetU32(&offset);
6061 
6062           const uint32_t xxxx = minos >> 16;
6063           const uint32_t yy = (minos >> 8) & 0xffu;
6064           const uint32_t zz = minos & 0xffu;
6065           if (xxxx) {
6066             m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz);
6067             break;
6068           }
6069         }
6070         offset = load_cmd_offset + lc.cmdsize;
6071       }
6072     }
6073 
6074     if (!m_sdk_versions.hasValue())
6075       m_sdk_versions = llvm::VersionTuple();
6076   }
6077 
6078   return m_sdk_versions.getValue();
6079 }
6080 
6081 bool ObjectFileMachO::GetIsDynamicLinkEditor() {
6082   return m_header.filetype == llvm::MachO::MH_DYLINKER;
6083 }
6084 
6085 bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
6086   return m_allow_assembly_emulation_unwind_plans;
6087 }
6088 
6089 Section *ObjectFileMachO::GetMachHeaderSection() {
6090   // Find the first address of the mach header which is the first non-zero file
6091   // sized section whose file offset is zero. This is the base file address of
6092   // the mach-o file which can be subtracted from the vmaddr of the other
6093   // segments found in memory and added to the load address
6094   ModuleSP module_sp = GetModule();
6095   if (!module_sp)
6096     return nullptr;
6097   SectionList *section_list = GetSectionList();
6098   if (!section_list)
6099     return nullptr;
6100   const size_t num_sections = section_list->GetSize();
6101   for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6102     Section *section = section_list->GetSectionAtIndex(sect_idx).get();
6103     if (section->GetFileOffset() == 0 && SectionIsLoadable(section))
6104       return section;
6105   }
6106   return nullptr;
6107 }
6108 
6109 bool ObjectFileMachO::SectionIsLoadable(const Section *section) {
6110   if (!section)
6111     return false;
6112   const bool is_dsym = (m_header.filetype == MH_DSYM);
6113   if (section->GetFileSize() == 0 && !is_dsym)
6114     return false;
6115   if (section->IsThreadSpecific())
6116     return false;
6117   if (GetModule().get() != section->GetModule().get())
6118     return false;
6119   // Be careful with __LINKEDIT and __DWARF segments
6120   if (section->GetName() == GetSegmentNameLINKEDIT() ||
6121       section->GetName() == GetSegmentNameDWARF()) {
6122     // Only map __LINKEDIT and __DWARF if we have an in memory image and
6123     // this isn't a kernel binary like a kext or mach_kernel.
6124     const bool is_memory_image = (bool)m_process_wp.lock();
6125     const Strata strata = GetStrata();
6126     if (is_memory_image == false || strata == eStrataKernel)
6127       return false;
6128   }
6129   return true;
6130 }
6131 
6132 lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
6133     lldb::addr_t header_load_address, const Section *header_section,
6134     const Section *section) {
6135   ModuleSP module_sp = GetModule();
6136   if (module_sp && header_section && section &&
6137       header_load_address != LLDB_INVALID_ADDRESS) {
6138     lldb::addr_t file_addr = header_section->GetFileAddress();
6139     if (file_addr != LLDB_INVALID_ADDRESS && SectionIsLoadable(section))
6140       return section->GetFileAddress() - file_addr + header_load_address;
6141   }
6142   return LLDB_INVALID_ADDRESS;
6143 }
6144 
6145 bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
6146                                      bool value_is_offset) {
6147   ModuleSP module_sp = GetModule();
6148   if (!module_sp)
6149     return false;
6150 
6151   SectionList *section_list = GetSectionList();
6152   if (!section_list)
6153     return false;
6154 
6155   size_t num_loaded_sections = 0;
6156   const size_t num_sections = section_list->GetSize();
6157 
6158   if (value_is_offset) {
6159     // "value" is an offset to apply to each top level segment
6160     for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6161       // Iterate through the object file sections to find all of the
6162       // sections that size on disk (to avoid __PAGEZERO) and load them
6163       SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
6164       if (SectionIsLoadable(section_sp.get()))
6165         if (target.GetSectionLoadList().SetSectionLoadAddress(
6166                 section_sp, section_sp->GetFileAddress() + value))
6167           ++num_loaded_sections;
6168     }
6169   } else {
6170     // "value" is the new base address of the mach_header, adjust each
6171     // section accordingly
6172 
6173     Section *mach_header_section = GetMachHeaderSection();
6174     if (mach_header_section) {
6175       for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6176         SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
6177 
6178         lldb::addr_t section_load_addr =
6179             CalculateSectionLoadAddressForMemoryImage(
6180                 value, mach_header_section, section_sp.get());
6181         if (section_load_addr != LLDB_INVALID_ADDRESS) {
6182           if (target.GetSectionLoadList().SetSectionLoadAddress(
6183                   section_sp, section_load_addr))
6184             ++num_loaded_sections;
6185         }
6186       }
6187     }
6188   }
6189   return num_loaded_sections > 0;
6190 }
6191 
6192 struct all_image_infos_header {
6193   uint32_t version;         // currently 1
6194   uint32_t imgcount;        // number of binary images
6195   uint64_t entries_fileoff; // file offset in the corefile of where the array of
6196                             // struct entry's begin.
6197   uint32_t entries_size;    // size of 'struct entry'.
6198   uint32_t unused;
6199 };
6200 
6201 struct image_entry {
6202   uint64_t filepath_offset;  // offset in corefile to c-string of the file path,
6203                              // UINT64_MAX if unavailable.
6204   uuid_t uuid;               // uint8_t[16].  should be set to all zeroes if
6205                              // uuid is unknown.
6206   uint64_t load_address;     // UINT64_MAX if unknown.
6207   uint64_t seg_addrs_offset; // offset to the array of struct segment_vmaddr's.
6208   uint32_t segment_count;    // The number of segments for this binary.
6209   uint32_t unused;
6210 
6211   image_entry() {
6212     filepath_offset = UINT64_MAX;
6213     memset(&uuid, 0, sizeof(uuid_t));
6214     segment_count = 0;
6215     load_address = UINT64_MAX;
6216     seg_addrs_offset = UINT64_MAX;
6217     unused = 0;
6218   }
6219   image_entry(const image_entry &rhs) {
6220     filepath_offset = rhs.filepath_offset;
6221     memcpy(&uuid, &rhs.uuid, sizeof(uuid_t));
6222     segment_count = rhs.segment_count;
6223     seg_addrs_offset = rhs.seg_addrs_offset;
6224     load_address = rhs.load_address;
6225     unused = rhs.unused;
6226   }
6227 };
6228 
6229 struct segment_vmaddr {
6230   char segname[16];
6231   uint64_t vmaddr;
6232   uint64_t unused;
6233 
6234   segment_vmaddr() {
6235     memset(&segname, 0, 16);
6236     vmaddr = UINT64_MAX;
6237     unused = 0;
6238   }
6239   segment_vmaddr(const segment_vmaddr &rhs) {
6240     memcpy(&segname, &rhs.segname, 16);
6241     vmaddr = rhs.vmaddr;
6242     unused = rhs.unused;
6243   }
6244 };
6245 
6246 // Write the payload for the "all image infos" LC_NOTE into
6247 // the supplied all_image_infos_payload, assuming that this
6248 // will be written into the corefile starting at
6249 // initial_file_offset.
6250 //
6251 // The placement of this payload is a little tricky.  We're
6252 // laying this out as
6253 //
6254 // 1. header (struct all_image_info_header)
6255 // 2. Array of fixed-size (struct image_entry)'s, one
6256 //    per binary image present in the process.
6257 // 3. Arrays of (struct segment_vmaddr)'s, a varying number
6258 //    for each binary image.
6259 // 4. Variable length c-strings of binary image filepaths,
6260 //    one per binary.
6261 //
6262 // To compute where everything will be laid out in the
6263 // payload, we need to iterate over the images and calculate
6264 // how many segment_vmaddr structures each image will need,
6265 // and how long each image's filepath c-string is. There
6266 // are some multiple passes over the image list while calculating
6267 // everything.
6268 
6269 static offset_t CreateAllImageInfosPayload(
6270     const lldb::ProcessSP &process_sp, offset_t initial_file_offset,
6271     StreamString &all_image_infos_payload, SaveCoreStyle core_style) {
6272   Target &target = process_sp->GetTarget();
6273   ModuleList modules = target.GetImages();
6274 
6275   // stack-only corefiles have no reason to include binaries that
6276   // are not executing; we're trying to make the smallest corefile
6277   // we can, so leave the rest out.
6278   if (core_style == SaveCoreStyle::eSaveCoreStackOnly)
6279     modules.Clear();
6280 
6281   std::set<std::string> executing_uuids;
6282   ThreadList &thread_list(process_sp->GetThreadList());
6283   for (uint32_t i = 0; i < thread_list.GetSize(); i++) {
6284     ThreadSP thread_sp = thread_list.GetThreadAtIndex(i);
6285     uint32_t stack_frame_count = thread_sp->GetStackFrameCount();
6286     for (uint32_t j = 0; j < stack_frame_count; j++) {
6287       StackFrameSP stack_frame_sp = thread_sp->GetStackFrameAtIndex(j);
6288       Address pc = stack_frame_sp->GetFrameCodeAddress();
6289       ModuleSP module_sp = pc.GetModule();
6290       if (module_sp) {
6291         UUID uuid = module_sp->GetUUID();
6292         if (uuid.IsValid()) {
6293           executing_uuids.insert(uuid.GetAsString());
6294           modules.AppendIfNeeded(module_sp);
6295         }
6296       }
6297     }
6298   }
6299   size_t modules_count = modules.GetSize();
6300 
6301   struct all_image_infos_header infos;
6302   infos.version = 1;
6303   infos.imgcount = modules_count;
6304   infos.entries_size = sizeof(image_entry);
6305   infos.entries_fileoff = initial_file_offset + sizeof(all_image_infos_header);
6306   infos.unused = 0;
6307 
6308   all_image_infos_payload.PutHex32(infos.version);
6309   all_image_infos_payload.PutHex32(infos.imgcount);
6310   all_image_infos_payload.PutHex64(infos.entries_fileoff);
6311   all_image_infos_payload.PutHex32(infos.entries_size);
6312   all_image_infos_payload.PutHex32(infos.unused);
6313 
6314   // First create the structures for all of the segment name+vmaddr vectors
6315   // for each module, so we will know the size of them as we add the
6316   // module entries.
6317   std::vector<std::vector<segment_vmaddr>> modules_segment_vmaddrs;
6318   for (size_t i = 0; i < modules_count; i++) {
6319     ModuleSP module = modules.GetModuleAtIndex(i);
6320 
6321     SectionList *sections = module->GetSectionList();
6322     size_t sections_count = sections->GetSize();
6323     std::vector<segment_vmaddr> segment_vmaddrs;
6324     for (size_t j = 0; j < sections_count; j++) {
6325       SectionSP section = sections->GetSectionAtIndex(j);
6326       if (!section->GetParent().get()) {
6327         addr_t vmaddr = section->GetLoadBaseAddress(&target);
6328         if (vmaddr == LLDB_INVALID_ADDRESS)
6329           continue;
6330         ConstString name = section->GetName();
6331         segment_vmaddr seg_vmaddr;
6332         strncpy(seg_vmaddr.segname, name.AsCString(),
6333                 sizeof(seg_vmaddr.segname));
6334         seg_vmaddr.vmaddr = vmaddr;
6335         seg_vmaddr.unused = 0;
6336         segment_vmaddrs.push_back(seg_vmaddr);
6337       }
6338     }
6339     modules_segment_vmaddrs.push_back(segment_vmaddrs);
6340   }
6341 
6342   offset_t size_of_vmaddr_structs = 0;
6343   for (size_t i = 0; i < modules_segment_vmaddrs.size(); i++) {
6344     size_of_vmaddr_structs +=
6345         modules_segment_vmaddrs[i].size() * sizeof(segment_vmaddr);
6346   }
6347 
6348   offset_t size_of_filepath_cstrings = 0;
6349   for (size_t i = 0; i < modules_count; i++) {
6350     ModuleSP module_sp = modules.GetModuleAtIndex(i);
6351     size_of_filepath_cstrings += module_sp->GetFileSpec().GetPath().size() + 1;
6352   }
6353 
6354   // Calculate the file offsets of our "all image infos" payload in the
6355   // corefile. initial_file_offset the original value passed in to this method.
6356 
6357   offset_t start_of_entries =
6358       initial_file_offset + sizeof(all_image_infos_header);
6359   offset_t start_of_seg_vmaddrs =
6360       start_of_entries + sizeof(image_entry) * modules_count;
6361   offset_t start_of_filenames = start_of_seg_vmaddrs + size_of_vmaddr_structs;
6362 
6363   offset_t final_file_offset = start_of_filenames + size_of_filepath_cstrings;
6364 
6365   // Now write the one-per-module 'struct image_entry' into the
6366   // StringStream; keep track of where the struct segment_vmaddr
6367   // entries for each module will end up in the corefile.
6368 
6369   offset_t current_string_offset = start_of_filenames;
6370   offset_t current_segaddrs_offset = start_of_seg_vmaddrs;
6371   std::vector<struct image_entry> image_entries;
6372   for (size_t i = 0; i < modules_count; i++) {
6373     ModuleSP module_sp = modules.GetModuleAtIndex(i);
6374 
6375     struct image_entry ent;
6376     memcpy(&ent.uuid, module_sp->GetUUID().GetBytes().data(), sizeof(ent.uuid));
6377     if (modules_segment_vmaddrs[i].size() > 0) {
6378       ent.segment_count = modules_segment_vmaddrs[i].size();
6379       ent.seg_addrs_offset = current_segaddrs_offset;
6380     }
6381     ent.filepath_offset = current_string_offset;
6382     ObjectFile *objfile = module_sp->GetObjectFile();
6383     if (objfile) {
6384       Address base_addr(objfile->GetBaseAddress());
6385       if (base_addr.IsValid()) {
6386         ent.load_address = base_addr.GetLoadAddress(&target);
6387       }
6388     }
6389 
6390     all_image_infos_payload.PutHex64(ent.filepath_offset);
6391     all_image_infos_payload.PutRawBytes(ent.uuid, sizeof(ent.uuid));
6392     all_image_infos_payload.PutHex64(ent.load_address);
6393     all_image_infos_payload.PutHex64(ent.seg_addrs_offset);
6394     all_image_infos_payload.PutHex32(ent.segment_count);
6395 
6396     if (executing_uuids.find(module_sp->GetUUID().GetAsString()) !=
6397         executing_uuids.end())
6398       all_image_infos_payload.PutHex32(1);
6399     else
6400       all_image_infos_payload.PutHex32(0);
6401 
6402     current_segaddrs_offset += ent.segment_count * sizeof(segment_vmaddr);
6403     current_string_offset += module_sp->GetFileSpec().GetPath().size() + 1;
6404   }
6405 
6406   // Now write the struct segment_vmaddr entries into the StringStream.
6407 
6408   for (size_t i = 0; i < modules_segment_vmaddrs.size(); i++) {
6409     if (modules_segment_vmaddrs[i].size() == 0)
6410       continue;
6411     for (struct segment_vmaddr segvm : modules_segment_vmaddrs[i]) {
6412       all_image_infos_payload.PutRawBytes(segvm.segname, sizeof(segvm.segname));
6413       all_image_infos_payload.PutHex64(segvm.vmaddr);
6414       all_image_infos_payload.PutHex64(segvm.unused);
6415     }
6416   }
6417 
6418   for (size_t i = 0; i < modules_count; i++) {
6419     ModuleSP module_sp = modules.GetModuleAtIndex(i);
6420     std::string filepath = module_sp->GetFileSpec().GetPath();
6421     all_image_infos_payload.PutRawBytes(filepath.data(), filepath.size() + 1);
6422   }
6423 
6424   return final_file_offset;
6425 }
6426 
6427 // Temp struct used to combine contiguous memory regions with
6428 // identical permissions.
6429 struct page_object {
6430   addr_t addr;
6431   addr_t size;
6432   uint32_t prot;
6433 };
6434 
6435 bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
6436                                const FileSpec &outfile,
6437                                lldb::SaveCoreStyle &core_style, Status &error) {
6438   if (!process_sp)
6439     return false;
6440 
6441   // Default on macOS is to create a dirty-memory-only corefile.
6442   if (core_style == SaveCoreStyle::eSaveCoreUnspecified) {
6443     core_style = SaveCoreStyle::eSaveCoreDirtyOnly;
6444   }
6445 
6446   Target &target = process_sp->GetTarget();
6447   const ArchSpec target_arch = target.GetArchitecture();
6448   const llvm::Triple &target_triple = target_arch.GetTriple();
6449   if (target_triple.getVendor() == llvm::Triple::Apple &&
6450       (target_triple.getOS() == llvm::Triple::MacOSX ||
6451        target_triple.getOS() == llvm::Triple::IOS ||
6452        target_triple.getOS() == llvm::Triple::WatchOS ||
6453        target_triple.getOS() == llvm::Triple::TvOS)) {
6454     // NEED_BRIDGEOS_TRIPLE target_triple.getOS() == llvm::Triple::BridgeOS))
6455     // {
6456     bool make_core = false;
6457     switch (target_arch.GetMachine()) {
6458     case llvm::Triple::aarch64:
6459     case llvm::Triple::aarch64_32:
6460     case llvm::Triple::arm:
6461     case llvm::Triple::thumb:
6462     case llvm::Triple::x86:
6463     case llvm::Triple::x86_64:
6464       make_core = true;
6465       break;
6466     default:
6467       error.SetErrorStringWithFormat("unsupported core architecture: %s",
6468                                      target_triple.str().c_str());
6469       break;
6470     }
6471 
6472     if (make_core) {
6473       std::vector<llvm::MachO::segment_command_64> segment_load_commands;
6474       //                uint32_t range_info_idx = 0;
6475       MemoryRegionInfo range_info;
6476       Status range_error = process_sp->GetMemoryRegionInfo(0, range_info);
6477       const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
6478       const ByteOrder byte_order = target_arch.GetByteOrder();
6479       std::vector<page_object> pages_to_copy;
6480 
6481       if (range_error.Success()) {
6482         while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
6483           // Calculate correct protections
6484           uint32_t prot = 0;
6485           if (range_info.GetReadable() == MemoryRegionInfo::eYes)
6486             prot |= VM_PROT_READ;
6487           if (range_info.GetWritable() == MemoryRegionInfo::eYes)
6488             prot |= VM_PROT_WRITE;
6489           if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
6490             prot |= VM_PROT_EXECUTE;
6491 
6492           const addr_t addr = range_info.GetRange().GetRangeBase();
6493           const addr_t size = range_info.GetRange().GetByteSize();
6494 
6495           if (size == 0)
6496             break;
6497 
6498           bool include_this_region = true;
6499           bool dirty_pages_only = false;
6500           if (core_style == SaveCoreStyle::eSaveCoreStackOnly) {
6501             dirty_pages_only = true;
6502             if (range_info.IsStackMemory() != MemoryRegionInfo::eYes) {
6503               include_this_region = false;
6504             }
6505           }
6506           if (core_style == SaveCoreStyle::eSaveCoreDirtyOnly) {
6507             dirty_pages_only = true;
6508           }
6509 
6510           if (prot != 0 && include_this_region) {
6511             addr_t pagesize = range_info.GetPageSize();
6512             const llvm::Optional<std::vector<addr_t>> &dirty_page_list =
6513                 range_info.GetDirtyPageList();
6514             if (dirty_pages_only && dirty_page_list.hasValue()) {
6515               for (addr_t dirtypage : dirty_page_list.getValue()) {
6516                 page_object obj;
6517                 obj.addr = dirtypage;
6518                 obj.size = pagesize;
6519                 obj.prot = prot;
6520                 pages_to_copy.push_back(obj);
6521               }
6522             } else {
6523               page_object obj;
6524               obj.addr = addr;
6525               obj.size = size;
6526               obj.prot = prot;
6527               pages_to_copy.push_back(obj);
6528             }
6529           }
6530 
6531           range_error = process_sp->GetMemoryRegionInfo(
6532               range_info.GetRange().GetRangeEnd(), range_info);
6533           if (range_error.Fail())
6534             break;
6535         }
6536 
6537         // Combine contiguous entries that have the same
6538         // protections so we don't have an excess of
6539         // load commands.
6540         std::vector<page_object> combined_page_objects;
6541         page_object last_obj;
6542         last_obj.addr = LLDB_INVALID_ADDRESS;
6543         last_obj.size = 0;
6544         for (page_object obj : pages_to_copy) {
6545           if (last_obj.addr == LLDB_INVALID_ADDRESS) {
6546             last_obj = obj;
6547             continue;
6548           }
6549           if (last_obj.addr + last_obj.size == obj.addr &&
6550               last_obj.prot == obj.prot) {
6551             last_obj.size += obj.size;
6552             continue;
6553           }
6554           combined_page_objects.push_back(last_obj);
6555           last_obj = obj;
6556         }
6557         // Add the last entry we were looking to combine
6558         // on to the array.
6559         if (last_obj.addr != LLDB_INVALID_ADDRESS && last_obj.size != 0)
6560           combined_page_objects.push_back(last_obj);
6561 
6562         for (page_object obj : combined_page_objects) {
6563           uint32_t cmd_type = LC_SEGMENT_64;
6564           uint32_t segment_size = sizeof(llvm::MachO::segment_command_64);
6565           if (addr_byte_size == 4) {
6566             cmd_type = LC_SEGMENT;
6567             segment_size = sizeof(llvm::MachO::segment_command);
6568           }
6569           llvm::MachO::segment_command_64 segment = {
6570               cmd_type,     // uint32_t cmd;
6571               segment_size, // uint32_t cmdsize;
6572               {0},          // char segname[16];
6573               obj.addr,     // uint64_t vmaddr;    // uint32_t for 32-bit
6574                             // Mach-O
6575               obj.size,     // uint64_t vmsize;    // uint32_t for 32-bit
6576                             // Mach-O
6577               0,            // uint64_t fileoff;   // uint32_t for 32-bit Mach-O
6578               obj.size,     // uint64_t filesize;  // uint32_t for 32-bit
6579                             // Mach-O
6580               obj.prot,     // uint32_t maxprot;
6581               obj.prot,     // uint32_t initprot;
6582               0,            // uint32_t nsects;
6583               0};           // uint32_t flags;
6584           segment_load_commands.push_back(segment);
6585         }
6586 
6587         StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
6588 
6589         llvm::MachO::mach_header_64 mach_header;
6590         if (addr_byte_size == 8) {
6591           mach_header.magic = MH_MAGIC_64;
6592         } else {
6593           mach_header.magic = MH_MAGIC;
6594         }
6595         mach_header.cputype = target_arch.GetMachOCPUType();
6596         mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
6597         mach_header.filetype = MH_CORE;
6598         mach_header.ncmds = segment_load_commands.size();
6599         mach_header.flags = 0;
6600         mach_header.reserved = 0;
6601         ThreadList &thread_list = process_sp->GetThreadList();
6602         const uint32_t num_threads = thread_list.GetSize();
6603 
6604         // Make an array of LC_THREAD data items. Each one contains the
6605         // contents of the LC_THREAD load command. The data doesn't contain
6606         // the load command + load command size, we will add the load command
6607         // and load command size as we emit the data.
6608         std::vector<StreamString> LC_THREAD_datas(num_threads);
6609         for (auto &LC_THREAD_data : LC_THREAD_datas) {
6610           LC_THREAD_data.GetFlags().Set(Stream::eBinary);
6611           LC_THREAD_data.SetAddressByteSize(addr_byte_size);
6612           LC_THREAD_data.SetByteOrder(byte_order);
6613         }
6614         for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
6615           ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
6616           if (thread_sp) {
6617             switch (mach_header.cputype) {
6618             case llvm::MachO::CPU_TYPE_ARM64:
6619             case llvm::MachO::CPU_TYPE_ARM64_32:
6620               RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
6621                   thread_sp.get(), LC_THREAD_datas[thread_idx]);
6622               break;
6623 
6624             case llvm::MachO::CPU_TYPE_ARM:
6625               RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
6626                   thread_sp.get(), LC_THREAD_datas[thread_idx]);
6627               break;
6628 
6629             case llvm::MachO::CPU_TYPE_I386:
6630               RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
6631                   thread_sp.get(), LC_THREAD_datas[thread_idx]);
6632               break;
6633 
6634             case llvm::MachO::CPU_TYPE_X86_64:
6635               RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
6636                   thread_sp.get(), LC_THREAD_datas[thread_idx]);
6637               break;
6638             }
6639           }
6640         }
6641 
6642         // The size of the load command is the size of the segments...
6643         if (addr_byte_size == 8) {
6644           mach_header.sizeofcmds = segment_load_commands.size() *
6645                                    sizeof(llvm::MachO::segment_command_64);
6646         } else {
6647           mach_header.sizeofcmds = segment_load_commands.size() *
6648                                    sizeof(llvm::MachO::segment_command);
6649         }
6650 
6651         // and the size of all LC_THREAD load command
6652         for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6653           ++mach_header.ncmds;
6654           mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
6655         }
6656 
6657         // Bits will be set to indicate which bits are NOT used in
6658         // addressing in this process or 0 for unknown.
6659         uint64_t address_mask = process_sp->GetCodeAddressMask();
6660         if (address_mask != 0) {
6661           // LC_NOTE "addrable bits"
6662           mach_header.ncmds++;
6663           mach_header.sizeofcmds += sizeof(llvm::MachO::note_command);
6664         }
6665 
6666         // LC_NOTE "all image infos"
6667         mach_header.ncmds++;
6668         mach_header.sizeofcmds += sizeof(llvm::MachO::note_command);
6669 
6670         // Write the mach header
6671         buffer.PutHex32(mach_header.magic);
6672         buffer.PutHex32(mach_header.cputype);
6673         buffer.PutHex32(mach_header.cpusubtype);
6674         buffer.PutHex32(mach_header.filetype);
6675         buffer.PutHex32(mach_header.ncmds);
6676         buffer.PutHex32(mach_header.sizeofcmds);
6677         buffer.PutHex32(mach_header.flags);
6678         if (addr_byte_size == 8) {
6679           buffer.PutHex32(mach_header.reserved);
6680         }
6681 
6682         // Skip the mach header and all load commands and align to the next
6683         // 0x1000 byte boundary
6684         addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
6685 
6686         file_offset = llvm::alignTo(file_offset, 16);
6687         std::vector<std::unique_ptr<LCNoteEntry>> lc_notes;
6688 
6689         // Add "addrable bits" LC_NOTE when an address mask is available
6690         if (address_mask != 0) {
6691           std::unique_ptr<LCNoteEntry> addrable_bits_lcnote_up(
6692               new LCNoteEntry(addr_byte_size, byte_order));
6693           addrable_bits_lcnote_up->name = "addrable bits";
6694           addrable_bits_lcnote_up->payload_file_offset = file_offset;
6695           int bits = std::bitset<64>(~address_mask).count();
6696           addrable_bits_lcnote_up->payload.PutHex32(3); // version
6697           addrable_bits_lcnote_up->payload.PutHex32(
6698               bits); // # of bits used for addressing
6699           addrable_bits_lcnote_up->payload.PutHex64(0); // unused
6700 
6701           file_offset += addrable_bits_lcnote_up->payload.GetSize();
6702 
6703           lc_notes.push_back(std::move(addrable_bits_lcnote_up));
6704         }
6705 
6706         // Add "all image infos" LC_NOTE
6707         std::unique_ptr<LCNoteEntry> all_image_infos_lcnote_up(
6708             new LCNoteEntry(addr_byte_size, byte_order));
6709         all_image_infos_lcnote_up->name = "all image infos";
6710         all_image_infos_lcnote_up->payload_file_offset = file_offset;
6711         file_offset = CreateAllImageInfosPayload(
6712             process_sp, file_offset, all_image_infos_lcnote_up->payload,
6713             core_style);
6714         lc_notes.push_back(std::move(all_image_infos_lcnote_up));
6715 
6716         // Add LC_NOTE load commands
6717         for (auto &lcnote : lc_notes) {
6718           // Add the LC_NOTE load command to the file.
6719           buffer.PutHex32(LC_NOTE);
6720           buffer.PutHex32(sizeof(llvm::MachO::note_command));
6721           char namebuf[16];
6722           memset(namebuf, 0, sizeof(namebuf));
6723           // this is the uncommon case where strncpy is exactly
6724           // the right one, doesn't need to be nul terminated.
6725           strncpy(namebuf, lcnote->name.c_str(), sizeof(namebuf));
6726           buffer.PutRawBytes(namebuf, sizeof(namebuf));
6727           buffer.PutHex64(lcnote->payload_file_offset);
6728           buffer.PutHex64(lcnote->payload.GetSize());
6729         }
6730 
6731         // Align to 4096-byte page boundary for the LC_SEGMENTs.
6732         file_offset = llvm::alignTo(file_offset, 4096);
6733 
6734         for (auto &segment : segment_load_commands) {
6735           segment.fileoff = file_offset;
6736           file_offset += segment.filesize;
6737         }
6738 
6739         // Write out all of the LC_THREAD load commands
6740         for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6741           const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6742           buffer.PutHex32(LC_THREAD);
6743           buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
6744           buffer.Write(LC_THREAD_data.GetString().data(), LC_THREAD_data_size);
6745         }
6746 
6747         // Write out all of the segment load commands
6748         for (const auto &segment : segment_load_commands) {
6749           buffer.PutHex32(segment.cmd);
6750           buffer.PutHex32(segment.cmdsize);
6751           buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
6752           if (addr_byte_size == 8) {
6753             buffer.PutHex64(segment.vmaddr);
6754             buffer.PutHex64(segment.vmsize);
6755             buffer.PutHex64(segment.fileoff);
6756             buffer.PutHex64(segment.filesize);
6757           } else {
6758             buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
6759             buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
6760             buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
6761             buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
6762           }
6763           buffer.PutHex32(segment.maxprot);
6764           buffer.PutHex32(segment.initprot);
6765           buffer.PutHex32(segment.nsects);
6766           buffer.PutHex32(segment.flags);
6767         }
6768 
6769         std::string core_file_path(outfile.GetPath());
6770         auto core_file = FileSystem::Instance().Open(
6771             outfile, File::eOpenOptionWriteOnly | File::eOpenOptionTruncate |
6772                          File::eOpenOptionCanCreate);
6773         if (!core_file) {
6774           error = core_file.takeError();
6775         } else {
6776           // Read 1 page at a time
6777           uint8_t bytes[0x1000];
6778           // Write the mach header and load commands out to the core file
6779           size_t bytes_written = buffer.GetString().size();
6780           error =
6781               core_file.get()->Write(buffer.GetString().data(), bytes_written);
6782           if (error.Success()) {
6783 
6784             for (auto &lcnote : lc_notes) {
6785               if (core_file.get()->SeekFromStart(lcnote->payload_file_offset) ==
6786                   -1) {
6787                 error.SetErrorStringWithFormat("Unable to seek to corefile pos "
6788                                                "to write '%s' LC_NOTE payload",
6789                                                lcnote->name.c_str());
6790                 return false;
6791               }
6792               bytes_written = lcnote->payload.GetSize();
6793               error = core_file.get()->Write(lcnote->payload.GetData(),
6794                                              bytes_written);
6795               if (!error.Success())
6796                 return false;
6797             }
6798 
6799             // Now write the file data for all memory segments in the process
6800             for (const auto &segment : segment_load_commands) {
6801               if (core_file.get()->SeekFromStart(segment.fileoff) == -1) {
6802                 error.SetErrorStringWithFormat(
6803                     "unable to seek to offset 0x%" PRIx64 " in '%s'",
6804                     segment.fileoff, core_file_path.c_str());
6805                 break;
6806               }
6807 
6808               target.GetDebugger().GetAsyncOutputStream()->Printf(
6809                   "Saving %" PRId64
6810                   " bytes of data for memory region at 0x%" PRIx64 "\n",
6811                   segment.vmsize, segment.vmaddr);
6812               addr_t bytes_left = segment.vmsize;
6813               addr_t addr = segment.vmaddr;
6814               Status memory_read_error;
6815               while (bytes_left > 0 && error.Success()) {
6816                 const size_t bytes_to_read =
6817                     bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6818 
6819                 // In a savecore setting, we don't really care about caching,
6820                 // as the data is dumped and very likely never read again,
6821                 // so we call ReadMemoryFromInferior to bypass it.
6822                 const size_t bytes_read = process_sp->ReadMemoryFromInferior(
6823                     addr, bytes, bytes_to_read, memory_read_error);
6824 
6825                 if (bytes_read == bytes_to_read) {
6826                   size_t bytes_written = bytes_read;
6827                   error = core_file.get()->Write(bytes, bytes_written);
6828                   bytes_left -= bytes_read;
6829                   addr += bytes_read;
6830                 } else {
6831                   // Some pages within regions are not readable, those should
6832                   // be zero filled
6833                   memset(bytes, 0, bytes_to_read);
6834                   size_t bytes_written = bytes_to_read;
6835                   error = core_file.get()->Write(bytes, bytes_written);
6836                   bytes_left -= bytes_to_read;
6837                   addr += bytes_to_read;
6838                 }
6839               }
6840             }
6841           }
6842         }
6843       } else {
6844         error.SetErrorString(
6845             "process doesn't support getting memory region info");
6846       }
6847     }
6848     return true; // This is the right plug to handle saving core files for
6849                  // this process
6850   }
6851   return false;
6852 }
6853 
6854 ObjectFileMachO::MachOCorefileAllImageInfos
6855 ObjectFileMachO::GetCorefileAllImageInfos() {
6856   MachOCorefileAllImageInfos image_infos;
6857 
6858   // Look for an "all image infos" LC_NOTE.
6859   lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
6860   for (uint32_t i = 0; i < m_header.ncmds; ++i) {
6861     const uint32_t cmd_offset = offset;
6862     llvm::MachO::load_command lc;
6863     if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
6864       break;
6865     if (lc.cmd == LC_NOTE) {
6866       char data_owner[17];
6867       m_data.CopyData(offset, 16, data_owner);
6868       data_owner[16] = '\0';
6869       offset += 16;
6870       uint64_t fileoff = m_data.GetU64_unchecked(&offset);
6871       offset += 4; /* size unused */
6872 
6873       if (strcmp("all image infos", data_owner) == 0) {
6874         offset = fileoff;
6875         // Read the struct all_image_infos_header.
6876         uint32_t version = m_data.GetU32(&offset);
6877         if (version != 1) {
6878           return image_infos;
6879         }
6880         uint32_t imgcount = m_data.GetU32(&offset);
6881         uint64_t entries_fileoff = m_data.GetU64(&offset);
6882         offset += 4; // uint32_t entries_size;
6883         offset += 4; // uint32_t unused;
6884 
6885         offset = entries_fileoff;
6886         for (uint32_t i = 0; i < imgcount; i++) {
6887           // Read the struct image_entry.
6888           offset_t filepath_offset = m_data.GetU64(&offset);
6889           uuid_t uuid;
6890           memcpy(&uuid, m_data.GetData(&offset, sizeof(uuid_t)),
6891                  sizeof(uuid_t));
6892           uint64_t load_address = m_data.GetU64(&offset);
6893           offset_t seg_addrs_offset = m_data.GetU64(&offset);
6894           uint32_t segment_count = m_data.GetU32(&offset);
6895           uint32_t currently_executing = m_data.GetU32(&offset);
6896 
6897           MachOCorefileImageEntry image_entry;
6898           image_entry.filename = (const char *)m_data.GetCStr(&filepath_offset);
6899           image_entry.uuid = UUID::fromData(uuid, sizeof(uuid_t));
6900           image_entry.load_address = load_address;
6901           image_entry.currently_executing = currently_executing;
6902 
6903           offset_t seg_vmaddrs_offset = seg_addrs_offset;
6904           for (uint32_t j = 0; j < segment_count; j++) {
6905             char segname[17];
6906             m_data.CopyData(seg_vmaddrs_offset, 16, segname);
6907             segname[16] = '\0';
6908             seg_vmaddrs_offset += 16;
6909             uint64_t vmaddr = m_data.GetU64(&seg_vmaddrs_offset);
6910             seg_vmaddrs_offset += 8; /* unused */
6911 
6912             std::tuple<ConstString, addr_t> new_seg{ConstString(segname),
6913                                                     vmaddr};
6914             image_entry.segment_load_addresses.push_back(new_seg);
6915           }
6916           image_infos.all_image_infos.push_back(image_entry);
6917         }
6918       } else if (strcmp("load binary", data_owner) == 0) {
6919         uint32_t version = m_data.GetU32(&fileoff);
6920         if (version == 1) {
6921           uuid_t uuid;
6922           memcpy(&uuid, m_data.GetData(&fileoff, sizeof(uuid_t)),
6923                  sizeof(uuid_t));
6924           uint64_t load_address = m_data.GetU64(&fileoff);
6925           uint64_t slide = m_data.GetU64(&fileoff);
6926           std::string filename = m_data.GetCStr(&fileoff);
6927 
6928           MachOCorefileImageEntry image_entry;
6929           image_entry.filename = filename;
6930           image_entry.uuid = UUID::fromData(uuid, sizeof(uuid_t));
6931           image_entry.load_address = load_address;
6932           image_entry.slide = slide;
6933           image_infos.all_image_infos.push_back(image_entry);
6934         }
6935       }
6936     }
6937     offset = cmd_offset + lc.cmdsize;
6938   }
6939 
6940   return image_infos;
6941 }
6942 
6943 bool ObjectFileMachO::LoadCoreFileImages(lldb_private::Process &process) {
6944   MachOCorefileAllImageInfos image_infos = GetCorefileAllImageInfos();
6945   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
6946 
6947   ModuleList added_modules;
6948   for (const MachOCorefileImageEntry &image : image_infos.all_image_infos) {
6949     ModuleSpec module_spec;
6950     module_spec.GetUUID() = image.uuid;
6951     if (image.filename.empty()) {
6952       char namebuf[80];
6953       if (image.load_address != LLDB_INVALID_ADDRESS)
6954         snprintf(namebuf, sizeof(namebuf), "mem-image-0x%" PRIx64,
6955                  image.load_address);
6956       else
6957         snprintf(namebuf, sizeof(namebuf), "mem-image+0x%" PRIx64, image.slide);
6958       module_spec.GetFileSpec() = FileSpec(namebuf);
6959     } else {
6960       module_spec.GetFileSpec() = FileSpec(image.filename.c_str());
6961     }
6962     if (image.currently_executing) {
6963       Symbols::DownloadObjectAndSymbolFile(module_spec, true);
6964       if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
6965         process.GetTarget().GetOrCreateModule(module_spec, false);
6966       }
6967     }
6968     Status error;
6969     ModuleSP module_sp =
6970         process.GetTarget().GetOrCreateModule(module_spec, false, &error);
6971     if (!module_sp.get() || !module_sp->GetObjectFile()) {
6972       if (image.load_address != LLDB_INVALID_ADDRESS) {
6973         module_sp = process.ReadModuleFromMemory(module_spec.GetFileSpec(),
6974                                                  image.load_address);
6975       }
6976     }
6977     if (module_sp.get()) {
6978       // Will call ModulesDidLoad with all modules once they've all
6979       // been added to the Target with load addresses.  Don't notify
6980       // here, before the load address is set.
6981       const bool notify = false;
6982       process.GetTarget().GetImages().AppendIfNeeded(module_sp, notify);
6983       added_modules.Append(module_sp, notify);
6984       if (image.segment_load_addresses.size() > 0) {
6985         if (log) {
6986           std::string uuidstr = image.uuid.GetAsString();
6987           log->Printf("ObjectFileMachO::LoadCoreFileImages adding binary '%s' "
6988                       "UUID %s with section load addresses",
6989                       image.filename.c_str(), uuidstr.c_str());
6990         }
6991         for (auto name_vmaddr_tuple : image.segment_load_addresses) {
6992           SectionList *sectlist = module_sp->GetObjectFile()->GetSectionList();
6993           if (sectlist) {
6994             SectionSP sect_sp =
6995                 sectlist->FindSectionByName(std::get<0>(name_vmaddr_tuple));
6996             if (sect_sp) {
6997               process.GetTarget().SetSectionLoadAddress(
6998                   sect_sp, std::get<1>(name_vmaddr_tuple));
6999             }
7000           }
7001         }
7002       } else if (image.load_address != LLDB_INVALID_ADDRESS) {
7003         if (log) {
7004           std::string uuidstr = image.uuid.GetAsString();
7005           log->Printf("ObjectFileMachO::LoadCoreFileImages adding binary '%s' "
7006                       "UUID %s with load address 0x%" PRIx64,
7007                       image.filename.c_str(), uuidstr.c_str(),
7008                       image.load_address);
7009         }
7010         const bool address_is_slide = false;
7011         bool changed = false;
7012         module_sp->SetLoadAddress(process.GetTarget(), image.load_address,
7013                                   address_is_slide, changed);
7014       } else if (image.slide != 0) {
7015         if (log) {
7016           std::string uuidstr = image.uuid.GetAsString();
7017           log->Printf("ObjectFileMachO::LoadCoreFileImages adding binary '%s' "
7018                       "UUID %s with slide amount 0x%" PRIx64,
7019                       image.filename.c_str(), uuidstr.c_str(), image.slide);
7020         }
7021         const bool address_is_slide = true;
7022         bool changed = false;
7023         module_sp->SetLoadAddress(process.GetTarget(), image.slide,
7024                                   address_is_slide, changed);
7025       } else {
7026         if (log) {
7027           std::string uuidstr = image.uuid.GetAsString();
7028           log->Printf("ObjectFileMachO::LoadCoreFileImages adding binary '%s' "
7029                       "UUID %s at its file address, no slide applied",
7030                       image.filename.c_str(), uuidstr.c_str());
7031         }
7032         const bool address_is_slide = true;
7033         bool changed = false;
7034         module_sp->SetLoadAddress(process.GetTarget(), 0, address_is_slide,
7035                                   changed);
7036       }
7037     }
7038   }
7039   if (added_modules.GetSize() > 0) {
7040     process.GetTarget().ModulesDidLoad(added_modules);
7041     process.Flush();
7042     return true;
7043   }
7044   return false;
7045 }
7046