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