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