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