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