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