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