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