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