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/ArchSpec.h"
21 #include "lldb/Core/DataBufferLLVM.h"
22 #include "lldb/Core/Debugger.h"
23 #include "lldb/Core/FileSpecList.h"
24 #include "lldb/Core/Log.h"
25 #include "lldb/Core/Module.h"
26 #include "lldb/Core/ModuleSpec.h"
27 #include "lldb/Core/PluginManager.h"
28 #include "lldb/Core/RangeMap.h"
29 #include "lldb/Core/Section.h"
30 #include "lldb/Core/StreamFile.h"
31 #include "lldb/Core/Timer.h"
32 #include "lldb/Core/UUID.h"
33 #include "lldb/Host/FileSpec.h"
34 #include "lldb/Host/Host.h"
35 #include "lldb/Symbol/DWARFCallFrameInfo.h"
36 #include "lldb/Symbol/ObjectFile.h"
37 #include "lldb/Target/DynamicLoader.h"
38 #include "lldb/Target/MemoryRegionInfo.h"
39 #include "lldb/Target/Platform.h"
40 #include "lldb/Target/Process.h"
41 #include "lldb/Target/SectionLoadList.h"
42 #include "lldb/Target/Target.h"
43 #include "lldb/Target/Thread.h"
44 #include "lldb/Target/ThreadList.h"
45 #include "lldb/Utility/Error.h"
46 #include "lldb/Utility/StreamString.h"
47 
48 #include "lldb/Utility/SafeMachO.h"
49 
50 #include "llvm/Support/MemoryBuffer.h"
51 
52 #include "ObjectFileMachO.h"
53 
54 #if defined(__APPLE__) &&                                                      \
55     (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
56 // GetLLDBSharedCacheUUID() needs to call dlsym()
57 #include <dlfcn.h>
58 #endif
59 
60 #ifndef __APPLE__
61 #include "Utility/UuidCompatibility.h"
62 #endif
63 
64 #define THUMB_ADDRESS_BIT_MASK 0xfffffffffffffffeull
65 using namespace lldb;
66 using namespace lldb_private;
67 using namespace llvm::MachO;
68 
69 // Some structure definitions needed for parsing the dyld shared cache files
70 // found on iOS devices.
71 
72 struct lldb_copy_dyld_cache_header_v1 {
73   char magic[16];         // e.g. "dyld_v0    i386", "dyld_v1   armv7", etc.
74   uint32_t mappingOffset; // file offset to first dyld_cache_mapping_info
75   uint32_t mappingCount;  // number of dyld_cache_mapping_info entries
76   uint32_t imagesOffset;
77   uint32_t imagesCount;
78   uint64_t dyldBaseAddress;
79   uint64_t codeSignatureOffset;
80   uint64_t codeSignatureSize;
81   uint64_t slideInfoOffset;
82   uint64_t slideInfoSize;
83   uint64_t localSymbolsOffset;
84   uint64_t localSymbolsSize;
85   uint8_t uuid[16]; // v1 and above, also recorded in dyld_all_image_infos v13
86                     // and later
87 };
88 
89 struct lldb_copy_dyld_cache_mapping_info {
90   uint64_t address;
91   uint64_t size;
92   uint64_t fileOffset;
93   uint32_t maxProt;
94   uint32_t initProt;
95 };
96 
97 struct lldb_copy_dyld_cache_local_symbols_info {
98   uint32_t nlistOffset;
99   uint32_t nlistCount;
100   uint32_t stringsOffset;
101   uint32_t stringsSize;
102   uint32_t entriesOffset;
103   uint32_t entriesCount;
104 };
105 struct lldb_copy_dyld_cache_local_symbols_entry {
106   uint32_t dylibOffset;
107   uint32_t nlistStartIndex;
108   uint32_t nlistCount;
109 };
110 
111 class RegisterContextDarwin_x86_64_Mach : public RegisterContextDarwin_x86_64 {
112 public:
113   RegisterContextDarwin_x86_64_Mach(lldb_private::Thread &thread,
114                                     const DataExtractor &data)
115       : RegisterContextDarwin_x86_64(thread, 0) {
116     SetRegisterDataFrom_LC_THREAD(data);
117   }
118 
119   void InvalidateAllRegisters() override {
120     // Do nothing... registers are always valid...
121   }
122 
123   void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
124     lldb::offset_t offset = 0;
125     SetError(GPRRegSet, Read, -1);
126     SetError(FPURegSet, Read, -1);
127     SetError(EXCRegSet, Read, -1);
128     bool done = false;
129 
130     while (!done) {
131       int flavor = data.GetU32(&offset);
132       if (flavor == 0)
133         done = true;
134       else {
135         uint32_t i;
136         uint32_t count = data.GetU32(&offset);
137         switch (flavor) {
138         case GPRRegSet:
139           for (i = 0; i < count; ++i)
140             (&gpr.rax)[i] = data.GetU64(&offset);
141           SetError(GPRRegSet, Read, 0);
142           done = true;
143 
144           break;
145         case FPURegSet:
146           // TODO: fill in FPU regs....
147           // SetError (FPURegSet, Read, -1);
148           done = true;
149 
150           break;
151         case EXCRegSet:
152           exc.trapno = data.GetU32(&offset);
153           exc.err = data.GetU32(&offset);
154           exc.faultvaddr = data.GetU64(&offset);
155           SetError(EXCRegSet, Read, 0);
156           done = true;
157           break;
158         case 7:
159         case 8:
160         case 9:
161           // fancy flavors that encapsulate of the above
162           // flavors...
163           break;
164 
165         default:
166           done = true;
167           break;
168         }
169       }
170     }
171   }
172 
173   static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
174                               const char *alt_name, size_t reg_byte_size,
175                               Stream &data) {
176     const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
177     if (reg_info == NULL)
178       reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
179     if (reg_info) {
180       lldb_private::RegisterValue reg_value;
181       if (reg_ctx->ReadRegister(reg_info, reg_value)) {
182         if (reg_info->byte_size >= reg_byte_size)
183           data.Write(reg_value.GetBytes(), reg_byte_size);
184         else {
185           data.Write(reg_value.GetBytes(), reg_info->byte_size);
186           for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
187                ++i)
188             data.PutChar(0);
189         }
190         return reg_byte_size;
191       }
192     }
193     // Just write zeros if all else fails
194     for (size_t i = 0; i < reg_byte_size; ++i)
195       data.PutChar(0);
196     return reg_byte_size;
197   }
198 
199   static bool Create_LC_THREAD(Thread *thread, Stream &data) {
200     RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
201     if (reg_ctx_sp) {
202       RegisterContext *reg_ctx = reg_ctx_sp.get();
203 
204       data.PutHex32(GPRRegSet); // Flavor
205       data.PutHex32(GPRWordCount);
206       WriteRegister(reg_ctx, "rax", NULL, 8, data);
207       WriteRegister(reg_ctx, "rbx", NULL, 8, data);
208       WriteRegister(reg_ctx, "rcx", NULL, 8, data);
209       WriteRegister(reg_ctx, "rdx", NULL, 8, data);
210       WriteRegister(reg_ctx, "rdi", NULL, 8, data);
211       WriteRegister(reg_ctx, "rsi", NULL, 8, data);
212       WriteRegister(reg_ctx, "rbp", NULL, 8, data);
213       WriteRegister(reg_ctx, "rsp", NULL, 8, data);
214       WriteRegister(reg_ctx, "r8", NULL, 8, data);
215       WriteRegister(reg_ctx, "r9", NULL, 8, data);
216       WriteRegister(reg_ctx, "r10", NULL, 8, data);
217       WriteRegister(reg_ctx, "r11", NULL, 8, data);
218       WriteRegister(reg_ctx, "r12", NULL, 8, data);
219       WriteRegister(reg_ctx, "r13", NULL, 8, data);
220       WriteRegister(reg_ctx, "r14", NULL, 8, data);
221       WriteRegister(reg_ctx, "r15", NULL, 8, data);
222       WriteRegister(reg_ctx, "rip", NULL, 8, data);
223       WriteRegister(reg_ctx, "rflags", NULL, 8, data);
224       WriteRegister(reg_ctx, "cs", NULL, 8, data);
225       WriteRegister(reg_ctx, "fs", NULL, 8, data);
226       WriteRegister(reg_ctx, "gs", NULL, 8, data);
227 
228       //            // Write out the FPU registers
229       //            const size_t fpu_byte_size = sizeof(FPU);
230       //            size_t bytes_written = 0;
231       //            data.PutHex32 (FPURegSet);
232       //            data.PutHex32 (fpu_byte_size/sizeof(uint64_t));
233       //            bytes_written += data.PutHex32(0); // uint32_t pad[0]
234       //            bytes_written += data.PutHex32(0); // uint32_t pad[1]
235       //            bytes_written += WriteRegister (reg_ctx, "fcw", "fctrl", 2,
236       //            data);   // uint16_t    fcw;    // "fctrl"
237       //            bytes_written += WriteRegister (reg_ctx, "fsw" , "fstat", 2,
238       //            data);  // uint16_t    fsw;    // "fstat"
239       //            bytes_written += WriteRegister (reg_ctx, "ftw" , "ftag", 1,
240       //            data);   // uint8_t     ftw;    // "ftag"
241       //            bytes_written += data.PutHex8  (0); // uint8_t pad1;
242       //            bytes_written += WriteRegister (reg_ctx, "fop" , NULL, 2,
243       //            data);     // uint16_t    fop;    // "fop"
244       //            bytes_written += WriteRegister (reg_ctx, "fioff", "ip", 4,
245       //            data);    // uint32_t    ip;     // "fioff"
246       //            bytes_written += WriteRegister (reg_ctx, "fiseg", NULL, 2,
247       //            data);    // uint16_t    cs;     // "fiseg"
248       //            bytes_written += data.PutHex16 (0); // uint16_t    pad2;
249       //            bytes_written += WriteRegister (reg_ctx, "dp", "fooff" , 4,
250       //            data);   // uint32_t    dp;     // "fooff"
251       //            bytes_written += WriteRegister (reg_ctx, "foseg", NULL, 2,
252       //            data);    // uint16_t    ds;     // "foseg"
253       //            bytes_written += data.PutHex16 (0); // uint16_t    pad3;
254       //            bytes_written += WriteRegister (reg_ctx, "mxcsr", NULL, 4,
255       //            data);    // uint32_t    mxcsr;
256       //            bytes_written += WriteRegister (reg_ctx, "mxcsrmask", NULL,
257       //            4, data);// uint32_t    mxcsrmask;
258       //            bytes_written += WriteRegister (reg_ctx, "stmm0", NULL,
259       //            sizeof(MMSReg), data);
260       //            bytes_written += WriteRegister (reg_ctx, "stmm1", NULL,
261       //            sizeof(MMSReg), data);
262       //            bytes_written += WriteRegister (reg_ctx, "stmm2", NULL,
263       //            sizeof(MMSReg), data);
264       //            bytes_written += WriteRegister (reg_ctx, "stmm3", NULL,
265       //            sizeof(MMSReg), data);
266       //            bytes_written += WriteRegister (reg_ctx, "stmm4", NULL,
267       //            sizeof(MMSReg), data);
268       //            bytes_written += WriteRegister (reg_ctx, "stmm5", NULL,
269       //            sizeof(MMSReg), data);
270       //            bytes_written += WriteRegister (reg_ctx, "stmm6", NULL,
271       //            sizeof(MMSReg), data);
272       //            bytes_written += WriteRegister (reg_ctx, "stmm7", NULL,
273       //            sizeof(MMSReg), data);
274       //            bytes_written += WriteRegister (reg_ctx, "xmm0" , NULL,
275       //            sizeof(XMMReg), data);
276       //            bytes_written += WriteRegister (reg_ctx, "xmm1" , NULL,
277       //            sizeof(XMMReg), data);
278       //            bytes_written += WriteRegister (reg_ctx, "xmm2" , NULL,
279       //            sizeof(XMMReg), data);
280       //            bytes_written += WriteRegister (reg_ctx, "xmm3" , NULL,
281       //            sizeof(XMMReg), data);
282       //            bytes_written += WriteRegister (reg_ctx, "xmm4" , NULL,
283       //            sizeof(XMMReg), data);
284       //            bytes_written += WriteRegister (reg_ctx, "xmm5" , NULL,
285       //            sizeof(XMMReg), data);
286       //            bytes_written += WriteRegister (reg_ctx, "xmm6" , NULL,
287       //            sizeof(XMMReg), data);
288       //            bytes_written += WriteRegister (reg_ctx, "xmm7" , NULL,
289       //            sizeof(XMMReg), data);
290       //            bytes_written += WriteRegister (reg_ctx, "xmm8" , NULL,
291       //            sizeof(XMMReg), data);
292       //            bytes_written += WriteRegister (reg_ctx, "xmm9" , NULL,
293       //            sizeof(XMMReg), data);
294       //            bytes_written += WriteRegister (reg_ctx, "xmm10", NULL,
295       //            sizeof(XMMReg), data);
296       //            bytes_written += WriteRegister (reg_ctx, "xmm11", NULL,
297       //            sizeof(XMMReg), data);
298       //            bytes_written += WriteRegister (reg_ctx, "xmm12", NULL,
299       //            sizeof(XMMReg), data);
300       //            bytes_written += WriteRegister (reg_ctx, "xmm13", NULL,
301       //            sizeof(XMMReg), data);
302       //            bytes_written += WriteRegister (reg_ctx, "xmm14", NULL,
303       //            sizeof(XMMReg), data);
304       //            bytes_written += WriteRegister (reg_ctx, "xmm15", NULL,
305       //            sizeof(XMMReg), data);
306       //
307       //            // Fill rest with zeros
308       //            for (size_t i=0, n = fpu_byte_size - bytes_written; i<n; ++
309       //            i)
310       //                data.PutChar(0);
311 
312       // Write out the EXC registers
313       data.PutHex32(EXCRegSet);
314       data.PutHex32(EXCWordCount);
315       WriteRegister(reg_ctx, "trapno", NULL, 4, data);
316       WriteRegister(reg_ctx, "err", NULL, 4, data);
317       WriteRegister(reg_ctx, "faultvaddr", NULL, 8, data);
318       return true;
319     }
320     return false;
321   }
322 
323 protected:
324   int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
325 
326   int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
327 
328   int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
329 
330   int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
331     return 0;
332   }
333 
334   int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
335     return 0;
336   }
337 
338   int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
339     return 0;
340   }
341 };
342 
343 class RegisterContextDarwin_i386_Mach : public RegisterContextDarwin_i386 {
344 public:
345   RegisterContextDarwin_i386_Mach(lldb_private::Thread &thread,
346                                   const DataExtractor &data)
347       : RegisterContextDarwin_i386(thread, 0) {
348     SetRegisterDataFrom_LC_THREAD(data);
349   }
350 
351   void InvalidateAllRegisters() override {
352     // Do nothing... registers are always valid...
353   }
354 
355   void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
356     lldb::offset_t offset = 0;
357     SetError(GPRRegSet, Read, -1);
358     SetError(FPURegSet, Read, -1);
359     SetError(EXCRegSet, Read, -1);
360     bool done = false;
361 
362     while (!done) {
363       int flavor = data.GetU32(&offset);
364       if (flavor == 0)
365         done = true;
366       else {
367         uint32_t i;
368         uint32_t count = data.GetU32(&offset);
369         switch (flavor) {
370         case GPRRegSet:
371           for (i = 0; i < count; ++i)
372             (&gpr.eax)[i] = data.GetU32(&offset);
373           SetError(GPRRegSet, Read, 0);
374           done = true;
375 
376           break;
377         case FPURegSet:
378           // TODO: fill in FPU regs....
379           // SetError (FPURegSet, Read, -1);
380           done = true;
381 
382           break;
383         case EXCRegSet:
384           exc.trapno = data.GetU32(&offset);
385           exc.err = data.GetU32(&offset);
386           exc.faultvaddr = data.GetU32(&offset);
387           SetError(EXCRegSet, Read, 0);
388           done = true;
389           break;
390         case 7:
391         case 8:
392         case 9:
393           // fancy flavors that encapsulate of the above
394           // flavors...
395           break;
396 
397         default:
398           done = true;
399           break;
400         }
401       }
402     }
403   }
404 
405   static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
406                               const char *alt_name, size_t reg_byte_size,
407                               Stream &data) {
408     const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
409     if (reg_info == NULL)
410       reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
411     if (reg_info) {
412       lldb_private::RegisterValue reg_value;
413       if (reg_ctx->ReadRegister(reg_info, reg_value)) {
414         if (reg_info->byte_size >= reg_byte_size)
415           data.Write(reg_value.GetBytes(), reg_byte_size);
416         else {
417           data.Write(reg_value.GetBytes(), reg_info->byte_size);
418           for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
419                ++i)
420             data.PutChar(0);
421         }
422         return reg_byte_size;
423       }
424     }
425     // Just write zeros if all else fails
426     for (size_t i = 0; i < reg_byte_size; ++i)
427       data.PutChar(0);
428     return reg_byte_size;
429   }
430 
431   static bool Create_LC_THREAD(Thread *thread, Stream &data) {
432     RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
433     if (reg_ctx_sp) {
434       RegisterContext *reg_ctx = reg_ctx_sp.get();
435 
436       data.PutHex32(GPRRegSet); // Flavor
437       data.PutHex32(GPRWordCount);
438       WriteRegister(reg_ctx, "eax", NULL, 4, data);
439       WriteRegister(reg_ctx, "ebx", NULL, 4, data);
440       WriteRegister(reg_ctx, "ecx", NULL, 4, data);
441       WriteRegister(reg_ctx, "edx", NULL, 4, data);
442       WriteRegister(reg_ctx, "edi", NULL, 4, data);
443       WriteRegister(reg_ctx, "esi", NULL, 4, data);
444       WriteRegister(reg_ctx, "ebp", NULL, 4, data);
445       WriteRegister(reg_ctx, "esp", NULL, 4, data);
446       WriteRegister(reg_ctx, "ss", NULL, 4, data);
447       WriteRegister(reg_ctx, "eflags", NULL, 4, data);
448       WriteRegister(reg_ctx, "eip", NULL, 4, data);
449       WriteRegister(reg_ctx, "cs", NULL, 4, data);
450       WriteRegister(reg_ctx, "ds", NULL, 4, data);
451       WriteRegister(reg_ctx, "es", NULL, 4, data);
452       WriteRegister(reg_ctx, "fs", NULL, 4, data);
453       WriteRegister(reg_ctx, "gs", NULL, 4, data);
454 
455       // Write out the EXC registers
456       data.PutHex32(EXCRegSet);
457       data.PutHex32(EXCWordCount);
458       WriteRegister(reg_ctx, "trapno", NULL, 4, data);
459       WriteRegister(reg_ctx, "err", NULL, 4, data);
460       WriteRegister(reg_ctx, "faultvaddr", NULL, 4, data);
461       return true;
462     }
463     return false;
464   }
465 
466 protected:
467   int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
468 
469   int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
470 
471   int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
472 
473   int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
474     return 0;
475   }
476 
477   int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
478     return 0;
479   }
480 
481   int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
482     return 0;
483   }
484 };
485 
486 class RegisterContextDarwin_arm_Mach : public RegisterContextDarwin_arm {
487 public:
488   RegisterContextDarwin_arm_Mach(lldb_private::Thread &thread,
489                                  const DataExtractor &data)
490       : RegisterContextDarwin_arm(thread, 0) {
491     SetRegisterDataFrom_LC_THREAD(data);
492   }
493 
494   void InvalidateAllRegisters() override {
495     // Do nothing... registers are always valid...
496   }
497 
498   void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
499     lldb::offset_t offset = 0;
500     SetError(GPRRegSet, Read, -1);
501     SetError(FPURegSet, Read, -1);
502     SetError(EXCRegSet, Read, -1);
503     bool done = false;
504 
505     while (!done) {
506       int flavor = data.GetU32(&offset);
507       uint32_t count = data.GetU32(&offset);
508       lldb::offset_t next_thread_state = offset + (count * 4);
509       switch (flavor) {
510       case GPRAltRegSet:
511       case GPRRegSet:
512         for (uint32_t i = 0; i < count; ++i) {
513           gpr.r[i] = data.GetU32(&offset);
514         }
515 
516         // Note that gpr.cpsr is also copied by the above loop; this loop
517         // technically extends
518         // one element past the end of the gpr.r[] array.
519 
520         SetError(GPRRegSet, Read, 0);
521         offset = next_thread_state;
522         break;
523 
524       case FPURegSet: {
525         uint8_t *fpu_reg_buf = (uint8_t *)&fpu.floats.s[0];
526         const int fpu_reg_buf_size = sizeof(fpu.floats);
527         if (data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
528                               fpu_reg_buf) == fpu_reg_buf_size) {
529           offset += fpu_reg_buf_size;
530           fpu.fpscr = data.GetU32(&offset);
531           SetError(FPURegSet, Read, 0);
532         } else {
533           done = true;
534         }
535       }
536         offset = next_thread_state;
537         break;
538 
539       case EXCRegSet:
540         if (count == 3) {
541           exc.exception = data.GetU32(&offset);
542           exc.fsr = data.GetU32(&offset);
543           exc.far = data.GetU32(&offset);
544           SetError(EXCRegSet, Read, 0);
545         }
546         done = true;
547         offset = next_thread_state;
548         break;
549 
550       // Unknown register set flavor, stop trying to parse.
551       default:
552         done = true;
553       }
554     }
555   }
556 
557   static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
558                               const char *alt_name, size_t reg_byte_size,
559                               Stream &data) {
560     const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
561     if (reg_info == NULL)
562       reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
563     if (reg_info) {
564       lldb_private::RegisterValue reg_value;
565       if (reg_ctx->ReadRegister(reg_info, reg_value)) {
566         if (reg_info->byte_size >= reg_byte_size)
567           data.Write(reg_value.GetBytes(), reg_byte_size);
568         else {
569           data.Write(reg_value.GetBytes(), reg_info->byte_size);
570           for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
571                ++i)
572             data.PutChar(0);
573         }
574         return reg_byte_size;
575       }
576     }
577     // Just write zeros if all else fails
578     for (size_t i = 0; i < reg_byte_size; ++i)
579       data.PutChar(0);
580     return reg_byte_size;
581   }
582 
583   static bool Create_LC_THREAD(Thread *thread, Stream &data) {
584     RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
585     if (reg_ctx_sp) {
586       RegisterContext *reg_ctx = reg_ctx_sp.get();
587 
588       data.PutHex32(GPRRegSet); // Flavor
589       data.PutHex32(GPRWordCount);
590       WriteRegister(reg_ctx, "r0", NULL, 4, data);
591       WriteRegister(reg_ctx, "r1", NULL, 4, data);
592       WriteRegister(reg_ctx, "r2", NULL, 4, data);
593       WriteRegister(reg_ctx, "r3", NULL, 4, data);
594       WriteRegister(reg_ctx, "r4", NULL, 4, data);
595       WriteRegister(reg_ctx, "r5", NULL, 4, data);
596       WriteRegister(reg_ctx, "r6", NULL, 4, data);
597       WriteRegister(reg_ctx, "r7", NULL, 4, data);
598       WriteRegister(reg_ctx, "r8", NULL, 4, data);
599       WriteRegister(reg_ctx, "r9", NULL, 4, data);
600       WriteRegister(reg_ctx, "r10", NULL, 4, data);
601       WriteRegister(reg_ctx, "r11", NULL, 4, data);
602       WriteRegister(reg_ctx, "r12", NULL, 4, data);
603       WriteRegister(reg_ctx, "sp", NULL, 4, data);
604       WriteRegister(reg_ctx, "lr", NULL, 4, data);
605       WriteRegister(reg_ctx, "pc", NULL, 4, data);
606       WriteRegister(reg_ctx, "cpsr", NULL, 4, data);
607 
608       // Write out the EXC registers
609       //            data.PutHex32 (EXCRegSet);
610       //            data.PutHex32 (EXCWordCount);
611       //            WriteRegister (reg_ctx, "exception", NULL, 4, data);
612       //            WriteRegister (reg_ctx, "fsr", NULL, 4, data);
613       //            WriteRegister (reg_ctx, "far", NULL, 4, data);
614       return true;
615     }
616     return false;
617   }
618 
619 protected:
620   int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
621 
622   int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
623 
624   int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
625 
626   int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
627 
628   int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
629     return 0;
630   }
631 
632   int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
633     return 0;
634   }
635 
636   int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
637     return 0;
638   }
639 
640   int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
641     return -1;
642   }
643 };
644 
645 class RegisterContextDarwin_arm64_Mach : public RegisterContextDarwin_arm64 {
646 public:
647   RegisterContextDarwin_arm64_Mach(lldb_private::Thread &thread,
648                                    const DataExtractor &data)
649       : RegisterContextDarwin_arm64(thread, 0) {
650     SetRegisterDataFrom_LC_THREAD(data);
651   }
652 
653   void InvalidateAllRegisters() override {
654     // Do nothing... registers are always valid...
655   }
656 
657   void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data) {
658     lldb::offset_t offset = 0;
659     SetError(GPRRegSet, Read, -1);
660     SetError(FPURegSet, Read, -1);
661     SetError(EXCRegSet, Read, -1);
662     bool done = false;
663     while (!done) {
664       int flavor = data.GetU32(&offset);
665       uint32_t count = data.GetU32(&offset);
666       lldb::offset_t next_thread_state = offset + (count * 4);
667       switch (flavor) {
668       case GPRRegSet:
669         // x0-x29 + fp + lr + sp + pc (== 33 64-bit registers) plus cpsr (1
670         // 32-bit register)
671         if (count >= (33 * 2) + 1) {
672           for (uint32_t i = 0; i < 29; ++i)
673             gpr.x[i] = data.GetU64(&offset);
674           gpr.fp = data.GetU64(&offset);
675           gpr.lr = data.GetU64(&offset);
676           gpr.sp = data.GetU64(&offset);
677           gpr.pc = data.GetU64(&offset);
678           gpr.cpsr = data.GetU32(&offset);
679           SetError(GPRRegSet, Read, 0);
680         }
681         offset = next_thread_state;
682         break;
683       case FPURegSet: {
684         uint8_t *fpu_reg_buf = (uint8_t *)&fpu.v[0];
685         const int fpu_reg_buf_size = sizeof(fpu);
686         if (fpu_reg_buf_size == count &&
687             data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
688                               fpu_reg_buf) == fpu_reg_buf_size) {
689           SetError(FPURegSet, Read, 0);
690         } else {
691           done = true;
692         }
693       }
694         offset = next_thread_state;
695         break;
696       case EXCRegSet:
697         if (count == 4) {
698           exc.far = data.GetU64(&offset);
699           exc.esr = data.GetU32(&offset);
700           exc.exception = data.GetU32(&offset);
701           SetError(EXCRegSet, Read, 0);
702         }
703         offset = next_thread_state;
704         break;
705       default:
706         done = true;
707         break;
708       }
709     }
710   }
711 
712   static size_t WriteRegister(RegisterContext *reg_ctx, const char *name,
713                               const char *alt_name, size_t reg_byte_size,
714                               Stream &data) {
715     const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
716     if (reg_info == NULL)
717       reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
718     if (reg_info) {
719       lldb_private::RegisterValue reg_value;
720       if (reg_ctx->ReadRegister(reg_info, reg_value)) {
721         if (reg_info->byte_size >= reg_byte_size)
722           data.Write(reg_value.GetBytes(), reg_byte_size);
723         else {
724           data.Write(reg_value.GetBytes(), reg_info->byte_size);
725           for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n;
726                ++i)
727             data.PutChar(0);
728         }
729         return reg_byte_size;
730       }
731     }
732     // Just write zeros if all else fails
733     for (size_t i = 0; i < reg_byte_size; ++i)
734       data.PutChar(0);
735     return reg_byte_size;
736   }
737 
738   static bool Create_LC_THREAD(Thread *thread, Stream &data) {
739     RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
740     if (reg_ctx_sp) {
741       RegisterContext *reg_ctx = reg_ctx_sp.get();
742 
743       data.PutHex32(GPRRegSet); // Flavor
744       data.PutHex32(GPRWordCount);
745       WriteRegister(reg_ctx, "x0", NULL, 8, data);
746       WriteRegister(reg_ctx, "x1", NULL, 8, data);
747       WriteRegister(reg_ctx, "x2", NULL, 8, data);
748       WriteRegister(reg_ctx, "x3", NULL, 8, data);
749       WriteRegister(reg_ctx, "x4", NULL, 8, data);
750       WriteRegister(reg_ctx, "x5", NULL, 8, data);
751       WriteRegister(reg_ctx, "x6", NULL, 8, data);
752       WriteRegister(reg_ctx, "x7", NULL, 8, data);
753       WriteRegister(reg_ctx, "x8", NULL, 8, data);
754       WriteRegister(reg_ctx, "x9", NULL, 8, data);
755       WriteRegister(reg_ctx, "x10", NULL, 8, data);
756       WriteRegister(reg_ctx, "x11", NULL, 8, data);
757       WriteRegister(reg_ctx, "x12", NULL, 8, data);
758       WriteRegister(reg_ctx, "x13", NULL, 8, data);
759       WriteRegister(reg_ctx, "x14", NULL, 8, data);
760       WriteRegister(reg_ctx, "x15", NULL, 8, data);
761       WriteRegister(reg_ctx, "x16", NULL, 8, data);
762       WriteRegister(reg_ctx, "x17", NULL, 8, data);
763       WriteRegister(reg_ctx, "x18", NULL, 8, data);
764       WriteRegister(reg_ctx, "x19", NULL, 8, data);
765       WriteRegister(reg_ctx, "x20", NULL, 8, data);
766       WriteRegister(reg_ctx, "x21", NULL, 8, data);
767       WriteRegister(reg_ctx, "x22", NULL, 8, data);
768       WriteRegister(reg_ctx, "x23", NULL, 8, data);
769       WriteRegister(reg_ctx, "x24", NULL, 8, data);
770       WriteRegister(reg_ctx, "x25", NULL, 8, data);
771       WriteRegister(reg_ctx, "x26", NULL, 8, data);
772       WriteRegister(reg_ctx, "x27", NULL, 8, data);
773       WriteRegister(reg_ctx, "x28", NULL, 8, data);
774       WriteRegister(reg_ctx, "fp", NULL, 8, data);
775       WriteRegister(reg_ctx, "lr", NULL, 8, data);
776       WriteRegister(reg_ctx, "sp", NULL, 8, data);
777       WriteRegister(reg_ctx, "pc", NULL, 8, data);
778       WriteRegister(reg_ctx, "cpsr", NULL, 4, data);
779 
780       // Write out the EXC registers
781       //            data.PutHex32 (EXCRegSet);
782       //            data.PutHex32 (EXCWordCount);
783       //            WriteRegister (reg_ctx, "far", NULL, 8, data);
784       //            WriteRegister (reg_ctx, "esr", NULL, 4, data);
785       //            WriteRegister (reg_ctx, "exception", NULL, 4, data);
786       return true;
787     }
788     return false;
789   }
790 
791 protected:
792   int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
793 
794   int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
795 
796   int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
797 
798   int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
799 
800   int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
801     return 0;
802   }
803 
804   int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
805     return 0;
806   }
807 
808   int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
809     return 0;
810   }
811 
812   int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
813     return -1;
814   }
815 };
816 
817 static uint32_t MachHeaderSizeFromMagic(uint32_t magic) {
818   switch (magic) {
819   case MH_MAGIC:
820   case MH_CIGAM:
821     return sizeof(struct mach_header);
822 
823   case MH_MAGIC_64:
824   case MH_CIGAM_64:
825     return sizeof(struct mach_header_64);
826     break;
827 
828   default:
829     break;
830   }
831   return 0;
832 }
833 
834 #define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008
835 
836 void ObjectFileMachO::Initialize() {
837   PluginManager::RegisterPlugin(
838       GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance,
839       CreateMemoryInstance, GetModuleSpecifications, SaveCore);
840 }
841 
842 void ObjectFileMachO::Terminate() {
843   PluginManager::UnregisterPlugin(CreateInstance);
844 }
845 
846 lldb_private::ConstString ObjectFileMachO::GetPluginNameStatic() {
847   static ConstString g_name("mach-o");
848   return g_name;
849 }
850 
851 const char *ObjectFileMachO::GetPluginDescriptionStatic() {
852   return "Mach-o object file reader (32 and 64 bit)";
853 }
854 
855 ObjectFile *ObjectFileMachO::CreateInstance(const lldb::ModuleSP &module_sp,
856                                             DataBufferSP &data_sp,
857                                             lldb::offset_t data_offset,
858                                             const FileSpec *file,
859                                             lldb::offset_t file_offset,
860                                             lldb::offset_t length) {
861   if (!data_sp) {
862     data_sp = DataBufferLLVM::CreateFromFileSpec(*file, length, file_offset);
863     if (!data_sp)
864       return nullptr;
865     data_offset = 0;
866   }
867 
868   if (!ObjectFileMachO::MagicBytesMatch(data_sp, data_offset, length))
869     return nullptr;
870 
871   // Update the data to contain the entire file if it doesn't already
872   if (data_sp->GetByteSize() < length) {
873     data_sp = DataBufferLLVM::CreateFromFileSpec(*file, length, file_offset);
874     if (!data_sp)
875       return nullptr;
876     data_offset = 0;
877   }
878   auto objfile_ap = llvm::make_unique<ObjectFileMachO>(
879       module_sp, data_sp, data_offset, file, file_offset, length);
880   if (!objfile_ap || !objfile_ap->ParseHeader())
881     return nullptr;
882 
883   return objfile_ap.release();
884 }
885 
886 ObjectFile *ObjectFileMachO::CreateMemoryInstance(
887     const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,
888     const ProcessSP &process_sp, lldb::addr_t header_addr) {
889   if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
890     std::unique_ptr<ObjectFile> objfile_ap(
891         new ObjectFileMachO(module_sp, data_sp, process_sp, header_addr));
892     if (objfile_ap.get() && objfile_ap->ParseHeader())
893       return objfile_ap.release();
894   }
895   return NULL;
896 }
897 
898 size_t ObjectFileMachO::GetModuleSpecifications(
899     const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
900     lldb::offset_t data_offset, lldb::offset_t file_offset,
901     lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
902   const size_t initial_count = specs.GetSize();
903 
904   if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
905     DataExtractor data;
906     data.SetData(data_sp);
907     llvm::MachO::mach_header header;
908     if (ParseHeader(data, &data_offset, header)) {
909       size_t header_and_load_cmds =
910           header.sizeofcmds + MachHeaderSizeFromMagic(header.magic);
911       if (header_and_load_cmds >= data_sp->GetByteSize()) {
912         data_sp = file.ReadFileContents(file_offset, header_and_load_cmds);
913         data.SetData(data_sp);
914         data_offset = MachHeaderSizeFromMagic(header.magic);
915       }
916       if (data_sp) {
917         ModuleSpec spec;
918         spec.GetFileSpec() = file;
919         spec.SetObjectOffset(file_offset);
920         spec.SetObjectSize(length);
921 
922         if (GetArchitecture(header, data, data_offset,
923                             spec.GetArchitecture())) {
924           if (spec.GetArchitecture().IsValid()) {
925             GetUUID(header, data, data_offset, spec.GetUUID());
926             specs.Append(spec);
927           }
928         }
929       }
930     }
931   }
932   return specs.GetSize() - initial_count;
933 }
934 
935 const ConstString &ObjectFileMachO::GetSegmentNameTEXT() {
936   static ConstString g_segment_name_TEXT("__TEXT");
937   return g_segment_name_TEXT;
938 }
939 
940 const ConstString &ObjectFileMachO::GetSegmentNameDATA() {
941   static ConstString g_segment_name_DATA("__DATA");
942   return g_segment_name_DATA;
943 }
944 
945 const ConstString &ObjectFileMachO::GetSegmentNameDATA_DIRTY() {
946   static ConstString g_segment_name("__DATA_DIRTY");
947   return g_segment_name;
948 }
949 
950 const ConstString &ObjectFileMachO::GetSegmentNameDATA_CONST() {
951   static ConstString g_segment_name("__DATA_CONST");
952   return g_segment_name;
953 }
954 
955 const ConstString &ObjectFileMachO::GetSegmentNameOBJC() {
956   static ConstString g_segment_name_OBJC("__OBJC");
957   return g_segment_name_OBJC;
958 }
959 
960 const ConstString &ObjectFileMachO::GetSegmentNameLINKEDIT() {
961   static ConstString g_section_name_LINKEDIT("__LINKEDIT");
962   return g_section_name_LINKEDIT;
963 }
964 
965 const ConstString &ObjectFileMachO::GetSectionNameEHFrame() {
966   static ConstString g_section_name_eh_frame("__eh_frame");
967   return g_section_name_eh_frame;
968 }
969 
970 bool ObjectFileMachO::MagicBytesMatch(DataBufferSP &data_sp,
971                                       lldb::addr_t data_offset,
972                                       lldb::addr_t data_length) {
973   DataExtractor data;
974   data.SetData(data_sp, data_offset, data_length);
975   lldb::offset_t offset = 0;
976   uint32_t magic = data.GetU32(&offset);
977   return MachHeaderSizeFromMagic(magic) != 0;
978 }
979 
980 ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
981                                  DataBufferSP &data_sp,
982                                  lldb::offset_t data_offset,
983                                  const FileSpec *file,
984                                  lldb::offset_t file_offset,
985                                  lldb::offset_t length)
986     : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
987       m_mach_segments(), m_mach_sections(), m_entry_point_address(),
988       m_thread_context_offsets(), m_thread_context_offsets_valid(false),
989       m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
990   ::memset(&m_header, 0, sizeof(m_header));
991   ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
992 }
993 
994 ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
995                                  lldb::DataBufferSP &header_data_sp,
996                                  const lldb::ProcessSP &process_sp,
997                                  lldb::addr_t header_addr)
998     : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
999       m_mach_segments(), m_mach_sections(), m_entry_point_address(),
1000       m_thread_context_offsets(), m_thread_context_offsets_valid(false),
1001       m_reexported_dylibs(), m_allow_assembly_emulation_unwind_plans(true) {
1002   ::memset(&m_header, 0, sizeof(m_header));
1003   ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
1004 }
1005 
1006 bool ObjectFileMachO::ParseHeader(DataExtractor &data,
1007                                   lldb::offset_t *data_offset_ptr,
1008                                   llvm::MachO::mach_header &header) {
1009   data.SetByteOrder(endian::InlHostByteOrder());
1010   // Leave magic in the original byte order
1011   header.magic = data.GetU32(data_offset_ptr);
1012   bool can_parse = false;
1013   bool is_64_bit = false;
1014   switch (header.magic) {
1015   case MH_MAGIC:
1016     data.SetByteOrder(endian::InlHostByteOrder());
1017     data.SetAddressByteSize(4);
1018     can_parse = true;
1019     break;
1020 
1021   case MH_MAGIC_64:
1022     data.SetByteOrder(endian::InlHostByteOrder());
1023     data.SetAddressByteSize(8);
1024     can_parse = true;
1025     is_64_bit = true;
1026     break;
1027 
1028   case MH_CIGAM:
1029     data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1030                           ? eByteOrderLittle
1031                           : eByteOrderBig);
1032     data.SetAddressByteSize(4);
1033     can_parse = true;
1034     break;
1035 
1036   case MH_CIGAM_64:
1037     data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1038                           ? eByteOrderLittle
1039                           : eByteOrderBig);
1040     data.SetAddressByteSize(8);
1041     is_64_bit = true;
1042     can_parse = true;
1043     break;
1044 
1045   default:
1046     break;
1047   }
1048 
1049   if (can_parse) {
1050     data.GetU32(data_offset_ptr, &header.cputype, 6);
1051     if (is_64_bit)
1052       *data_offset_ptr += 4;
1053     return true;
1054   } else {
1055     memset(&header, 0, sizeof(header));
1056   }
1057   return false;
1058 }
1059 
1060 bool ObjectFileMachO::ParseHeader() {
1061   ModuleSP module_sp(GetModule());
1062   if (module_sp) {
1063     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1064     bool can_parse = false;
1065     lldb::offset_t offset = 0;
1066     m_data.SetByteOrder(endian::InlHostByteOrder());
1067     // Leave magic in the original byte order
1068     m_header.magic = m_data.GetU32(&offset);
1069     switch (m_header.magic) {
1070     case MH_MAGIC:
1071       m_data.SetByteOrder(endian::InlHostByteOrder());
1072       m_data.SetAddressByteSize(4);
1073       can_parse = true;
1074       break;
1075 
1076     case MH_MAGIC_64:
1077       m_data.SetByteOrder(endian::InlHostByteOrder());
1078       m_data.SetAddressByteSize(8);
1079       can_parse = true;
1080       break;
1081 
1082     case MH_CIGAM:
1083       m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1084                               ? eByteOrderLittle
1085                               : eByteOrderBig);
1086       m_data.SetAddressByteSize(4);
1087       can_parse = true;
1088       break;
1089 
1090     case MH_CIGAM_64:
1091       m_data.SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1092                               ? eByteOrderLittle
1093                               : eByteOrderBig);
1094       m_data.SetAddressByteSize(8);
1095       can_parse = true;
1096       break;
1097 
1098     default:
1099       break;
1100     }
1101 
1102     if (can_parse) {
1103       m_data.GetU32(&offset, &m_header.cputype, 6);
1104 
1105       ArchSpec mach_arch;
1106 
1107       if (GetArchitecture(mach_arch)) {
1108         // Check if the module has a required architecture
1109         const ArchSpec &module_arch = module_sp->GetArchitecture();
1110         if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch))
1111           return false;
1112 
1113         if (SetModulesArchitecture(mach_arch)) {
1114           const size_t header_and_lc_size =
1115               m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
1116           if (m_data.GetByteSize() < header_and_lc_size) {
1117             DataBufferSP data_sp;
1118             ProcessSP process_sp(m_process_wp.lock());
1119             if (process_sp) {
1120               data_sp =
1121                   ReadMemory(process_sp, m_memory_addr, header_and_lc_size);
1122             } else {
1123               // Read in all only the load command data from the file on disk
1124               data_sp =
1125                   m_file.ReadFileContents(m_file_offset, header_and_lc_size);
1126               if (data_sp->GetByteSize() != header_and_lc_size)
1127                 return false;
1128             }
1129             if (data_sp)
1130               m_data.SetData(data_sp);
1131           }
1132         }
1133         return true;
1134       }
1135     } else {
1136       memset(&m_header, 0, sizeof(struct mach_header));
1137     }
1138   }
1139   return false;
1140 }
1141 
1142 ByteOrder ObjectFileMachO::GetByteOrder() const {
1143   return m_data.GetByteOrder();
1144 }
1145 
1146 bool ObjectFileMachO::IsExecutable() const {
1147   return m_header.filetype == MH_EXECUTE;
1148 }
1149 
1150 uint32_t ObjectFileMachO::GetAddressByteSize() const {
1151   return m_data.GetAddressByteSize();
1152 }
1153 
1154 AddressClass ObjectFileMachO::GetAddressClass(lldb::addr_t file_addr) {
1155   Symtab *symtab = GetSymtab();
1156   if (symtab) {
1157     Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
1158     if (symbol) {
1159       if (symbol->ValueIsAddress()) {
1160         SectionSP section_sp(symbol->GetAddressRef().GetSection());
1161         if (section_sp) {
1162           const lldb::SectionType section_type = section_sp->GetType();
1163           switch (section_type) {
1164           case eSectionTypeInvalid:
1165             return eAddressClassUnknown;
1166 
1167           case eSectionTypeCode:
1168             if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
1169               // For ARM we have a bit in the n_desc field of the symbol
1170               // that tells us ARM/Thumb which is bit 0x0008.
1171               if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
1172                 return eAddressClassCodeAlternateISA;
1173             }
1174             return eAddressClassCode;
1175 
1176           case eSectionTypeContainer:
1177             return eAddressClassUnknown;
1178 
1179           case eSectionTypeData:
1180           case eSectionTypeDataCString:
1181           case eSectionTypeDataCStringPointers:
1182           case eSectionTypeDataSymbolAddress:
1183           case eSectionTypeData4:
1184           case eSectionTypeData8:
1185           case eSectionTypeData16:
1186           case eSectionTypeDataPointers:
1187           case eSectionTypeZeroFill:
1188           case eSectionTypeDataObjCMessageRefs:
1189           case eSectionTypeDataObjCCFStrings:
1190           case eSectionTypeGoSymtab:
1191             return eAddressClassData;
1192 
1193           case eSectionTypeDebug:
1194           case eSectionTypeDWARFDebugAbbrev:
1195           case eSectionTypeDWARFDebugAddr:
1196           case eSectionTypeDWARFDebugAranges:
1197           case eSectionTypeDWARFDebugFrame:
1198           case eSectionTypeDWARFDebugInfo:
1199           case eSectionTypeDWARFDebugLine:
1200           case eSectionTypeDWARFDebugLoc:
1201           case eSectionTypeDWARFDebugMacInfo:
1202           case eSectionTypeDWARFDebugMacro:
1203           case eSectionTypeDWARFDebugPubNames:
1204           case eSectionTypeDWARFDebugPubTypes:
1205           case eSectionTypeDWARFDebugRanges:
1206           case eSectionTypeDWARFDebugStr:
1207           case eSectionTypeDWARFDebugStrOffsets:
1208           case eSectionTypeDWARFAppleNames:
1209           case eSectionTypeDWARFAppleTypes:
1210           case eSectionTypeDWARFAppleNamespaces:
1211           case eSectionTypeDWARFAppleObjC:
1212             return eAddressClassDebug;
1213 
1214           case eSectionTypeEHFrame:
1215           case eSectionTypeARMexidx:
1216           case eSectionTypeARMextab:
1217           case eSectionTypeCompactUnwind:
1218             return eAddressClassRuntime;
1219 
1220           case eSectionTypeAbsoluteAddress:
1221           case eSectionTypeELFSymbolTable:
1222           case eSectionTypeELFDynamicSymbols:
1223           case eSectionTypeELFRelocationEntries:
1224           case eSectionTypeELFDynamicLinkInfo:
1225           case eSectionTypeOther:
1226             return eAddressClassUnknown;
1227           }
1228         }
1229       }
1230 
1231       const SymbolType symbol_type = symbol->GetType();
1232       switch (symbol_type) {
1233       case eSymbolTypeAny:
1234         return eAddressClassUnknown;
1235       case eSymbolTypeAbsolute:
1236         return eAddressClassUnknown;
1237 
1238       case eSymbolTypeCode:
1239       case eSymbolTypeTrampoline:
1240       case eSymbolTypeResolver:
1241         if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
1242           // For ARM we have a bit in the n_desc field of the symbol
1243           // that tells us ARM/Thumb which is bit 0x0008.
1244           if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
1245             return eAddressClassCodeAlternateISA;
1246         }
1247         return eAddressClassCode;
1248 
1249       case eSymbolTypeData:
1250         return eAddressClassData;
1251       case eSymbolTypeRuntime:
1252         return eAddressClassRuntime;
1253       case eSymbolTypeException:
1254         return eAddressClassRuntime;
1255       case eSymbolTypeSourceFile:
1256         return eAddressClassDebug;
1257       case eSymbolTypeHeaderFile:
1258         return eAddressClassDebug;
1259       case eSymbolTypeObjectFile:
1260         return eAddressClassDebug;
1261       case eSymbolTypeCommonBlock:
1262         return eAddressClassDebug;
1263       case eSymbolTypeBlock:
1264         return eAddressClassDebug;
1265       case eSymbolTypeLocal:
1266         return eAddressClassData;
1267       case eSymbolTypeParam:
1268         return eAddressClassData;
1269       case eSymbolTypeVariable:
1270         return eAddressClassData;
1271       case eSymbolTypeVariableType:
1272         return eAddressClassDebug;
1273       case eSymbolTypeLineEntry:
1274         return eAddressClassDebug;
1275       case eSymbolTypeLineHeader:
1276         return eAddressClassDebug;
1277       case eSymbolTypeScopeBegin:
1278         return eAddressClassDebug;
1279       case eSymbolTypeScopeEnd:
1280         return eAddressClassDebug;
1281       case eSymbolTypeAdditional:
1282         return eAddressClassUnknown;
1283       case eSymbolTypeCompiler:
1284         return eAddressClassDebug;
1285       case eSymbolTypeInstrumentation:
1286         return eAddressClassDebug;
1287       case eSymbolTypeUndefined:
1288         return eAddressClassUnknown;
1289       case eSymbolTypeObjCClass:
1290         return eAddressClassRuntime;
1291       case eSymbolTypeObjCMetaClass:
1292         return eAddressClassRuntime;
1293       case eSymbolTypeObjCIVar:
1294         return eAddressClassRuntime;
1295       case eSymbolTypeReExported:
1296         return eAddressClassRuntime;
1297       }
1298     }
1299   }
1300   return eAddressClassUnknown;
1301 }
1302 
1303 Symtab *ObjectFileMachO::GetSymtab() {
1304   ModuleSP module_sp(GetModule());
1305   if (module_sp) {
1306     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1307     if (m_symtab_ap.get() == NULL) {
1308       m_symtab_ap.reset(new Symtab(this));
1309       std::lock_guard<std::recursive_mutex> symtab_guard(
1310           m_symtab_ap->GetMutex());
1311       ParseSymtab();
1312       m_symtab_ap->Finalize();
1313     }
1314   }
1315   return m_symtab_ap.get();
1316 }
1317 
1318 bool ObjectFileMachO::IsStripped() {
1319   if (m_dysymtab.cmd == 0) {
1320     ModuleSP module_sp(GetModule());
1321     if (module_sp) {
1322       lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1323       for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1324         const lldb::offset_t load_cmd_offset = offset;
1325 
1326         load_command lc;
1327         if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
1328           break;
1329         if (lc.cmd == LC_DYSYMTAB) {
1330           m_dysymtab.cmd = lc.cmd;
1331           m_dysymtab.cmdsize = lc.cmdsize;
1332           if (m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1333                             (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) ==
1334               NULL) {
1335             // Clear m_dysymtab if we were unable to read all items from the
1336             // load command
1337             ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
1338           }
1339         }
1340         offset = load_cmd_offset + lc.cmdsize;
1341       }
1342     }
1343   }
1344   if (m_dysymtab.cmd)
1345     return m_dysymtab.nlocalsym <= 1;
1346   return false;
1347 }
1348 
1349 void ObjectFileMachO::CreateSections(SectionList &unified_section_list) {
1350   if (!m_sections_ap.get()) {
1351     m_sections_ap.reset(new SectionList());
1352 
1353     const bool is_dsym = (m_header.filetype == MH_DSYM);
1354     lldb::user_id_t segID = 0;
1355     lldb::user_id_t sectID = 0;
1356     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1357     uint32_t i;
1358     const bool is_core = GetType() == eTypeCoreFile;
1359     // bool dump_sections = false;
1360     ModuleSP module_sp(GetModule());
1361     // First look up any LC_ENCRYPTION_INFO load commands
1362     typedef RangeArray<uint32_t, uint32_t, 8> EncryptedFileRanges;
1363     EncryptedFileRanges encrypted_file_ranges;
1364     encryption_info_command encryption_cmd;
1365     for (i = 0; i < m_header.ncmds; ++i) {
1366       const lldb::offset_t load_cmd_offset = offset;
1367       if (m_data.GetU32(&offset, &encryption_cmd, 2) == NULL)
1368         break;
1369 
1370       // LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for
1371       // the 3 fields we care about, so treat them the same.
1372       if (encryption_cmd.cmd == LC_ENCRYPTION_INFO ||
1373           encryption_cmd.cmd == LC_ENCRYPTION_INFO_64) {
1374         if (m_data.GetU32(&offset, &encryption_cmd.cryptoff, 3)) {
1375           if (encryption_cmd.cryptid != 0) {
1376             EncryptedFileRanges::Entry entry;
1377             entry.SetRangeBase(encryption_cmd.cryptoff);
1378             entry.SetByteSize(encryption_cmd.cryptsize);
1379             encrypted_file_ranges.Append(entry);
1380           }
1381         }
1382       }
1383       offset = load_cmd_offset + encryption_cmd.cmdsize;
1384     }
1385 
1386     bool section_file_addresses_changed = false;
1387 
1388     offset = MachHeaderSizeFromMagic(m_header.magic);
1389 
1390     struct segment_command_64 load_cmd;
1391     for (i = 0; i < m_header.ncmds; ++i) {
1392       const lldb::offset_t load_cmd_offset = offset;
1393       if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
1394         break;
1395 
1396       if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64) {
1397         if (m_data.GetU8(&offset, (uint8_t *)load_cmd.segname, 16)) {
1398           bool add_section = true;
1399           bool add_to_unified = true;
1400           ConstString const_segname(load_cmd.segname,
1401                                     std::min<size_t>(strlen(load_cmd.segname),
1402                                                      sizeof(load_cmd.segname)));
1403 
1404           SectionSP unified_section_sp(
1405               unified_section_list.FindSectionByName(const_segname));
1406           if (is_dsym && unified_section_sp) {
1407             if (const_segname == GetSegmentNameLINKEDIT()) {
1408               // We need to keep the __LINKEDIT segment private to this object
1409               // file only
1410               add_to_unified = false;
1411             } else {
1412               // This is the dSYM file and this section has already been created
1413               // by
1414               // the object file, no need to create it.
1415               add_section = false;
1416             }
1417           }
1418           load_cmd.vmaddr = m_data.GetAddress(&offset);
1419           load_cmd.vmsize = m_data.GetAddress(&offset);
1420           load_cmd.fileoff = m_data.GetAddress(&offset);
1421           load_cmd.filesize = m_data.GetAddress(&offset);
1422           if (m_length != 0 && load_cmd.filesize != 0) {
1423             if (load_cmd.fileoff > m_length) {
1424               // We have a load command that says it extends past the end of the
1425               // file.  This is likely
1426               // a corrupt file.  We don't have any way to return an error
1427               // condition here (this method
1428               // was likely invoked from something like
1429               // ObjectFile::GetSectionList()) -- all we can do
1430               // is null out the SectionList vector and if a process has been
1431               // set up, dump a message
1432               // to stdout.  The most common case here is core file debugging
1433               // with a truncated file.
1434               const char *lc_segment_name = load_cmd.cmd == LC_SEGMENT_64
1435                                                 ? "LC_SEGMENT_64"
1436                                                 : "LC_SEGMENT";
1437               module_sp->ReportWarning(
1438                   "load command %u %s has a fileoff (0x%" PRIx64
1439                   ") that extends beyond the end of the file (0x%" PRIx64
1440                   "), ignoring this section",
1441                   i, lc_segment_name, load_cmd.fileoff, m_length);
1442 
1443               load_cmd.fileoff = 0;
1444               load_cmd.filesize = 0;
1445             }
1446 
1447             if (load_cmd.fileoff + load_cmd.filesize > m_length) {
1448               // We have a load command that says it extends past the end of the
1449               // file.  This is likely
1450               // a corrupt file.  We don't have any way to return an error
1451               // condition here (this method
1452               // was likely invoked from something like
1453               // ObjectFile::GetSectionList()) -- all we can do
1454               // is null out the SectionList vector and if a process has been
1455               // set up, dump a message
1456               // to stdout.  The most common case here is core file debugging
1457               // with a truncated file.
1458               const char *lc_segment_name = load_cmd.cmd == LC_SEGMENT_64
1459                                                 ? "LC_SEGMENT_64"
1460                                                 : "LC_SEGMENT";
1461               GetModule()->ReportWarning(
1462                   "load command %u %s has a fileoff + filesize (0x%" PRIx64
1463                   ") that extends beyond the end of the file (0x%" PRIx64
1464                   "), the segment will be truncated to match",
1465                   i, lc_segment_name, load_cmd.fileoff + load_cmd.filesize,
1466                   m_length);
1467 
1468               // Tuncase the length
1469               load_cmd.filesize = m_length - load_cmd.fileoff;
1470             }
1471           }
1472           if (m_data.GetU32(&offset, &load_cmd.maxprot, 4)) {
1473             uint32_t segment_permissions = 0;
1474             if (load_cmd.initprot & VM_PROT_READ)
1475               segment_permissions |= ePermissionsReadable;
1476             if (load_cmd.initprot & VM_PROT_WRITE)
1477               segment_permissions |= ePermissionsWritable;
1478             if (load_cmd.initprot & VM_PROT_EXECUTE)
1479               segment_permissions |= ePermissionsExecutable;
1480 
1481             const bool segment_is_encrypted =
1482                 (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
1483 
1484             // Keep a list of mach segments around in case we need to
1485             // get at data that isn't stored in the abstracted Sections.
1486             m_mach_segments.push_back(load_cmd);
1487 
1488             // Use a segment ID of the segment index shifted left by 8 so they
1489             // never conflict with any of the sections.
1490             SectionSP segment_sp;
1491             if (add_section && (const_segname || is_core)) {
1492               segment_sp.reset(new Section(
1493                   module_sp,     // Module to which this section belongs
1494                   this,          // Object file to which this sections belongs
1495                   ++segID << 8,  // Section ID is the 1 based segment index
1496                                  // shifted right by 8 bits as not to collide
1497                                  // with any of the 256 section IDs that are
1498                                  // possible
1499                   const_segname, // Name of this section
1500                   eSectionTypeContainer, // This section is a container of other
1501                                          // sections.
1502                   load_cmd.vmaddr,   // File VM address == addresses as they are
1503                                      // found in the object file
1504                   load_cmd.vmsize,   // VM size in bytes of this section
1505                   load_cmd.fileoff,  // Offset to the data for this section in
1506                                      // the file
1507                   load_cmd.filesize, // Size in bytes of this section as found
1508                                      // in the file
1509                   0,                 // Segments have no alignment information
1510                   load_cmd.flags));  // Flags for this section
1511 
1512               segment_sp->SetIsEncrypted(segment_is_encrypted);
1513               m_sections_ap->AddSection(segment_sp);
1514               segment_sp->SetPermissions(segment_permissions);
1515               if (add_to_unified)
1516                 unified_section_list.AddSection(segment_sp);
1517             } else if (unified_section_sp) {
1518               if (is_dsym &&
1519                   unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
1520                 // Check to see if the module was read from memory?
1521                 if (module_sp->GetObjectFile()->GetHeaderAddress().IsValid()) {
1522                   // We have a module that is in memory and needs to have its
1523                   // file address adjusted. We need to do this because when we
1524                   // load a file from memory, its addresses will be slid
1525                   // already,
1526                   // yet the addresses in the new symbol file will still be
1527                   // unslid.
1528                   // Since everything is stored as section offset, this
1529                   // shouldn't
1530                   // cause any problems.
1531 
1532                   // Make sure we've parsed the symbol table from the
1533                   // ObjectFile before we go around changing its Sections.
1534                   module_sp->GetObjectFile()->GetSymtab();
1535                   // eh_frame would present the same problems but we parse that
1536                   // on
1537                   // a per-function basis as-needed so it's more difficult to
1538                   // remove its use of the Sections.  Realistically, the
1539                   // environments
1540                   // where this code path will be taken will not have eh_frame
1541                   // sections.
1542 
1543                   unified_section_sp->SetFileAddress(load_cmd.vmaddr);
1544 
1545                   // Notify the module that the section addresses have been
1546                   // changed once
1547                   // we're done so any file-address caches can be updated.
1548                   section_file_addresses_changed = true;
1549                 }
1550               }
1551               m_sections_ap->AddSection(unified_section_sp);
1552             }
1553 
1554             struct section_64 sect64;
1555             ::memset(&sect64, 0, sizeof(sect64));
1556             // Push a section into our mach sections for the section at
1557             // index zero (NO_SECT) if we don't have any mach sections yet...
1558             if (m_mach_sections.empty())
1559               m_mach_sections.push_back(sect64);
1560             uint32_t segment_sect_idx;
1561             const lldb::user_id_t first_segment_sectID = sectID + 1;
1562 
1563             const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
1564             for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
1565                  ++segment_sect_idx) {
1566               if (m_data.GetU8(&offset, (uint8_t *)sect64.sectname,
1567                                sizeof(sect64.sectname)) == NULL)
1568                 break;
1569               if (m_data.GetU8(&offset, (uint8_t *)sect64.segname,
1570                                sizeof(sect64.segname)) == NULL)
1571                 break;
1572               sect64.addr = m_data.GetAddress(&offset);
1573               sect64.size = m_data.GetAddress(&offset);
1574 
1575               if (m_data.GetU32(&offset, &sect64.offset, num_u32s) == NULL)
1576                 break;
1577 
1578               // Keep a list of mach sections around in case we need to
1579               // get at data that isn't stored in the abstracted Sections.
1580               m_mach_sections.push_back(sect64);
1581 
1582               if (add_section) {
1583                 ConstString section_name(
1584                     sect64.sectname, std::min<size_t>(strlen(sect64.sectname),
1585                                                       sizeof(sect64.sectname)));
1586                 if (!const_segname) {
1587                   // We have a segment with no name so we need to conjure up
1588                   // segments that correspond to the section's segname if there
1589                   // isn't already such a section. If there is such a section,
1590                   // we resize the section so that it spans all sections.
1591                   // We also mark these sections as fake so address matches
1592                   // don't
1593                   // hit if they land in the gaps between the child sections.
1594                   const_segname.SetTrimmedCStringWithLength(
1595                       sect64.segname, sizeof(sect64.segname));
1596                   segment_sp =
1597                       unified_section_list.FindSectionByName(const_segname);
1598                   if (segment_sp.get()) {
1599                     Section *segment = segment_sp.get();
1600                     // Grow the section size as needed.
1601                     const lldb::addr_t sect64_min_addr = sect64.addr;
1602                     const lldb::addr_t sect64_max_addr =
1603                         sect64_min_addr + sect64.size;
1604                     const lldb::addr_t curr_seg_byte_size =
1605                         segment->GetByteSize();
1606                     const lldb::addr_t curr_seg_min_addr =
1607                         segment->GetFileAddress();
1608                     const lldb::addr_t curr_seg_max_addr =
1609                         curr_seg_min_addr + curr_seg_byte_size;
1610                     if (sect64_min_addr >= curr_seg_min_addr) {
1611                       const lldb::addr_t new_seg_byte_size =
1612                           sect64_max_addr - curr_seg_min_addr;
1613                       // Only grow the section size if needed
1614                       if (new_seg_byte_size > curr_seg_byte_size)
1615                         segment->SetByteSize(new_seg_byte_size);
1616                     } else {
1617                       // We need to change the base address of the segment and
1618                       // adjust the child section offsets for all existing
1619                       // children.
1620                       const lldb::addr_t slide_amount =
1621                           sect64_min_addr - curr_seg_min_addr;
1622                       segment->Slide(slide_amount, false);
1623                       segment->GetChildren().Slide(-slide_amount, false);
1624                       segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
1625                     }
1626 
1627                     // Grow the section size as needed.
1628                     if (sect64.offset) {
1629                       const lldb::addr_t segment_min_file_offset =
1630                           segment->GetFileOffset();
1631                       const lldb::addr_t segment_max_file_offset =
1632                           segment_min_file_offset + segment->GetFileSize();
1633 
1634                       const lldb::addr_t section_min_file_offset =
1635                           sect64.offset;
1636                       const lldb::addr_t section_max_file_offset =
1637                           section_min_file_offset + sect64.size;
1638                       const lldb::addr_t new_file_offset = std::min(
1639                           section_min_file_offset, segment_min_file_offset);
1640                       const lldb::addr_t new_file_size =
1641                           std::max(section_max_file_offset,
1642                                    segment_max_file_offset) -
1643                           new_file_offset;
1644                       segment->SetFileOffset(new_file_offset);
1645                       segment->SetFileSize(new_file_size);
1646                     }
1647                   } else {
1648                     // Create a fake section for the section's named segment
1649                     segment_sp.reset(new Section(
1650                         segment_sp, // Parent section
1651                         module_sp,  // Module to which this section belongs
1652                         this,       // Object file to which this section belongs
1653                         ++segID << 8, // Section ID is the 1 based segment index
1654                                       // shifted right by 8 bits as not to
1655                                       // collide with any of the 256 section IDs
1656                                       // that are possible
1657                         const_segname,         // Name of this section
1658                         eSectionTypeContainer, // This section is a container of
1659                                                // other sections.
1660                         sect64.addr, // File VM address == addresses as they are
1661                                      // found in the object file
1662                         sect64.size, // VM size in bytes of this section
1663                         sect64.offset, // Offset to the data for this section in
1664                                        // the file
1665                         sect64.offset ? sect64.size : 0, // Size in bytes of
1666                                                          // this section as
1667                                                          // found in the file
1668                         sect64.align,
1669                         load_cmd.flags)); // Flags for this section
1670                     segment_sp->SetIsFake(true);
1671                     segment_sp->SetPermissions(segment_permissions);
1672                     m_sections_ap->AddSection(segment_sp);
1673                     if (add_to_unified)
1674                       unified_section_list.AddSection(segment_sp);
1675                     segment_sp->SetIsEncrypted(segment_is_encrypted);
1676                   }
1677                 }
1678                 assert(segment_sp.get());
1679 
1680                 lldb::SectionType sect_type = eSectionTypeOther;
1681 
1682                 if (sect64.flags &
1683                     (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS))
1684                   sect_type = eSectionTypeCode;
1685                 else {
1686                   uint32_t mach_sect_type = sect64.flags & SECTION_TYPE;
1687                   static ConstString g_sect_name_objc_data("__objc_data");
1688                   static ConstString g_sect_name_objc_msgrefs("__objc_msgrefs");
1689                   static ConstString g_sect_name_objc_selrefs("__objc_selrefs");
1690                   static ConstString g_sect_name_objc_classrefs(
1691                       "__objc_classrefs");
1692                   static ConstString g_sect_name_objc_superrefs(
1693                       "__objc_superrefs");
1694                   static ConstString g_sect_name_objc_const("__objc_const");
1695                   static ConstString g_sect_name_objc_classlist(
1696                       "__objc_classlist");
1697                   static ConstString g_sect_name_cfstring("__cfstring");
1698 
1699                   static ConstString g_sect_name_dwarf_debug_abbrev(
1700                       "__debug_abbrev");
1701                   static ConstString g_sect_name_dwarf_debug_aranges(
1702                       "__debug_aranges");
1703                   static ConstString g_sect_name_dwarf_debug_frame(
1704                       "__debug_frame");
1705                   static ConstString g_sect_name_dwarf_debug_info(
1706                       "__debug_info");
1707                   static ConstString g_sect_name_dwarf_debug_line(
1708                       "__debug_line");
1709                   static ConstString g_sect_name_dwarf_debug_loc("__debug_loc");
1710                   static ConstString g_sect_name_dwarf_debug_macinfo(
1711                       "__debug_macinfo");
1712                   static ConstString g_sect_name_dwarf_debug_pubnames(
1713                       "__debug_pubnames");
1714                   static ConstString g_sect_name_dwarf_debug_pubtypes(
1715                       "__debug_pubtypes");
1716                   static ConstString g_sect_name_dwarf_debug_ranges(
1717                       "__debug_ranges");
1718                   static ConstString g_sect_name_dwarf_debug_str("__debug_str");
1719                   static ConstString g_sect_name_dwarf_apple_names(
1720                       "__apple_names");
1721                   static ConstString g_sect_name_dwarf_apple_types(
1722                       "__apple_types");
1723                   static ConstString g_sect_name_dwarf_apple_namespaces(
1724                       "__apple_namespac");
1725                   static ConstString g_sect_name_dwarf_apple_objc(
1726                       "__apple_objc");
1727                   static ConstString g_sect_name_eh_frame("__eh_frame");
1728                   static ConstString g_sect_name_compact_unwind(
1729                       "__unwind_info");
1730                   static ConstString g_sect_name_text("__text");
1731                   static ConstString g_sect_name_data("__data");
1732                   static ConstString g_sect_name_go_symtab("__gosymtab");
1733 
1734                   if (section_name == g_sect_name_dwarf_debug_abbrev)
1735                     sect_type = eSectionTypeDWARFDebugAbbrev;
1736                   else if (section_name == g_sect_name_dwarf_debug_aranges)
1737                     sect_type = eSectionTypeDWARFDebugAranges;
1738                   else if (section_name == g_sect_name_dwarf_debug_frame)
1739                     sect_type = eSectionTypeDWARFDebugFrame;
1740                   else if (section_name == g_sect_name_dwarf_debug_info)
1741                     sect_type = eSectionTypeDWARFDebugInfo;
1742                   else if (section_name == g_sect_name_dwarf_debug_line)
1743                     sect_type = eSectionTypeDWARFDebugLine;
1744                   else if (section_name == g_sect_name_dwarf_debug_loc)
1745                     sect_type = eSectionTypeDWARFDebugLoc;
1746                   else if (section_name == g_sect_name_dwarf_debug_macinfo)
1747                     sect_type = eSectionTypeDWARFDebugMacInfo;
1748                   else if (section_name == g_sect_name_dwarf_debug_pubnames)
1749                     sect_type = eSectionTypeDWARFDebugPubNames;
1750                   else if (section_name == g_sect_name_dwarf_debug_pubtypes)
1751                     sect_type = eSectionTypeDWARFDebugPubTypes;
1752                   else if (section_name == g_sect_name_dwarf_debug_ranges)
1753                     sect_type = eSectionTypeDWARFDebugRanges;
1754                   else if (section_name == g_sect_name_dwarf_debug_str)
1755                     sect_type = eSectionTypeDWARFDebugStr;
1756                   else if (section_name == g_sect_name_dwarf_apple_names)
1757                     sect_type = eSectionTypeDWARFAppleNames;
1758                   else if (section_name == g_sect_name_dwarf_apple_types)
1759                     sect_type = eSectionTypeDWARFAppleTypes;
1760                   else if (section_name == g_sect_name_dwarf_apple_namespaces)
1761                     sect_type = eSectionTypeDWARFAppleNamespaces;
1762                   else if (section_name == g_sect_name_dwarf_apple_objc)
1763                     sect_type = eSectionTypeDWARFAppleObjC;
1764                   else if (section_name == g_sect_name_objc_selrefs)
1765                     sect_type = eSectionTypeDataCStringPointers;
1766                   else if (section_name == g_sect_name_objc_msgrefs)
1767                     sect_type = eSectionTypeDataObjCMessageRefs;
1768                   else if (section_name == g_sect_name_eh_frame)
1769                     sect_type = eSectionTypeEHFrame;
1770                   else if (section_name == g_sect_name_compact_unwind)
1771                     sect_type = eSectionTypeCompactUnwind;
1772                   else if (section_name == g_sect_name_cfstring)
1773                     sect_type = eSectionTypeDataObjCCFStrings;
1774                   else if (section_name == g_sect_name_go_symtab)
1775                     sect_type = eSectionTypeGoSymtab;
1776                   else if (section_name == g_sect_name_objc_data ||
1777                            section_name == g_sect_name_objc_classrefs ||
1778                            section_name == g_sect_name_objc_superrefs ||
1779                            section_name == g_sect_name_objc_const ||
1780                            section_name == g_sect_name_objc_classlist) {
1781                     sect_type = eSectionTypeDataPointers;
1782                   }
1783 
1784                   if (sect_type == eSectionTypeOther) {
1785                     switch (mach_sect_type) {
1786                     // TODO: categorize sections by other flags for regular
1787                     // sections
1788                     case S_REGULAR:
1789                       if (section_name == g_sect_name_text)
1790                         sect_type = eSectionTypeCode;
1791                       else if (section_name == g_sect_name_data)
1792                         sect_type = eSectionTypeData;
1793                       else
1794                         sect_type = eSectionTypeOther;
1795                       break;
1796                     case S_ZEROFILL:
1797                       sect_type = eSectionTypeZeroFill;
1798                       break;
1799                     case S_CSTRING_LITERALS:
1800                       sect_type = eSectionTypeDataCString;
1801                       break; // section with only literal C strings
1802                     case S_4BYTE_LITERALS:
1803                       sect_type = eSectionTypeData4;
1804                       break; // section with only 4 byte literals
1805                     case S_8BYTE_LITERALS:
1806                       sect_type = eSectionTypeData8;
1807                       break; // section with only 8 byte literals
1808                     case S_LITERAL_POINTERS:
1809                       sect_type = eSectionTypeDataPointers;
1810                       break; // section with only pointers to literals
1811                     case S_NON_LAZY_SYMBOL_POINTERS:
1812                       sect_type = eSectionTypeDataPointers;
1813                       break; // section with only non-lazy symbol pointers
1814                     case S_LAZY_SYMBOL_POINTERS:
1815                       sect_type = eSectionTypeDataPointers;
1816                       break; // section with only lazy symbol pointers
1817                     case S_SYMBOL_STUBS:
1818                       sect_type = eSectionTypeCode;
1819                       break; // section with only symbol stubs, byte size of
1820                              // stub in the reserved2 field
1821                     case S_MOD_INIT_FUNC_POINTERS:
1822                       sect_type = eSectionTypeDataPointers;
1823                       break; // section with only function pointers for
1824                              // initialization
1825                     case S_MOD_TERM_FUNC_POINTERS:
1826                       sect_type = eSectionTypeDataPointers;
1827                       break; // section with only function pointers for
1828                              // termination
1829                     case S_COALESCED:
1830                       sect_type = eSectionTypeOther;
1831                       break;
1832                     case S_GB_ZEROFILL:
1833                       sect_type = eSectionTypeZeroFill;
1834                       break;
1835                     case S_INTERPOSING:
1836                       sect_type = eSectionTypeCode;
1837                       break; // section with only pairs of function pointers for
1838                              // interposing
1839                     case S_16BYTE_LITERALS:
1840                       sect_type = eSectionTypeData16;
1841                       break; // section with only 16 byte literals
1842                     case S_DTRACE_DOF:
1843                       sect_type = eSectionTypeDebug;
1844                       break;
1845                     case S_LAZY_DYLIB_SYMBOL_POINTERS:
1846                       sect_type = eSectionTypeDataPointers;
1847                       break;
1848                     default:
1849                       break;
1850                     }
1851                   }
1852                 }
1853 
1854                 SectionSP section_sp(new Section(
1855                     segment_sp, module_sp, this, ++sectID, section_name,
1856                     sect_type, sect64.addr - segment_sp->GetFileAddress(),
1857                     sect64.size, sect64.offset,
1858                     sect64.offset == 0 ? 0 : sect64.size, sect64.align,
1859                     sect64.flags));
1860                 // Set the section to be encrypted to match the segment
1861 
1862                 bool section_is_encrypted = false;
1863                 if (!segment_is_encrypted && load_cmd.filesize != 0)
1864                   section_is_encrypted =
1865                       encrypted_file_ranges.FindEntryThatContains(
1866                           sect64.offset) != NULL;
1867 
1868                 section_sp->SetIsEncrypted(segment_is_encrypted ||
1869                                            section_is_encrypted);
1870                 section_sp->SetPermissions(segment_permissions);
1871                 segment_sp->GetChildren().AddSection(section_sp);
1872 
1873                 if (segment_sp->IsFake()) {
1874                   segment_sp.reset();
1875                   const_segname.Clear();
1876                 }
1877               }
1878             }
1879             if (segment_sp && is_dsym) {
1880               if (first_segment_sectID <= sectID) {
1881                 lldb::user_id_t sect_uid;
1882                 for (sect_uid = first_segment_sectID; sect_uid <= sectID;
1883                      ++sect_uid) {
1884                   SectionSP curr_section_sp(
1885                       segment_sp->GetChildren().FindSectionByID(sect_uid));
1886                   SectionSP next_section_sp;
1887                   if (sect_uid + 1 <= sectID)
1888                     next_section_sp =
1889                         segment_sp->GetChildren().FindSectionByID(sect_uid + 1);
1890 
1891                   if (curr_section_sp.get()) {
1892                     if (curr_section_sp->GetByteSize() == 0) {
1893                       if (next_section_sp.get() != NULL)
1894                         curr_section_sp->SetByteSize(
1895                             next_section_sp->GetFileAddress() -
1896                             curr_section_sp->GetFileAddress());
1897                       else
1898                         curr_section_sp->SetByteSize(load_cmd.vmsize);
1899                     }
1900                   }
1901                 }
1902               }
1903             }
1904           }
1905         }
1906       } else if (load_cmd.cmd == LC_DYSYMTAB) {
1907         m_dysymtab.cmd = load_cmd.cmd;
1908         m_dysymtab.cmdsize = load_cmd.cmdsize;
1909         m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1910                       (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1911       }
1912 
1913       offset = load_cmd_offset + load_cmd.cmdsize;
1914     }
1915 
1916     if (section_file_addresses_changed && module_sp.get()) {
1917       module_sp->SectionFileAddressesChanged();
1918     }
1919   }
1920 }
1921 
1922 class MachSymtabSectionInfo {
1923 public:
1924   MachSymtabSectionInfo(SectionList *section_list)
1925       : m_section_list(section_list), m_section_infos() {
1926     // Get the number of sections down to a depth of 1 to include
1927     // all segments and their sections, but no other sections that
1928     // may be added for debug map or
1929     m_section_infos.resize(section_list->GetNumSections(1));
1930   }
1931 
1932   SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
1933     if (n_sect == 0)
1934       return SectionSP();
1935     if (n_sect < m_section_infos.size()) {
1936       if (!m_section_infos[n_sect].section_sp) {
1937         SectionSP section_sp(m_section_list->FindSectionByID(n_sect));
1938         m_section_infos[n_sect].section_sp = section_sp;
1939         if (section_sp) {
1940           m_section_infos[n_sect].vm_range.SetBaseAddress(
1941               section_sp->GetFileAddress());
1942           m_section_infos[n_sect].vm_range.SetByteSize(
1943               section_sp->GetByteSize());
1944         } else {
1945           Host::SystemLog(Host::eSystemLogError,
1946                           "error: unable to find section for section %u\n",
1947                           n_sect);
1948         }
1949       }
1950       if (m_section_infos[n_sect].vm_range.Contains(file_addr)) {
1951         // Symbol is in section.
1952         return m_section_infos[n_sect].section_sp;
1953       } else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
1954                  m_section_infos[n_sect].vm_range.GetBaseAddress() ==
1955                      file_addr) {
1956         // Symbol is in section with zero size, but has the same start
1957         // address as the section. This can happen with linker symbols
1958         // (symbols that start with the letter 'l' or 'L'.
1959         return m_section_infos[n_sect].section_sp;
1960       }
1961     }
1962     return m_section_list->FindSectionContainingFileAddress(file_addr);
1963   }
1964 
1965 protected:
1966   struct SectionInfo {
1967     SectionInfo() : vm_range(), section_sp() {}
1968 
1969     VMRange vm_range;
1970     SectionSP section_sp;
1971   };
1972   SectionList *m_section_list;
1973   std::vector<SectionInfo> m_section_infos;
1974 };
1975 
1976 struct TrieEntry {
1977   TrieEntry()
1978       : name(), address(LLDB_INVALID_ADDRESS), flags(0), other(0),
1979         import_name() {}
1980 
1981   void Clear() {
1982     name.Clear();
1983     address = LLDB_INVALID_ADDRESS;
1984     flags = 0;
1985     other = 0;
1986     import_name.Clear();
1987   }
1988 
1989   void Dump() const {
1990     printf("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"",
1991            static_cast<unsigned long long>(address),
1992            static_cast<unsigned long long>(flags),
1993            static_cast<unsigned long long>(other), name.GetCString());
1994     if (import_name)
1995       printf(" -> \"%s\"\n", import_name.GetCString());
1996     else
1997       printf("\n");
1998   }
1999   ConstString name;
2000   uint64_t address;
2001   uint64_t flags;
2002   uint64_t other;
2003   ConstString import_name;
2004 };
2005 
2006 struct TrieEntryWithOffset {
2007   lldb::offset_t nodeOffset;
2008   TrieEntry entry;
2009 
2010   TrieEntryWithOffset(lldb::offset_t offset) : nodeOffset(offset), entry() {}
2011 
2012   void Dump(uint32_t idx) const {
2013     printf("[%3u] 0x%16.16llx: ", idx,
2014            static_cast<unsigned long long>(nodeOffset));
2015     entry.Dump();
2016   }
2017 
2018   bool operator<(const TrieEntryWithOffset &other) const {
2019     return (nodeOffset < other.nodeOffset);
2020   }
2021 };
2022 
2023 static bool ParseTrieEntries(DataExtractor &data, lldb::offset_t offset,
2024                              const bool is_arm,
2025                              std::vector<llvm::StringRef> &nameSlices,
2026                              std::set<lldb::addr_t> &resolver_addresses,
2027                              std::vector<TrieEntryWithOffset> &output) {
2028   if (!data.ValidOffset(offset))
2029     return true;
2030 
2031   const uint64_t terminalSize = data.GetULEB128(&offset);
2032   lldb::offset_t children_offset = offset + terminalSize;
2033   if (terminalSize != 0) {
2034     TrieEntryWithOffset e(offset);
2035     e.entry.flags = data.GetULEB128(&offset);
2036     const char *import_name = NULL;
2037     if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
2038       e.entry.address = 0;
2039       e.entry.other = data.GetULEB128(&offset); // dylib ordinal
2040       import_name = data.GetCStr(&offset);
2041     } else {
2042       e.entry.address = data.GetULEB128(&offset);
2043       if (e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2044         e.entry.other = data.GetULEB128(&offset);
2045         uint64_t resolver_addr = e.entry.other;
2046         if (is_arm)
2047           resolver_addr &= THUMB_ADDRESS_BIT_MASK;
2048         resolver_addresses.insert(resolver_addr);
2049       } else
2050         e.entry.other = 0;
2051     }
2052     // Only add symbols that are reexport symbols with a valid import name
2053     if (EXPORT_SYMBOL_FLAGS_REEXPORT & e.entry.flags && import_name &&
2054         import_name[0]) {
2055       std::string name;
2056       if (!nameSlices.empty()) {
2057         for (auto name_slice : nameSlices)
2058           name.append(name_slice.data(), name_slice.size());
2059       }
2060       if (name.size() > 1) {
2061         // Skip the leading '_'
2062         e.entry.name.SetCStringWithLength(name.c_str() + 1, name.size() - 1);
2063       }
2064       if (import_name) {
2065         // Skip the leading '_'
2066         e.entry.import_name.SetCString(import_name + 1);
2067       }
2068       output.push_back(e);
2069     }
2070   }
2071 
2072   const uint8_t childrenCount = data.GetU8(&children_offset);
2073   for (uint8_t i = 0; i < childrenCount; ++i) {
2074     const char *cstr = data.GetCStr(&children_offset);
2075     if (cstr)
2076       nameSlices.push_back(llvm::StringRef(cstr));
2077     else
2078       return false; // Corrupt data
2079     lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset);
2080     if (childNodeOffset) {
2081       if (!ParseTrieEntries(data, childNodeOffset, is_arm, nameSlices,
2082                             resolver_addresses, output)) {
2083         return false;
2084       }
2085     }
2086     nameSlices.pop_back();
2087   }
2088   return true;
2089 }
2090 
2091 // Read the UUID out of a dyld_shared_cache file on-disk.
2092 UUID ObjectFileMachO::GetSharedCacheUUID(FileSpec dyld_shared_cache,
2093                                          const ByteOrder byte_order,
2094                                          const uint32_t addr_byte_size) {
2095   UUID dsc_uuid;
2096   DataBufferSP DscData = DataBufferLLVM::CreateFromFileSpec(
2097       dyld_shared_cache, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
2098   if (!DscData)
2099     return dsc_uuid;
2100   DataExtractor dsc_header_data(DscData, byte_order, addr_byte_size);
2101 
2102   char version_str[7];
2103   lldb::offset_t offset = 0;
2104   memcpy(version_str, dsc_header_data.GetData(&offset, 6), 6);
2105   version_str[6] = '\0';
2106   if (strcmp(version_str, "dyld_v") == 0) {
2107     offset = offsetof(struct lldb_copy_dyld_cache_header_v1, uuid);
2108     uint8_t uuid_bytes[sizeof(uuid_t)];
2109     memcpy(uuid_bytes, dsc_header_data.GetData(&offset, sizeof(uuid_t)),
2110            sizeof(uuid_t));
2111     dsc_uuid.SetBytes(uuid_bytes);
2112   }
2113   return dsc_uuid;
2114 }
2115 
2116 size_t ObjectFileMachO::ParseSymtab() {
2117   Timer scoped_timer(LLVM_PRETTY_FUNCTION,
2118                      "ObjectFileMachO::ParseSymtab () module = %s",
2119                      m_file.GetFilename().AsCString(""));
2120   ModuleSP module_sp(GetModule());
2121   if (!module_sp)
2122     return 0;
2123 
2124   struct symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
2125   struct linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
2126   struct dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2127   typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2128   FunctionStarts function_starts;
2129   lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
2130   uint32_t i;
2131   FileSpecList dylib_files;
2132   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2133   static const llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2134   static const llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
2135   static const llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2136 
2137   for (i = 0; i < m_header.ncmds; ++i) {
2138     const lldb::offset_t cmd_offset = offset;
2139     // Read in the load command and load command size
2140     struct load_command lc;
2141     if (m_data.GetU32(&offset, &lc, 2) == NULL)
2142       break;
2143     // Watch for the symbol table load command
2144     switch (lc.cmd) {
2145     case LC_SYMTAB:
2146       symtab_load_command.cmd = lc.cmd;
2147       symtab_load_command.cmdsize = lc.cmdsize;
2148       // Read in the rest of the symtab load command
2149       if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
2150           0) // fill in symoff, nsyms, stroff, strsize fields
2151         return 0;
2152       if (symtab_load_command.symoff == 0) {
2153         if (log)
2154           module_sp->LogMessage(log, "LC_SYMTAB.symoff == 0");
2155         return 0;
2156       }
2157 
2158       if (symtab_load_command.stroff == 0) {
2159         if (log)
2160           module_sp->LogMessage(log, "LC_SYMTAB.stroff == 0");
2161         return 0;
2162       }
2163 
2164       if (symtab_load_command.nsyms == 0) {
2165         if (log)
2166           module_sp->LogMessage(log, "LC_SYMTAB.nsyms == 0");
2167         return 0;
2168       }
2169 
2170       if (symtab_load_command.strsize == 0) {
2171         if (log)
2172           module_sp->LogMessage(log, "LC_SYMTAB.strsize == 0");
2173         return 0;
2174       }
2175       break;
2176 
2177     case LC_DYLD_INFO:
2178     case LC_DYLD_INFO_ONLY:
2179       if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
2180         dyld_info.cmd = lc.cmd;
2181         dyld_info.cmdsize = lc.cmdsize;
2182       } else {
2183         memset(&dyld_info, 0, sizeof(dyld_info));
2184       }
2185       break;
2186 
2187     case LC_LOAD_DYLIB:
2188     case LC_LOAD_WEAK_DYLIB:
2189     case LC_REEXPORT_DYLIB:
2190     case LC_LOADFVMLIB:
2191     case LC_LOAD_UPWARD_DYLIB: {
2192       uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
2193       const char *path = m_data.PeekCStr(name_offset);
2194       if (path) {
2195         FileSpec file_spec(path, false);
2196         // Strip the path if there is @rpath, @executable, etc so we just use
2197         // the basename
2198         if (path[0] == '@')
2199           file_spec.GetDirectory().Clear();
2200 
2201         if (lc.cmd == LC_REEXPORT_DYLIB) {
2202           m_reexported_dylibs.AppendIfUnique(file_spec);
2203         }
2204 
2205         dylib_files.Append(file_spec);
2206       }
2207     } break;
2208 
2209     case LC_FUNCTION_STARTS:
2210       function_starts_load_command.cmd = lc.cmd;
2211       function_starts_load_command.cmdsize = lc.cmdsize;
2212       if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
2213           NULL) // fill in symoff, nsyms, stroff, strsize fields
2214         memset(&function_starts_load_command, 0,
2215                sizeof(function_starts_load_command));
2216       break;
2217 
2218     default:
2219       break;
2220     }
2221     offset = cmd_offset + lc.cmdsize;
2222   }
2223 
2224   if (symtab_load_command.cmd) {
2225     Symtab *symtab = m_symtab_ap.get();
2226     SectionList *section_list = GetSectionList();
2227     if (section_list == NULL)
2228       return 0;
2229 
2230     const uint32_t addr_byte_size = m_data.GetAddressByteSize();
2231     const ByteOrder byte_order = m_data.GetByteOrder();
2232     bool bit_width_32 = addr_byte_size == 4;
2233     const size_t nlist_byte_size =
2234         bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2235 
2236     DataExtractor nlist_data(NULL, 0, byte_order, addr_byte_size);
2237     DataExtractor strtab_data(NULL, 0, byte_order, addr_byte_size);
2238     DataExtractor function_starts_data(NULL, 0, byte_order, addr_byte_size);
2239     DataExtractor indirect_symbol_index_data(NULL, 0, byte_order,
2240                                              addr_byte_size);
2241     DataExtractor dyld_trie_data(NULL, 0, byte_order, addr_byte_size);
2242 
2243     const addr_t nlist_data_byte_size =
2244         symtab_load_command.nsyms * nlist_byte_size;
2245     const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2246     addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2247 
2248     ProcessSP process_sp(m_process_wp.lock());
2249     Process *process = process_sp.get();
2250 
2251     uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2252 
2253     if (process && m_header.filetype != llvm::MachO::MH_OBJECT) {
2254       Target &target = process->GetTarget();
2255 
2256       memory_module_load_level = target.GetMemoryModuleLoadLevel();
2257 
2258       SectionSP linkedit_section_sp(
2259           section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
2260       // Reading mach file from memory in a process or core file...
2261 
2262       if (linkedit_section_sp) {
2263         addr_t linkedit_load_addr =
2264             linkedit_section_sp->GetLoadBaseAddress(&target);
2265         if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2266           // We might be trying to access the symbol table before the
2267           // __LINKEDIT's load
2268           // address has been set in the target. We can't fail to read the
2269           // symbol table,
2270           // so calculate the right address manually
2271           linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2272               m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2273         }
2274 
2275         const addr_t linkedit_file_offset =
2276             linkedit_section_sp->GetFileOffset();
2277         const addr_t symoff_addr = linkedit_load_addr +
2278                                    symtab_load_command.symoff -
2279                                    linkedit_file_offset;
2280         strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2281                       linkedit_file_offset;
2282 
2283         bool data_was_read = false;
2284 
2285 #if defined(__APPLE__) &&                                                      \
2286     (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2287         if (m_header.flags & 0x80000000u &&
2288             process->GetAddressByteSize() == sizeof(void *)) {
2289           // This mach-o memory file is in the dyld shared cache. If this
2290           // program is not remote and this is iOS, then this process will
2291           // share the same shared cache as the process we are debugging and
2292           // we can read the entire __LINKEDIT from the address space in this
2293           // process. This is a needed optimization that is used for local iOS
2294           // debugging only since all shared libraries in the shared cache do
2295           // not have corresponding files that exist in the file system of the
2296           // device. They have been combined into a single file. This means we
2297           // always have to load these files from memory. All of the symbol and
2298           // string tables from all of the __LINKEDIT sections from the shared
2299           // libraries in the shared cache have been merged into a single large
2300           // symbol and string table. Reading all of this symbol and string
2301           // table
2302           // data across can slow down debug launch times, so we optimize this
2303           // by
2304           // reading the memory for the __LINKEDIT section from this process.
2305 
2306           UUID lldb_shared_cache(GetLLDBSharedCacheUUID());
2307           UUID process_shared_cache(GetProcessSharedCacheUUID(process));
2308           bool use_lldb_cache = true;
2309           if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() &&
2310               lldb_shared_cache != process_shared_cache) {
2311             use_lldb_cache = false;
2312             ModuleSP module_sp(GetModule());
2313             if (module_sp)
2314               module_sp->ReportWarning("shared cache in process does not match "
2315                                        "lldb's own shared cache, startup will "
2316                                        "be slow.");
2317           }
2318 
2319           PlatformSP platform_sp(target.GetPlatform());
2320           if (platform_sp && platform_sp->IsHost() && use_lldb_cache) {
2321             data_was_read = true;
2322             nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size,
2323                                eByteOrderLittle);
2324             strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size,
2325                                 eByteOrderLittle);
2326             if (function_starts_load_command.cmd) {
2327               const addr_t func_start_addr =
2328                   linkedit_load_addr + function_starts_load_command.dataoff -
2329                   linkedit_file_offset;
2330               function_starts_data.SetData(
2331                   (void *)func_start_addr,
2332                   function_starts_load_command.datasize, eByteOrderLittle);
2333             }
2334           }
2335         }
2336 #endif
2337 
2338         if (!data_was_read) {
2339           // Always load dyld - the dynamic linker - from memory if we didn't
2340           // find a binary anywhere else.
2341           // lldb will not register dylib/framework/bundle loads/unloads if we
2342           // don't have the dyld symbols,
2343           // we force dyld to load from memory despite the user's
2344           // target.memory-module-load-level setting.
2345           if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2346               m_header.filetype == llvm::MachO::MH_DYLINKER) {
2347             DataBufferSP nlist_data_sp(
2348                 ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
2349             if (nlist_data_sp)
2350               nlist_data.SetData(nlist_data_sp, 0,
2351                                  nlist_data_sp->GetByteSize());
2352             // Load strings individually from memory when loading from memory
2353             // since shared cache
2354             // string tables contain strings for all symbols from all shared
2355             // cached libraries
2356             // DataBufferSP strtab_data_sp (ReadMemory (process_sp, strtab_addr,
2357             // strtab_data_byte_size));
2358             // if (strtab_data_sp)
2359             //    strtab_data.SetData (strtab_data_sp, 0,
2360             //    strtab_data_sp->GetByteSize());
2361             if (m_dysymtab.nindirectsyms != 0) {
2362               const addr_t indirect_syms_addr = linkedit_load_addr +
2363                                                 m_dysymtab.indirectsymoff -
2364                                                 linkedit_file_offset;
2365               DataBufferSP indirect_syms_data_sp(
2366                   ReadMemory(process_sp, indirect_syms_addr,
2367                              m_dysymtab.nindirectsyms * 4));
2368               if (indirect_syms_data_sp)
2369                 indirect_symbol_index_data.SetData(
2370                     indirect_syms_data_sp, 0,
2371                     indirect_syms_data_sp->GetByteSize());
2372             }
2373           } else if (memory_module_load_level >=
2374                      eMemoryModuleLoadLevelPartial) {
2375             if (function_starts_load_command.cmd) {
2376               const addr_t func_start_addr =
2377                   linkedit_load_addr + function_starts_load_command.dataoff -
2378                   linkedit_file_offset;
2379               DataBufferSP func_start_data_sp(
2380                   ReadMemory(process_sp, func_start_addr,
2381                              function_starts_load_command.datasize));
2382               if (func_start_data_sp)
2383                 function_starts_data.SetData(func_start_data_sp, 0,
2384                                              func_start_data_sp->GetByteSize());
2385             }
2386           }
2387         }
2388       }
2389     } else {
2390       nlist_data.SetData(m_data, symtab_load_command.symoff,
2391                          nlist_data_byte_size);
2392       strtab_data.SetData(m_data, symtab_load_command.stroff,
2393                           strtab_data_byte_size);
2394 
2395       if (dyld_info.export_size > 0) {
2396         dyld_trie_data.SetData(m_data, dyld_info.export_off,
2397                                dyld_info.export_size);
2398       }
2399 
2400       if (m_dysymtab.nindirectsyms != 0) {
2401         indirect_symbol_index_data.SetData(m_data, m_dysymtab.indirectsymoff,
2402                                            m_dysymtab.nindirectsyms * 4);
2403       }
2404       if (function_starts_load_command.cmd) {
2405         function_starts_data.SetData(m_data,
2406                                      function_starts_load_command.dataoff,
2407                                      function_starts_load_command.datasize);
2408       }
2409     }
2410 
2411     if (nlist_data.GetByteSize() == 0 &&
2412         memory_module_load_level == eMemoryModuleLoadLevelComplete) {
2413       if (log)
2414         module_sp->LogMessage(log, "failed to read nlist data");
2415       return 0;
2416     }
2417 
2418     const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2419     if (!have_strtab_data) {
2420       if (process) {
2421         if (strtab_addr == LLDB_INVALID_ADDRESS) {
2422           if (log)
2423             module_sp->LogMessage(log, "failed to locate the strtab in memory");
2424           return 0;
2425         }
2426       } else {
2427         if (log)
2428           module_sp->LogMessage(log, "failed to read strtab data");
2429         return 0;
2430       }
2431     }
2432 
2433     const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT();
2434     const ConstString &g_segment_name_DATA = GetSegmentNameDATA();
2435     const ConstString &g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
2436     const ConstString &g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
2437     const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC();
2438     const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame();
2439     SectionSP text_section_sp(
2440         section_list->FindSectionByName(g_segment_name_TEXT));
2441     SectionSP data_section_sp(
2442         section_list->FindSectionByName(g_segment_name_DATA));
2443     SectionSP data_dirty_section_sp(
2444         section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
2445     SectionSP data_const_section_sp(
2446         section_list->FindSectionByName(g_segment_name_DATA_CONST));
2447     SectionSP objc_section_sp(
2448         section_list->FindSectionByName(g_segment_name_OBJC));
2449     SectionSP eh_frame_section_sp;
2450     if (text_section_sp.get())
2451       eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2452           g_section_name_eh_frame);
2453     else
2454       eh_frame_section_sp =
2455           section_list->FindSectionByName(g_section_name_eh_frame);
2456 
2457     const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
2458 
2459     // lldb works best if it knows the start address of all functions in a
2460     // module.
2461     // Linker symbols or debug info are normally the best source of information
2462     // for start addr / size but
2463     // they may be stripped in a released binary.
2464     // Two additional sources of information exist in Mach-O binaries:
2465     //    LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2466     //    function's start address in the
2467     //                         binary, relative to the text section.
2468     //    eh_frame           - the eh_frame FDEs have the start addr & size of
2469     //    each function
2470     //  LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2471     //  all modern binaries.
2472     //  Binaries built to run on older releases may need to use eh_frame
2473     //  information.
2474 
2475     if (text_section_sp && function_starts_data.GetByteSize()) {
2476       FunctionStarts::Entry function_start_entry;
2477       function_start_entry.data = false;
2478       lldb::offset_t function_start_offset = 0;
2479       function_start_entry.addr = text_section_sp->GetFileAddress();
2480       uint64_t delta;
2481       while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
2482              0) {
2483         // Now append the current entry
2484         function_start_entry.addr += delta;
2485         function_starts.Append(function_start_entry);
2486       }
2487     } else {
2488       // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
2489       // load command claiming an eh_frame
2490       // but it doesn't actually have the eh_frame content.  And if we have a
2491       // dSYM, we don't need to do any
2492       // of this fill-in-the-missing-symbols works anyway - the debug info
2493       // should give us all the functions in
2494       // the module.
2495       if (text_section_sp.get() && eh_frame_section_sp.get() &&
2496           m_type != eTypeDebugInfo) {
2497         DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
2498                                     eRegisterKindEHFrame, true);
2499         DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2500         eh_frame.GetFunctionAddressAndSizeVector(functions);
2501         addr_t text_base_addr = text_section_sp->GetFileAddress();
2502         size_t count = functions.GetSize();
2503         for (size_t i = 0; i < count; ++i) {
2504           const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
2505               functions.GetEntryAtIndex(i);
2506           if (func) {
2507             FunctionStarts::Entry function_start_entry;
2508             function_start_entry.addr = func->base - text_base_addr;
2509             function_starts.Append(function_start_entry);
2510           }
2511         }
2512       }
2513     }
2514 
2515     const size_t function_starts_count = function_starts.GetSize();
2516 
2517     // For user process binaries (executables, dylibs, frameworks, bundles), if
2518     // we don't have
2519     // LC_FUNCTION_STARTS/eh_frame section in this binary, we're going to assume
2520     // the binary
2521     // has been stripped.  Don't allow assembly language instruction emulation
2522     // because we don't
2523     // know proper function start boundaries.
2524     //
2525     // For all other types of binaries (kernels, stand-alone bare board
2526     // binaries, kexts), they
2527     // may not have LC_FUNCTION_STARTS / eh_frame sections - we should not make
2528     // any assumptions
2529     // about them based on that.
2530     if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2531       m_allow_assembly_emulation_unwind_plans = false;
2532       Log *unwind_or_symbol_log(lldb_private::GetLogIfAnyCategoriesSet(
2533           LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_UNWIND));
2534 
2535       if (unwind_or_symbol_log)
2536         module_sp->LogMessage(
2537             unwind_or_symbol_log,
2538             "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2539     }
2540 
2541     const user_id_t TEXT_eh_frame_sectID =
2542         eh_frame_section_sp.get() ? eh_frame_section_sp->GetID()
2543                                   : static_cast<user_id_t>(NO_SECT);
2544 
2545     lldb::offset_t nlist_data_offset = 0;
2546 
2547     uint32_t N_SO_index = UINT32_MAX;
2548 
2549     MachSymtabSectionInfo section_info(section_list);
2550     std::vector<uint32_t> N_FUN_indexes;
2551     std::vector<uint32_t> N_NSYM_indexes;
2552     std::vector<uint32_t> N_INCL_indexes;
2553     std::vector<uint32_t> N_BRAC_indexes;
2554     std::vector<uint32_t> N_COMM_indexes;
2555     typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2556     typedef std::map<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2557     typedef std::map<const char *, uint32_t> ConstNameToSymbolIndexMap;
2558     ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2559     ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2560     ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
2561     // Any symbols that get merged into another will get an entry
2562     // in this map so we know
2563     NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2564     uint32_t nlist_idx = 0;
2565     Symbol *symbol_ptr = NULL;
2566 
2567     uint32_t sym_idx = 0;
2568     Symbol *sym = NULL;
2569     size_t num_syms = 0;
2570     std::string memory_symbol_name;
2571     uint32_t unmapped_local_symbols_found = 0;
2572 
2573     std::vector<TrieEntryWithOffset> trie_entries;
2574     std::set<lldb::addr_t> resolver_addresses;
2575 
2576     if (dyld_trie_data.GetByteSize() > 0) {
2577       std::vector<llvm::StringRef> nameSlices;
2578       ParseTrieEntries(dyld_trie_data, 0, is_arm, nameSlices,
2579                        resolver_addresses, trie_entries);
2580 
2581       ConstString text_segment_name("__TEXT");
2582       SectionSP text_segment_sp =
2583           GetSectionList()->FindSectionByName(text_segment_name);
2584       if (text_segment_sp) {
2585         const lldb::addr_t text_segment_file_addr =
2586             text_segment_sp->GetFileAddress();
2587         if (text_segment_file_addr != LLDB_INVALID_ADDRESS) {
2588           for (auto &e : trie_entries)
2589             e.entry.address += text_segment_file_addr;
2590         }
2591       }
2592     }
2593 
2594     typedef std::set<ConstString> IndirectSymbols;
2595     IndirectSymbols indirect_symbol_names;
2596 
2597 #if defined(__APPLE__) &&                                                      \
2598     (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2599 
2600     // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
2601     // optimized by moving LOCAL
2602     // symbols out of the memory mapped portion of the DSC. The symbol
2603     // information has all been retained,
2604     // but it isn't available in the normal nlist data. However, there *are*
2605     // duplicate entries of *some*
2606     // LOCAL symbols in the normal nlist data. To handle this situation
2607     // correctly, we must first attempt
2608     // to parse any DSC unmapped symbol information. If we find any, we set a
2609     // flag that tells the normal
2610     // nlist parser to ignore all LOCAL symbols.
2611 
2612     if (m_header.flags & 0x80000000u) {
2613       // Before we can start mapping the DSC, we need to make certain the target
2614       // process is actually
2615       // using the cache we can find.
2616 
2617       // Next we need to determine the correct path for the dyld shared cache.
2618 
2619       ArchSpec header_arch;
2620       GetArchitecture(header_arch);
2621       char dsc_path[PATH_MAX];
2622       char dsc_path_development[PATH_MAX];
2623 
2624       snprintf(
2625           dsc_path, sizeof(dsc_path), "%s%s%s",
2626           "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2627                                                        */
2628           "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
2629           header_arch.GetArchitectureName());
2630 
2631       snprintf(
2632           dsc_path_development, sizeof(dsc_path), "%s%s%s%s",
2633           "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2634                                                        */
2635           "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
2636           header_arch.GetArchitectureName(), ".development");
2637 
2638       FileSpec dsc_nondevelopment_filespec(dsc_path, false);
2639       FileSpec dsc_development_filespec(dsc_path_development, false);
2640       FileSpec dsc_filespec;
2641 
2642       UUID dsc_uuid;
2643       UUID process_shared_cache_uuid;
2644 
2645       if (process) {
2646         process_shared_cache_uuid = GetProcessSharedCacheUUID(process);
2647       }
2648 
2649       // First see if we can find an exact match for the inferior process shared
2650       // cache UUID in
2651       // the development or non-development shared caches on disk.
2652       if (process_shared_cache_uuid.IsValid()) {
2653         if (dsc_development_filespec.Exists()) {
2654           UUID dsc_development_uuid = GetSharedCacheUUID(
2655               dsc_development_filespec, byte_order, addr_byte_size);
2656           if (dsc_development_uuid.IsValid() &&
2657               dsc_development_uuid == process_shared_cache_uuid) {
2658             dsc_filespec = dsc_development_filespec;
2659             dsc_uuid = dsc_development_uuid;
2660           }
2661         }
2662         if (!dsc_uuid.IsValid() && dsc_nondevelopment_filespec.Exists()) {
2663           UUID dsc_nondevelopment_uuid = GetSharedCacheUUID(
2664               dsc_nondevelopment_filespec, byte_order, addr_byte_size);
2665           if (dsc_nondevelopment_uuid.IsValid() &&
2666               dsc_nondevelopment_uuid == process_shared_cache_uuid) {
2667             dsc_filespec = dsc_nondevelopment_filespec;
2668             dsc_uuid = dsc_nondevelopment_uuid;
2669           }
2670         }
2671       }
2672 
2673       // Failing a UUID match, prefer the development dyld_shared cache if both
2674       // are present.
2675       if (!dsc_filespec.Exists()) {
2676         if (dsc_development_filespec.Exists()) {
2677           dsc_filespec = dsc_development_filespec;
2678         } else {
2679           dsc_filespec = dsc_nondevelopment_filespec;
2680         }
2681       }
2682 
2683       /* The dyld_cache_header has a pointer to the
2684          dyld_cache_local_symbols_info structure (localSymbolsOffset).
2685          The dyld_cache_local_symbols_info structure gives us three things:
2686            1. The start and count of the nlist records in the dyld_shared_cache
2687          file
2688            2. The start and size of the strings for these nlist records
2689            3. The start and count of dyld_cache_local_symbols_entry entries
2690 
2691          There is one dyld_cache_local_symbols_entry per dylib/framework in the
2692          dyld shared cache.
2693          The "dylibOffset" field is the Mach-O header of this dylib/framework in
2694          the dyld shared cache.
2695          The dyld_cache_local_symbols_entry also lists the start of this
2696          dylib/framework's nlist records
2697          and the count of how many nlist records there are for this
2698          dylib/framework.
2699       */
2700 
2701       // Process the dyld shared cache header to find the unmapped symbols
2702 
2703       DataBufferSP dsc_data_sp = DataBufferLLVM::CreateFromFileSpec(
2704           dsc_filespec, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
2705       if (!dsc_uuid.IsValid()) {
2706         dsc_uuid = GetSharedCacheUUID(dsc_filespec, byte_order, addr_byte_size);
2707       }
2708       if (dsc_data_sp) {
2709         DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2710 
2711         bool uuid_match = true;
2712         if (dsc_uuid.IsValid() && process) {
2713           if (process_shared_cache_uuid.IsValid() &&
2714               dsc_uuid != process_shared_cache_uuid) {
2715             // The on-disk dyld_shared_cache file is not the same as the one in
2716             // this
2717             // process' memory, don't use it.
2718             uuid_match = false;
2719             ModuleSP module_sp(GetModule());
2720             if (module_sp)
2721               module_sp->ReportWarning("process shared cache does not match "
2722                                        "on-disk dyld_shared_cache file, some "
2723                                        "symbol names will be missing.");
2724           }
2725         }
2726 
2727         offset = offsetof(struct lldb_copy_dyld_cache_header_v1, mappingOffset);
2728 
2729         uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
2730 
2731         // If the mappingOffset points to a location inside the header, we've
2732         // opened an old dyld shared cache, and should not proceed further.
2733         if (uuid_match &&
2734             mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v1)) {
2735 
2736           DataBufferSP dsc_mapping_info_data_sp =
2737               DataBufferLLVM::CreateFromFileSpec(
2738                   dsc_filespec,
2739                   sizeof(struct lldb_copy_dyld_cache_mapping_info),
2740                   mappingOffset);
2741 
2742           DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp,
2743                                               byte_order, addr_byte_size);
2744           offset = 0;
2745 
2746           // The File addresses (from the in-memory Mach-O load commands) for
2747           // the shared libraries
2748           // in the shared library cache need to be adjusted by an offset to
2749           // match up with the
2750           // dylibOffset identifying field in the
2751           // dyld_cache_local_symbol_entry's.  This offset is
2752           // recorded in mapping_offset_value.
2753           const uint64_t mapping_offset_value =
2754               dsc_mapping_info_data.GetU64(&offset);
2755 
2756           offset = offsetof(struct lldb_copy_dyld_cache_header_v1,
2757                             localSymbolsOffset);
2758           uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2759           uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
2760 
2761           if (localSymbolsOffset && localSymbolsSize) {
2762             // Map the local symbols
2763             DataBufferSP dsc_local_symbols_data_sp =
2764                 DataBufferLLVM::CreateFromFileSpec(
2765                     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           Error 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     const bool resolve_path = false; // Don't resolve the dependent file paths
5050                                      // since they may not reside on this system
5051     uint32_t i;
5052     for (i = 0; i < m_header.ncmds; ++i) {
5053       const uint32_t cmd_offset = offset;
5054       if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5055         break;
5056 
5057       switch (load_cmd.cmd) {
5058       case LC_RPATH:
5059       case LC_LOAD_DYLIB:
5060       case LC_LOAD_WEAK_DYLIB:
5061       case LC_REEXPORT_DYLIB:
5062       case LC_LOAD_DYLINKER:
5063       case LC_LOADFVMLIB:
5064       case LC_LOAD_UPWARD_DYLIB: {
5065         uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
5066         const char *path = m_data.PeekCStr(name_offset);
5067         if (path) {
5068           if (load_cmd.cmd == LC_RPATH)
5069             rpath_paths.push_back(path);
5070           else {
5071             if (path[0] == '@') {
5072               if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
5073                 rpath_relative_paths.push_back(path + strlen("@rpath"));
5074             } else {
5075               FileSpec file_spec(path, resolve_path);
5076               if (files.AppendIfUnique(file_spec))
5077                 count++;
5078             }
5079           }
5080         }
5081       } break;
5082 
5083       default:
5084         break;
5085       }
5086       offset = cmd_offset + load_cmd.cmdsize;
5087     }
5088 
5089     if (!rpath_paths.empty()) {
5090       // Fixup all LC_RPATH values to be absolute paths
5091       FileSpec this_file_spec(m_file);
5092       this_file_spec.ResolvePath();
5093       std::string loader_path("@loader_path");
5094       std::string executable_path("@executable_path");
5095       for (auto &rpath : rpath_paths) {
5096         if (rpath.find(loader_path) == 0) {
5097           rpath.erase(0, loader_path.size());
5098           rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5099         } else if (rpath.find(executable_path) == 0) {
5100           rpath.erase(0, executable_path.size());
5101           rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5102         }
5103       }
5104 
5105       for (const auto &rpath_relative_path : rpath_relative_paths) {
5106         for (const auto &rpath : rpath_paths) {
5107           std::string path = rpath;
5108           path += rpath_relative_path;
5109           // It is OK to resolve this path because we must find a file on
5110           // disk for us to accept it anyway if it is rpath relative.
5111           FileSpec file_spec(path, true);
5112           // Remove any redundant parts of the path (like "../foo") since
5113           // LC_RPATH values often contain "..".
5114           file_spec = file_spec.GetNormalizedPath();
5115           if (file_spec.Exists() && files.AppendIfUnique(file_spec)) {
5116             count++;
5117             break;
5118           }
5119         }
5120       }
5121     }
5122   }
5123   return count;
5124 }
5125 
5126 lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
5127   // If the object file is not an executable it can't hold the entry point.
5128   // m_entry_point_address
5129   // is initialized to an invalid address, so we can just return that.
5130   // If m_entry_point_address is valid it means we've found it already, so
5131   // return the cached value.
5132 
5133   if (!IsExecutable() || m_entry_point_address.IsValid())
5134     return m_entry_point_address;
5135 
5136   // Otherwise, look for the UnixThread or Thread command.  The data for the
5137   // Thread command is given in
5138   // /usr/include/mach-o.h, but it is basically:
5139   //
5140   //  uint32_t flavor  - this is the flavor argument you would pass to
5141   //  thread_get_state
5142   //  uint32_t count   - this is the count of longs in the thread state data
5143   //  struct XXX_thread_state state - this is the structure from
5144   //  <machine/thread_status.h> corresponding to the flavor.
5145   //  <repeat this trio>
5146   //
5147   // So we just keep reading the various register flavors till we find the GPR
5148   // one, then read the PC out of there.
5149   // FIXME: We will need to have a "RegisterContext data provider" class at some
5150   // point that can get all the registers
5151   // out of data in this form & attach them to a given thread.  That should
5152   // underlie the MacOS X User process plugin,
5153   // and we'll also need it for the MacOS X Core File process plugin.  When we
5154   // have that we can also use it here.
5155   //
5156   // For now we hard-code the offsets and flavors we need:
5157   //
5158   //
5159 
5160   ModuleSP module_sp(GetModule());
5161   if (module_sp) {
5162     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5163     struct load_command load_cmd;
5164     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5165     uint32_t i;
5166     lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
5167     bool done = false;
5168 
5169     for (i = 0; i < m_header.ncmds; ++i) {
5170       const lldb::offset_t cmd_offset = offset;
5171       if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5172         break;
5173 
5174       switch (load_cmd.cmd) {
5175       case LC_UNIXTHREAD:
5176       case LC_THREAD: {
5177         while (offset < cmd_offset + load_cmd.cmdsize) {
5178           uint32_t flavor = m_data.GetU32(&offset);
5179           uint32_t count = m_data.GetU32(&offset);
5180           if (count == 0) {
5181             // We've gotten off somehow, log and exit;
5182             return m_entry_point_address;
5183           }
5184 
5185           switch (m_header.cputype) {
5186           case llvm::MachO::CPU_TYPE_ARM:
5187             if (flavor == 1 ||
5188                 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32 from
5189                              // mach/arm/thread_status.h
5190             {
5191               offset += 60; // This is the offset of pc in the GPR thread state
5192                             // data structure.
5193               start_address = m_data.GetU32(&offset);
5194               done = true;
5195             }
5196             break;
5197           case llvm::MachO::CPU_TYPE_ARM64:
5198             if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
5199             {
5200               offset += 256; // This is the offset of pc in the GPR thread state
5201                              // data structure.
5202               start_address = m_data.GetU64(&offset);
5203               done = true;
5204             }
5205             break;
5206           case llvm::MachO::CPU_TYPE_I386:
5207             if (flavor ==
5208                 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
5209             {
5210               offset += 40; // This is the offset of eip in the GPR thread state
5211                             // data structure.
5212               start_address = m_data.GetU32(&offset);
5213               done = true;
5214             }
5215             break;
5216           case llvm::MachO::CPU_TYPE_X86_64:
5217             if (flavor ==
5218                 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
5219             {
5220               offset += 16 * 8; // This is the offset of rip in the GPR thread
5221                                 // state data structure.
5222               start_address = m_data.GetU64(&offset);
5223               done = true;
5224             }
5225             break;
5226           default:
5227             return m_entry_point_address;
5228           }
5229           // Haven't found the GPR flavor yet, skip over the data for this
5230           // flavor:
5231           if (done)
5232             break;
5233           offset += count * 4;
5234         }
5235       } break;
5236       case LC_MAIN: {
5237         ConstString text_segment_name("__TEXT");
5238         uint64_t entryoffset = m_data.GetU64(&offset);
5239         SectionSP text_segment_sp =
5240             GetSectionList()->FindSectionByName(text_segment_name);
5241         if (text_segment_sp) {
5242           done = true;
5243           start_address = text_segment_sp->GetFileAddress() + entryoffset;
5244         }
5245       } break;
5246 
5247       default:
5248         break;
5249       }
5250       if (done)
5251         break;
5252 
5253       // Go to the next load command:
5254       offset = cmd_offset + load_cmd.cmdsize;
5255     }
5256 
5257     if (start_address != LLDB_INVALID_ADDRESS) {
5258       // We got the start address from the load commands, so now resolve that
5259       // address in the sections
5260       // of this ObjectFile:
5261       if (!m_entry_point_address.ResolveAddressUsingFileSections(
5262               start_address, GetSectionList())) {
5263         m_entry_point_address.Clear();
5264       }
5265     } else {
5266       // We couldn't read the UnixThread load command - maybe it wasn't there.
5267       // As a fallback look for the
5268       // "start" symbol in the main executable.
5269 
5270       ModuleSP module_sp(GetModule());
5271 
5272       if (module_sp) {
5273         SymbolContextList contexts;
5274         SymbolContext context;
5275         if (module_sp->FindSymbolsWithNameAndType(ConstString("start"),
5276                                                   eSymbolTypeCode, contexts)) {
5277           if (contexts.GetContextAtIndex(0, context))
5278             m_entry_point_address = context.symbol->GetAddress();
5279         }
5280       }
5281     }
5282   }
5283 
5284   return m_entry_point_address;
5285 }
5286 
5287 lldb_private::Address ObjectFileMachO::GetHeaderAddress() {
5288   lldb_private::Address header_addr;
5289   SectionList *section_list = GetSectionList();
5290   if (section_list) {
5291     SectionSP text_segment_sp(
5292         section_list->FindSectionByName(GetSegmentNameTEXT()));
5293     if (text_segment_sp) {
5294       header_addr.SetSection(text_segment_sp);
5295       header_addr.SetOffset(0);
5296     }
5297   }
5298   return header_addr;
5299 }
5300 
5301 uint32_t ObjectFileMachO::GetNumThreadContexts() {
5302   ModuleSP module_sp(GetModule());
5303   if (module_sp) {
5304     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5305     if (!m_thread_context_offsets_valid) {
5306       m_thread_context_offsets_valid = true;
5307       lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5308       FileRangeArray::Entry file_range;
5309       thread_command thread_cmd;
5310       for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5311         const uint32_t cmd_offset = offset;
5312         if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL)
5313           break;
5314 
5315         if (thread_cmd.cmd == LC_THREAD) {
5316           file_range.SetRangeBase(offset);
5317           file_range.SetByteSize(thread_cmd.cmdsize - 8);
5318           m_thread_context_offsets.Append(file_range);
5319         }
5320         offset = cmd_offset + thread_cmd.cmdsize;
5321       }
5322     }
5323   }
5324   return m_thread_context_offsets.GetSize();
5325 }
5326 
5327 lldb::RegisterContextSP
5328 ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
5329                                          lldb_private::Thread &thread) {
5330   lldb::RegisterContextSP reg_ctx_sp;
5331 
5332   ModuleSP module_sp(GetModule());
5333   if (module_sp) {
5334     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5335     if (!m_thread_context_offsets_valid)
5336       GetNumThreadContexts();
5337 
5338     const FileRangeArray::Entry *thread_context_file_range =
5339         m_thread_context_offsets.GetEntryAtIndex(idx);
5340     if (thread_context_file_range) {
5341 
5342       DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
5343                          thread_context_file_range->GetByteSize());
5344 
5345       switch (m_header.cputype) {
5346       case llvm::MachO::CPU_TYPE_ARM64:
5347         reg_ctx_sp.reset(new RegisterContextDarwin_arm64_Mach(thread, data));
5348         break;
5349 
5350       case llvm::MachO::CPU_TYPE_ARM:
5351         reg_ctx_sp.reset(new RegisterContextDarwin_arm_Mach(thread, data));
5352         break;
5353 
5354       case llvm::MachO::CPU_TYPE_I386:
5355         reg_ctx_sp.reset(new RegisterContextDarwin_i386_Mach(thread, data));
5356         break;
5357 
5358       case llvm::MachO::CPU_TYPE_X86_64:
5359         reg_ctx_sp.reset(new RegisterContextDarwin_x86_64_Mach(thread, data));
5360         break;
5361       }
5362     }
5363   }
5364   return reg_ctx_sp;
5365 }
5366 
5367 ObjectFile::Type ObjectFileMachO::CalculateType() {
5368   switch (m_header.filetype) {
5369   case MH_OBJECT: // 0x1u
5370     if (GetAddressByteSize() == 4) {
5371       // 32 bit kexts are just object files, but they do have a valid
5372       // UUID load command.
5373       UUID uuid;
5374       if (GetUUID(&uuid)) {
5375         // this checking for the UUID load command is not enough
5376         // we could eventually look for the symbol named
5377         // "OSKextGetCurrentIdentifier" as this is required of kexts
5378         if (m_strata == eStrataInvalid)
5379           m_strata = eStrataKernel;
5380         return eTypeSharedLibrary;
5381       }
5382     }
5383     return eTypeObjectFile;
5384 
5385   case MH_EXECUTE:
5386     return eTypeExecutable; // 0x2u
5387   case MH_FVMLIB:
5388     return eTypeSharedLibrary; // 0x3u
5389   case MH_CORE:
5390     return eTypeCoreFile; // 0x4u
5391   case MH_PRELOAD:
5392     return eTypeSharedLibrary; // 0x5u
5393   case MH_DYLIB:
5394     return eTypeSharedLibrary; // 0x6u
5395   case MH_DYLINKER:
5396     return eTypeDynamicLinker; // 0x7u
5397   case MH_BUNDLE:
5398     return eTypeSharedLibrary; // 0x8u
5399   case MH_DYLIB_STUB:
5400     return eTypeStubLibrary; // 0x9u
5401   case MH_DSYM:
5402     return eTypeDebugInfo; // 0xAu
5403   case MH_KEXT_BUNDLE:
5404     return eTypeSharedLibrary; // 0xBu
5405   default:
5406     break;
5407   }
5408   return eTypeUnknown;
5409 }
5410 
5411 ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
5412   switch (m_header.filetype) {
5413   case MH_OBJECT: // 0x1u
5414   {
5415     // 32 bit kexts are just object files, but they do have a valid
5416     // UUID load command.
5417     UUID uuid;
5418     if (GetUUID(&uuid)) {
5419       // this checking for the UUID load command is not enough
5420       // we could eventually look for the symbol named
5421       // "OSKextGetCurrentIdentifier" as this is required of kexts
5422       if (m_type == eTypeInvalid)
5423         m_type = eTypeSharedLibrary;
5424 
5425       return eStrataKernel;
5426     }
5427   }
5428     return eStrataUnknown;
5429 
5430   case MH_EXECUTE: // 0x2u
5431     // Check for the MH_DYLDLINK bit in the flags
5432     if (m_header.flags & MH_DYLDLINK) {
5433       return eStrataUser;
5434     } else {
5435       SectionList *section_list = GetSectionList();
5436       if (section_list) {
5437         static ConstString g_kld_section_name("__KLD");
5438         if (section_list->FindSectionByName(g_kld_section_name))
5439           return eStrataKernel;
5440       }
5441     }
5442     return eStrataRawImage;
5443 
5444   case MH_FVMLIB:
5445     return eStrataUser; // 0x3u
5446   case MH_CORE:
5447     return eStrataUnknown; // 0x4u
5448   case MH_PRELOAD:
5449     return eStrataRawImage; // 0x5u
5450   case MH_DYLIB:
5451     return eStrataUser; // 0x6u
5452   case MH_DYLINKER:
5453     return eStrataUser; // 0x7u
5454   case MH_BUNDLE:
5455     return eStrataUser; // 0x8u
5456   case MH_DYLIB_STUB:
5457     return eStrataUser; // 0x9u
5458   case MH_DSYM:
5459     return eStrataUnknown; // 0xAu
5460   case MH_KEXT_BUNDLE:
5461     return eStrataKernel; // 0xBu
5462   default:
5463     break;
5464   }
5465   return eStrataUnknown;
5466 }
5467 
5468 uint32_t ObjectFileMachO::GetVersion(uint32_t *versions,
5469                                      uint32_t num_versions) {
5470   ModuleSP module_sp(GetModule());
5471   if (module_sp) {
5472     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5473     struct dylib_command load_cmd;
5474     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5475     uint32_t version_cmd = 0;
5476     uint64_t version = 0;
5477     uint32_t i;
5478     for (i = 0; i < m_header.ncmds; ++i) {
5479       const lldb::offset_t cmd_offset = offset;
5480       if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5481         break;
5482 
5483       if (load_cmd.cmd == LC_ID_DYLIB) {
5484         if (version_cmd == 0) {
5485           version_cmd = load_cmd.cmd;
5486           if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL)
5487             break;
5488           version = load_cmd.dylib.current_version;
5489         }
5490         break; // Break for now unless there is another more complete version
5491                // number load command in the future.
5492       }
5493       offset = cmd_offset + load_cmd.cmdsize;
5494     }
5495 
5496     if (version_cmd == LC_ID_DYLIB) {
5497       if (versions != NULL && num_versions > 0) {
5498         if (num_versions > 0)
5499           versions[0] = (version & 0xFFFF0000ull) >> 16;
5500         if (num_versions > 1)
5501           versions[1] = (version & 0x0000FF00ull) >> 8;
5502         if (num_versions > 2)
5503           versions[2] = (version & 0x000000FFull);
5504         // Fill in an remaining version numbers with invalid values
5505         for (i = 3; i < num_versions; ++i)
5506           versions[i] = UINT32_MAX;
5507       }
5508       // The LC_ID_DYLIB load command has a version with 3 version numbers
5509       // in it, so always return 3
5510       return 3;
5511     }
5512   }
5513   return false;
5514 }
5515 
5516 bool ObjectFileMachO::GetArchitecture(ArchSpec &arch) {
5517   ModuleSP module_sp(GetModule());
5518   if (module_sp) {
5519     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5520     return GetArchitecture(m_header, m_data,
5521                            MachHeaderSizeFromMagic(m_header.magic), arch);
5522   }
5523   return false;
5524 }
5525 
5526 UUID ObjectFileMachO::GetProcessSharedCacheUUID(Process *process) {
5527   UUID uuid;
5528   if (process && process->GetDynamicLoader()) {
5529     DynamicLoader *dl = process->GetDynamicLoader();
5530     addr_t load_address;
5531     LazyBool using_shared_cache;
5532     LazyBool private_shared_cache;
5533     dl->GetSharedCacheInformation(load_address, uuid, using_shared_cache,
5534                                   private_shared_cache);
5535   }
5536   return uuid;
5537 }
5538 
5539 UUID ObjectFileMachO::GetLLDBSharedCacheUUID() {
5540   UUID uuid;
5541 #if defined(__APPLE__) &&                                                      \
5542     (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
5543   uint8_t *(*dyld_get_all_image_infos)(void);
5544   dyld_get_all_image_infos =
5545       (uint8_t * (*)())dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5546   if (dyld_get_all_image_infos) {
5547     uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5548     if (dyld_all_image_infos_address) {
5549       uint32_t *version = (uint32_t *)
5550           dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5551       if (*version >= 13) {
5552         uuid_t *sharedCacheUUID_address = 0;
5553         int wordsize = sizeof(uint8_t *);
5554         if (wordsize == 8) {
5555           sharedCacheUUID_address =
5556               (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5557                          160); // sharedCacheUUID <mach-o/dyld_images.h>
5558         } else {
5559           sharedCacheUUID_address =
5560               (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5561                          84); // sharedCacheUUID <mach-o/dyld_images.h>
5562         }
5563         uuid.SetBytes(sharedCacheUUID_address);
5564       }
5565     }
5566   }
5567 #endif
5568   return uuid;
5569 }
5570 
5571 uint32_t ObjectFileMachO::GetMinimumOSVersion(uint32_t *versions,
5572                                               uint32_t num_versions) {
5573   if (m_min_os_versions.empty()) {
5574     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5575     bool success = false;
5576     for (uint32_t i = 0; success == false && i < m_header.ncmds; ++i) {
5577       const lldb::offset_t load_cmd_offset = offset;
5578 
5579       version_min_command lc;
5580       if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5581         break;
5582       if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5583           lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5584           lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5585           lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5586         if (m_data.GetU32(&offset, &lc.version,
5587                           (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5588           const uint32_t xxxx = lc.version >> 16;
5589           const uint32_t yy = (lc.version >> 8) & 0xffu;
5590           const uint32_t zz = lc.version & 0xffu;
5591           if (xxxx) {
5592             m_min_os_versions.push_back(xxxx);
5593             m_min_os_versions.push_back(yy);
5594             m_min_os_versions.push_back(zz);
5595           }
5596           success = true;
5597         }
5598       }
5599       offset = load_cmd_offset + lc.cmdsize;
5600     }
5601 
5602     if (success == false) {
5603       // Push an invalid value so we don't keep trying to
5604       m_min_os_versions.push_back(UINT32_MAX);
5605     }
5606   }
5607 
5608   if (m_min_os_versions.size() > 1 || m_min_os_versions[0] != UINT32_MAX) {
5609     if (versions != NULL && num_versions > 0) {
5610       for (size_t i = 0; i < num_versions; ++i) {
5611         if (i < m_min_os_versions.size())
5612           versions[i] = m_min_os_versions[i];
5613         else
5614           versions[i] = 0;
5615       }
5616     }
5617     return m_min_os_versions.size();
5618   }
5619   // Call the superclasses version that will empty out the data
5620   return ObjectFile::GetMinimumOSVersion(versions, num_versions);
5621 }
5622 
5623 uint32_t ObjectFileMachO::GetSDKVersion(uint32_t *versions,
5624                                         uint32_t num_versions) {
5625   if (m_sdk_versions.empty()) {
5626     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5627     bool success = false;
5628     for (uint32_t i = 0; success == false && i < m_header.ncmds; ++i) {
5629       const lldb::offset_t load_cmd_offset = offset;
5630 
5631       version_min_command lc;
5632       if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5633         break;
5634       if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5635           lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5636           lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5637           lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5638         if (m_data.GetU32(&offset, &lc.version,
5639                           (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5640           const uint32_t xxxx = lc.sdk >> 16;
5641           const uint32_t yy = (lc.sdk >> 8) & 0xffu;
5642           const uint32_t zz = lc.sdk & 0xffu;
5643           if (xxxx) {
5644             m_sdk_versions.push_back(xxxx);
5645             m_sdk_versions.push_back(yy);
5646             m_sdk_versions.push_back(zz);
5647           }
5648           success = true;
5649         }
5650       }
5651       offset = load_cmd_offset + lc.cmdsize;
5652     }
5653 
5654     if (success == false) {
5655       // Push an invalid value so we don't keep trying to
5656       m_sdk_versions.push_back(UINT32_MAX);
5657     }
5658   }
5659 
5660   if (m_sdk_versions.size() > 1 || m_sdk_versions[0] != UINT32_MAX) {
5661     if (versions != NULL && num_versions > 0) {
5662       for (size_t i = 0; i < num_versions; ++i) {
5663         if (i < m_sdk_versions.size())
5664           versions[i] = m_sdk_versions[i];
5665         else
5666           versions[i] = 0;
5667       }
5668     }
5669     return m_sdk_versions.size();
5670   }
5671   // Call the superclasses version that will empty out the data
5672   return ObjectFile::GetSDKVersion(versions, num_versions);
5673 }
5674 
5675 bool ObjectFileMachO::GetIsDynamicLinkEditor() {
5676   return m_header.filetype == llvm::MachO::MH_DYLINKER;
5677 }
5678 
5679 bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
5680   return m_allow_assembly_emulation_unwind_plans;
5681 }
5682 
5683 //------------------------------------------------------------------
5684 // PluginInterface protocol
5685 //------------------------------------------------------------------
5686 lldb_private::ConstString ObjectFileMachO::GetPluginName() {
5687   return GetPluginNameStatic();
5688 }
5689 
5690 uint32_t ObjectFileMachO::GetPluginVersion() { return 1; }
5691 
5692 Section *ObjectFileMachO::GetMachHeaderSection() {
5693   // Find the first address of the mach header which is the first non-zero
5694   // file sized section whose file offset is zero. This is the base file address
5695   // of the mach-o file which can be subtracted from the vmaddr of the other
5696   // segments found in memory and added to the load address
5697   ModuleSP module_sp = GetModule();
5698   if (module_sp) {
5699     SectionList *section_list = GetSectionList();
5700     if (section_list) {
5701       lldb::addr_t mach_base_file_addr = LLDB_INVALID_ADDRESS;
5702       const size_t num_sections = section_list->GetSize();
5703 
5704       for (size_t sect_idx = 0; sect_idx < num_sections &&
5705                                 mach_base_file_addr == LLDB_INVALID_ADDRESS;
5706            ++sect_idx) {
5707         Section *section = section_list->GetSectionAtIndex(sect_idx).get();
5708         if (section && section->GetFileSize() > 0 &&
5709             section->GetFileOffset() == 0 &&
5710             section->IsThreadSpecific() == false &&
5711             module_sp.get() == section->GetModule().get()) {
5712           return section;
5713         }
5714       }
5715     }
5716   }
5717   return nullptr;
5718 }
5719 
5720 lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
5721     lldb::addr_t mach_header_load_address, const Section *mach_header_section,
5722     const Section *section) {
5723   ModuleSP module_sp = GetModule();
5724   if (module_sp && mach_header_section && section &&
5725       mach_header_load_address != LLDB_INVALID_ADDRESS) {
5726     lldb::addr_t mach_header_file_addr = mach_header_section->GetFileAddress();
5727     if (mach_header_file_addr != LLDB_INVALID_ADDRESS) {
5728       if (section && section->GetFileSize() > 0 &&
5729           section->IsThreadSpecific() == false &&
5730           module_sp.get() == section->GetModule().get()) {
5731         // Ignore __LINKEDIT and __DWARF segments
5732         if (section->GetName() == GetSegmentNameLINKEDIT()) {
5733           // Only map __LINKEDIT if we have an in memory image and this isn't
5734           // a kernel binary like a kext or mach_kernel.
5735           const bool is_memory_image = (bool)m_process_wp.lock();
5736           const Strata strata = GetStrata();
5737           if (is_memory_image == false || strata == eStrataKernel)
5738             return LLDB_INVALID_ADDRESS;
5739         }
5740         return section->GetFileAddress() - mach_header_file_addr +
5741                mach_header_load_address;
5742       }
5743     }
5744   }
5745   return LLDB_INVALID_ADDRESS;
5746 }
5747 
5748 bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
5749                                      bool value_is_offset) {
5750   ModuleSP module_sp = GetModule();
5751   if (module_sp) {
5752     size_t num_loaded_sections = 0;
5753     SectionList *section_list = GetSectionList();
5754     if (section_list) {
5755       const size_t num_sections = section_list->GetSize();
5756 
5757       if (value_is_offset) {
5758         // "value" is an offset to apply to each top level segment
5759         for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5760           // Iterate through the object file sections to find all
5761           // of the sections that size on disk (to avoid __PAGEZERO)
5762           // and load them
5763           SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
5764           if (section_sp && section_sp->GetFileSize() > 0 &&
5765               section_sp->IsThreadSpecific() == false &&
5766               module_sp.get() == section_sp->GetModule().get()) {
5767             // Ignore __LINKEDIT and __DWARF segments
5768             if (section_sp->GetName() == GetSegmentNameLINKEDIT()) {
5769               // Only map __LINKEDIT if we have an in memory image and this
5770               // isn't
5771               // a kernel binary like a kext or mach_kernel.
5772               const bool is_memory_image = (bool)m_process_wp.lock();
5773               const Strata strata = GetStrata();
5774               if (is_memory_image == false || strata == eStrataKernel)
5775                 continue;
5776             }
5777             if (target.GetSectionLoadList().SetSectionLoadAddress(
5778                     section_sp, section_sp->GetFileAddress() + value))
5779               ++num_loaded_sections;
5780           }
5781         }
5782       } else {
5783         // "value" is the new base address of the mach_header, adjust each
5784         // section accordingly
5785 
5786         Section *mach_header_section = GetMachHeaderSection();
5787         if (mach_header_section) {
5788           for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5789             SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
5790 
5791             lldb::addr_t section_load_addr =
5792                 CalculateSectionLoadAddressForMemoryImage(
5793                     value, mach_header_section, section_sp.get());
5794             if (section_load_addr != LLDB_INVALID_ADDRESS) {
5795               if (target.GetSectionLoadList().SetSectionLoadAddress(
5796                       section_sp, section_load_addr))
5797                 ++num_loaded_sections;
5798             }
5799           }
5800         }
5801       }
5802     }
5803     return num_loaded_sections > 0;
5804   }
5805   return false;
5806 }
5807 
5808 bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
5809                                const FileSpec &outfile, Error &error) {
5810   if (process_sp) {
5811     Target &target = process_sp->GetTarget();
5812     const ArchSpec target_arch = target.GetArchitecture();
5813     const llvm::Triple &target_triple = target_arch.GetTriple();
5814     if (target_triple.getVendor() == llvm::Triple::Apple &&
5815         (target_triple.getOS() == llvm::Triple::MacOSX ||
5816          target_triple.getOS() == llvm::Triple::IOS ||
5817          target_triple.getOS() == llvm::Triple::WatchOS ||
5818          target_triple.getOS() == llvm::Triple::TvOS)) {
5819       bool make_core = false;
5820       switch (target_arch.GetMachine()) {
5821       case llvm::Triple::aarch64:
5822       case llvm::Triple::arm:
5823       case llvm::Triple::thumb:
5824       case llvm::Triple::x86:
5825       case llvm::Triple::x86_64:
5826         make_core = true;
5827         break;
5828       default:
5829         error.SetErrorStringWithFormat("unsupported core architecture: %s",
5830                                        target_triple.str().c_str());
5831         break;
5832       }
5833 
5834       if (make_core) {
5835         std::vector<segment_command_64> segment_load_commands;
5836         //                uint32_t range_info_idx = 0;
5837         MemoryRegionInfo range_info;
5838         Error range_error = process_sp->GetMemoryRegionInfo(0, range_info);
5839         const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
5840         const ByteOrder byte_order = target_arch.GetByteOrder();
5841         if (range_error.Success()) {
5842           while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
5843             const addr_t addr = range_info.GetRange().GetRangeBase();
5844             const addr_t size = range_info.GetRange().GetByteSize();
5845 
5846             if (size == 0)
5847               break;
5848 
5849             // Calculate correct protections
5850             uint32_t prot = 0;
5851             if (range_info.GetReadable() == MemoryRegionInfo::eYes)
5852               prot |= VM_PROT_READ;
5853             if (range_info.GetWritable() == MemoryRegionInfo::eYes)
5854               prot |= VM_PROT_WRITE;
5855             if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
5856               prot |= VM_PROT_EXECUTE;
5857 
5858             //                        printf ("[%3u] [0x%16.16" PRIx64 " -
5859             //                        0x%16.16" PRIx64 ") %c%c%c\n",
5860             //                                range_info_idx,
5861             //                                addr,
5862             //                                size,
5863             //                                (prot & VM_PROT_READ   ) ? 'r' :
5864             //                                '-',
5865             //                                (prot & VM_PROT_WRITE  ) ? 'w' :
5866             //                                '-',
5867             //                                (prot & VM_PROT_EXECUTE) ? 'x' :
5868             //                                '-');
5869 
5870             if (prot != 0) {
5871               uint32_t cmd_type = LC_SEGMENT_64;
5872               uint32_t segment_size = sizeof(segment_command_64);
5873               if (addr_byte_size == 4) {
5874                 cmd_type = LC_SEGMENT;
5875                 segment_size = sizeof(segment_command);
5876               }
5877               segment_command_64 segment = {
5878                   cmd_type,     // uint32_t cmd;
5879                   segment_size, // uint32_t cmdsize;
5880                   {0},          // char segname[16];
5881                   addr, // uint64_t vmaddr;    // uint32_t for 32-bit Mach-O
5882                   size, // uint64_t vmsize;    // uint32_t for 32-bit Mach-O
5883                   0,    // uint64_t fileoff;   // uint32_t for 32-bit Mach-O
5884                   size, // uint64_t filesize;  // uint32_t for 32-bit Mach-O
5885                   prot, // uint32_t maxprot;
5886                   prot, // uint32_t initprot;
5887                   0,    // uint32_t nsects;
5888                   0};   // uint32_t flags;
5889               segment_load_commands.push_back(segment);
5890             } else {
5891               // No protections and a size of 1 used to be returned from old
5892               // debugservers when we asked about a region that was past the
5893               // last memory region and it indicates the end...
5894               if (size == 1)
5895                 break;
5896             }
5897 
5898             range_error = process_sp->GetMemoryRegionInfo(
5899                 range_info.GetRange().GetRangeEnd(), range_info);
5900             if (range_error.Fail())
5901               break;
5902           }
5903 
5904           StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
5905 
5906           mach_header_64 mach_header;
5907           if (addr_byte_size == 8) {
5908             mach_header.magic = MH_MAGIC_64;
5909           } else {
5910             mach_header.magic = MH_MAGIC;
5911           }
5912           mach_header.cputype = target_arch.GetMachOCPUType();
5913           mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
5914           mach_header.filetype = MH_CORE;
5915           mach_header.ncmds = segment_load_commands.size();
5916           mach_header.flags = 0;
5917           mach_header.reserved = 0;
5918           ThreadList &thread_list = process_sp->GetThreadList();
5919           const uint32_t num_threads = thread_list.GetSize();
5920 
5921           // Make an array of LC_THREAD data items. Each one contains
5922           // the contents of the LC_THREAD load command. The data doesn't
5923           // contain the load command + load command size, we will
5924           // add the load command and load command size as we emit the data.
5925           std::vector<StreamString> LC_THREAD_datas(num_threads);
5926           for (auto &LC_THREAD_data : LC_THREAD_datas) {
5927             LC_THREAD_data.GetFlags().Set(Stream::eBinary);
5928             LC_THREAD_data.SetAddressByteSize(addr_byte_size);
5929             LC_THREAD_data.SetByteOrder(byte_order);
5930           }
5931           for (uint32_t thread_idx = 0; thread_idx < num_threads;
5932                ++thread_idx) {
5933             ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
5934             if (thread_sp) {
5935               switch (mach_header.cputype) {
5936               case llvm::MachO::CPU_TYPE_ARM64:
5937                 RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
5938                     thread_sp.get(), LC_THREAD_datas[thread_idx]);
5939                 break;
5940 
5941               case llvm::MachO::CPU_TYPE_ARM:
5942                 RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
5943                     thread_sp.get(), LC_THREAD_datas[thread_idx]);
5944                 break;
5945 
5946               case llvm::MachO::CPU_TYPE_I386:
5947                 RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
5948                     thread_sp.get(), LC_THREAD_datas[thread_idx]);
5949                 break;
5950 
5951               case llvm::MachO::CPU_TYPE_X86_64:
5952                 RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
5953                     thread_sp.get(), LC_THREAD_datas[thread_idx]);
5954                 break;
5955               }
5956             }
5957           }
5958 
5959           // The size of the load command is the size of the segments...
5960           if (addr_byte_size == 8) {
5961             mach_header.sizeofcmds = segment_load_commands.size() *
5962                                      sizeof(struct segment_command_64);
5963           } else {
5964             mach_header.sizeofcmds =
5965                 segment_load_commands.size() * sizeof(struct segment_command);
5966           }
5967 
5968           // and the size of all LC_THREAD load command
5969           for (const auto &LC_THREAD_data : LC_THREAD_datas) {
5970             ++mach_header.ncmds;
5971             mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
5972           }
5973 
5974           printf("mach_header: 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x "
5975                  "0x%8.8x 0x%8.8x\n",
5976                  mach_header.magic, mach_header.cputype, mach_header.cpusubtype,
5977                  mach_header.filetype, mach_header.ncmds,
5978                  mach_header.sizeofcmds, mach_header.flags,
5979                  mach_header.reserved);
5980 
5981           // Write the mach header
5982           buffer.PutHex32(mach_header.magic);
5983           buffer.PutHex32(mach_header.cputype);
5984           buffer.PutHex32(mach_header.cpusubtype);
5985           buffer.PutHex32(mach_header.filetype);
5986           buffer.PutHex32(mach_header.ncmds);
5987           buffer.PutHex32(mach_header.sizeofcmds);
5988           buffer.PutHex32(mach_header.flags);
5989           if (addr_byte_size == 8) {
5990             buffer.PutHex32(mach_header.reserved);
5991           }
5992 
5993           // Skip the mach header and all load commands and align to the next
5994           // 0x1000 byte boundary
5995           addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
5996           if (file_offset & 0x00000fff) {
5997             file_offset += 0x00001000ull;
5998             file_offset &= (~0x00001000ull + 1);
5999           }
6000 
6001           for (auto &segment : segment_load_commands) {
6002             segment.fileoff = file_offset;
6003             file_offset += segment.filesize;
6004           }
6005 
6006           // Write out all of the LC_THREAD load commands
6007           for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6008             const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6009             buffer.PutHex32(LC_THREAD);
6010             buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
6011             buffer.Write(LC_THREAD_data.GetString().data(),
6012                          LC_THREAD_data_size);
6013           }
6014 
6015           // Write out all of the segment load commands
6016           for (const auto &segment : segment_load_commands) {
6017             printf("0x%8.8x 0x%8.8x [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
6018                    ") [0x%16.16" PRIx64 " 0x%16.16" PRIx64
6019                    ") 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x]\n",
6020                    segment.cmd, segment.cmdsize, segment.vmaddr,
6021                    segment.vmaddr + segment.vmsize, segment.fileoff,
6022                    segment.filesize, segment.maxprot, segment.initprot,
6023                    segment.nsects, segment.flags);
6024 
6025             buffer.PutHex32(segment.cmd);
6026             buffer.PutHex32(segment.cmdsize);
6027             buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
6028             if (addr_byte_size == 8) {
6029               buffer.PutHex64(segment.vmaddr);
6030               buffer.PutHex64(segment.vmsize);
6031               buffer.PutHex64(segment.fileoff);
6032               buffer.PutHex64(segment.filesize);
6033             } else {
6034               buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
6035               buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
6036               buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
6037               buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
6038             }
6039             buffer.PutHex32(segment.maxprot);
6040             buffer.PutHex32(segment.initprot);
6041             buffer.PutHex32(segment.nsects);
6042             buffer.PutHex32(segment.flags);
6043           }
6044 
6045           File core_file;
6046           std::string core_file_path(outfile.GetPath());
6047           error = core_file.Open(core_file_path.c_str(),
6048                                  File::eOpenOptionWrite |
6049                                      File::eOpenOptionTruncate |
6050                                      File::eOpenOptionCanCreate);
6051           if (error.Success()) {
6052             // Read 1 page at a time
6053             uint8_t bytes[0x1000];
6054             // Write the mach header and load commands out to the core file
6055             size_t bytes_written = buffer.GetString().size();
6056             error = core_file.Write(buffer.GetString().data(), bytes_written);
6057             if (error.Success()) {
6058               // Now write the file data for all memory segments in the process
6059               for (const auto &segment : segment_load_commands) {
6060                 if (core_file.SeekFromStart(segment.fileoff) == -1) {
6061                   error.SetErrorStringWithFormat(
6062                       "unable to seek to offset 0x%" PRIx64 " in '%s'",
6063                       segment.fileoff, core_file_path.c_str());
6064                   break;
6065                 }
6066 
6067                 printf("Saving %" PRId64
6068                        " bytes of data for memory region at 0x%" PRIx64 "\n",
6069                        segment.vmsize, segment.vmaddr);
6070                 addr_t bytes_left = segment.vmsize;
6071                 addr_t addr = segment.vmaddr;
6072                 Error memory_read_error;
6073                 while (bytes_left > 0 && error.Success()) {
6074                   const size_t bytes_to_read =
6075                       bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6076                   const size_t bytes_read = process_sp->ReadMemory(
6077                       addr, bytes, bytes_to_read, memory_read_error);
6078                   if (bytes_read == bytes_to_read) {
6079                     size_t bytes_written = bytes_read;
6080                     error = core_file.Write(bytes, bytes_written);
6081                     bytes_left -= bytes_read;
6082                     addr += bytes_read;
6083                   } else {
6084                     // Some pages within regions are not readable, those
6085                     // should be zero filled
6086                     memset(bytes, 0, bytes_to_read);
6087                     size_t bytes_written = bytes_to_read;
6088                     error = core_file.Write(bytes, bytes_written);
6089                     bytes_left -= bytes_to_read;
6090                     addr += bytes_to_read;
6091                   }
6092                 }
6093               }
6094             }
6095           }
6096         } else {
6097           error.SetErrorString(
6098               "process doesn't support getting memory region info");
6099         }
6100       }
6101       return true; // This is the right plug to handle saving core files for
6102                    // this process
6103     }
6104   }
6105   return false;
6106 }
6107