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