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