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     LLDB_LOGF(log, "Shared cache %s has UUID %s",
2107               dyld_shared_cache.GetPath().c_str(),
2108               dsc_uuid.GetAsString().c_str());
2109   }
2110   return dsc_uuid;
2111 }
2112 
2113 size_t ObjectFileMachO::ParseSymtab() {
2114   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2115   Timer scoped_timer(func_cat, "ObjectFileMachO::ParseSymtab () module = %s",
2116                      m_file.GetFilename().AsCString(""));
2117   ModuleSP module_sp(GetModule());
2118   if (!module_sp)
2119     return 0;
2120 
2121   struct symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
2122   struct linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
2123   struct dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2124   typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2125   FunctionStarts function_starts;
2126   lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
2127   uint32_t i;
2128   FileSpecList dylib_files;
2129   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
2130   static const llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2131   static const llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
2132   static const llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2133 
2134   for (i = 0; i < m_header.ncmds; ++i) {
2135     const lldb::offset_t cmd_offset = offset;
2136     // Read in the load command and load command size
2137     struct load_command lc;
2138     if (m_data.GetU32(&offset, &lc, 2) == nullptr)
2139       break;
2140     // Watch for the symbol table load command
2141     switch (lc.cmd) {
2142     case LC_SYMTAB:
2143       symtab_load_command.cmd = lc.cmd;
2144       symtab_load_command.cmdsize = lc.cmdsize;
2145       // Read in the rest of the symtab load command
2146       if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
2147           nullptr) // fill in symoff, nsyms, stroff, strsize fields
2148         return 0;
2149       if (symtab_load_command.symoff == 0) {
2150         if (log)
2151           module_sp->LogMessage(log, "LC_SYMTAB.symoff == 0");
2152         return 0;
2153       }
2154 
2155       if (symtab_load_command.stroff == 0) {
2156         if (log)
2157           module_sp->LogMessage(log, "LC_SYMTAB.stroff == 0");
2158         return 0;
2159       }
2160 
2161       if (symtab_load_command.nsyms == 0) {
2162         if (log)
2163           module_sp->LogMessage(log, "LC_SYMTAB.nsyms == 0");
2164         return 0;
2165       }
2166 
2167       if (symtab_load_command.strsize == 0) {
2168         if (log)
2169           module_sp->LogMessage(log, "LC_SYMTAB.strsize == 0");
2170         return 0;
2171       }
2172       break;
2173 
2174     case LC_DYLD_INFO:
2175     case LC_DYLD_INFO_ONLY:
2176       if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
2177         dyld_info.cmd = lc.cmd;
2178         dyld_info.cmdsize = lc.cmdsize;
2179       } else {
2180         memset(&dyld_info, 0, sizeof(dyld_info));
2181       }
2182       break;
2183 
2184     case LC_LOAD_DYLIB:
2185     case LC_LOAD_WEAK_DYLIB:
2186     case LC_REEXPORT_DYLIB:
2187     case LC_LOADFVMLIB:
2188     case LC_LOAD_UPWARD_DYLIB: {
2189       uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
2190       const char *path = m_data.PeekCStr(name_offset);
2191       if (path) {
2192         FileSpec file_spec(path);
2193         // Strip the path if there is @rpath, @executable, etc so we just use
2194         // the basename
2195         if (path[0] == '@')
2196           file_spec.GetDirectory().Clear();
2197 
2198         if (lc.cmd == LC_REEXPORT_DYLIB) {
2199           m_reexported_dylibs.AppendIfUnique(file_spec);
2200         }
2201 
2202         dylib_files.Append(file_spec);
2203       }
2204     } break;
2205 
2206     case LC_FUNCTION_STARTS:
2207       function_starts_load_command.cmd = lc.cmd;
2208       function_starts_load_command.cmdsize = lc.cmdsize;
2209       if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
2210           nullptr) // fill in symoff, nsyms, stroff, strsize fields
2211         memset(&function_starts_load_command, 0,
2212                sizeof(function_starts_load_command));
2213       break;
2214 
2215     default:
2216       break;
2217     }
2218     offset = cmd_offset + lc.cmdsize;
2219   }
2220 
2221   if (symtab_load_command.cmd) {
2222     Symtab *symtab = m_symtab_up.get();
2223     SectionList *section_list = GetSectionList();
2224     if (section_list == nullptr)
2225       return 0;
2226 
2227     const uint32_t addr_byte_size = m_data.GetAddressByteSize();
2228     const ByteOrder byte_order = m_data.GetByteOrder();
2229     bool bit_width_32 = addr_byte_size == 4;
2230     const size_t nlist_byte_size =
2231         bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2232 
2233     DataExtractor nlist_data(nullptr, 0, byte_order, addr_byte_size);
2234     DataExtractor strtab_data(nullptr, 0, byte_order, addr_byte_size);
2235     DataExtractor function_starts_data(nullptr, 0, byte_order, addr_byte_size);
2236     DataExtractor indirect_symbol_index_data(nullptr, 0, byte_order,
2237                                              addr_byte_size);
2238     DataExtractor dyld_trie_data(nullptr, 0, byte_order, addr_byte_size);
2239 
2240     const addr_t nlist_data_byte_size =
2241         symtab_load_command.nsyms * nlist_byte_size;
2242     const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2243     addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2244 
2245     ProcessSP process_sp(m_process_wp.lock());
2246     Process *process = process_sp.get();
2247 
2248     uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2249 
2250     if (process && m_header.filetype != llvm::MachO::MH_OBJECT) {
2251       Target &target = process->GetTarget();
2252 
2253       memory_module_load_level = target.GetMemoryModuleLoadLevel();
2254 
2255       SectionSP linkedit_section_sp(
2256           section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
2257       // Reading mach file from memory in a process or core file...
2258 
2259       if (linkedit_section_sp) {
2260         addr_t linkedit_load_addr =
2261             linkedit_section_sp->GetLoadBaseAddress(&target);
2262         if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2263           // We might be trying to access the symbol table before the
2264           // __LINKEDIT's load address has been set in the target. We can't
2265           // fail to read the symbol table, so calculate the right address
2266           // manually
2267           linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2268               m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2269         }
2270 
2271         const addr_t linkedit_file_offset =
2272             linkedit_section_sp->GetFileOffset();
2273         const addr_t symoff_addr = linkedit_load_addr +
2274                                    symtab_load_command.symoff -
2275                                    linkedit_file_offset;
2276         strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2277                       linkedit_file_offset;
2278 
2279         bool data_was_read = false;
2280 
2281 #if defined(__APPLE__) &&                                                      \
2282     (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2283         if (m_header.flags & 0x80000000u &&
2284             process->GetAddressByteSize() == sizeof(void *)) {
2285           // This mach-o memory file is in the dyld shared cache. If this
2286           // program is not remote and this is iOS, then this process will
2287           // share the same shared cache as the process we are debugging and we
2288           // can read the entire __LINKEDIT from the address space in this
2289           // process. This is a needed optimization that is used for local iOS
2290           // debugging only since all shared libraries in the shared cache do
2291           // not have corresponding files that exist in the file system of the
2292           // device. They have been combined into a single file. This means we
2293           // always have to load these files from memory. All of the symbol and
2294           // string tables from all of the __LINKEDIT sections from the shared
2295           // libraries in the shared cache have been merged into a single large
2296           // symbol and string table. Reading all of this symbol and string
2297           // table data across can slow down debug launch times, so we optimize
2298           // this by reading the memory for the __LINKEDIT section from this
2299           // process.
2300 
2301           UUID lldb_shared_cache;
2302           addr_t lldb_shared_cache_addr;
2303           GetLLDBSharedCacheUUID (lldb_shared_cache_addr, lldb_shared_cache);
2304           UUID process_shared_cache;
2305           addr_t process_shared_cache_addr;
2306           GetProcessSharedCacheUUID(process, process_shared_cache_addr, process_shared_cache);
2307           bool use_lldb_cache = true;
2308           if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() &&
2309               (lldb_shared_cache != process_shared_cache
2310                || process_shared_cache_addr != lldb_shared_cache_addr)) {
2311             use_lldb_cache = false;
2312           }
2313 
2314           PlatformSP platform_sp(target.GetPlatform());
2315           if (platform_sp && platform_sp->IsHost() && use_lldb_cache) {
2316             data_was_read = true;
2317             nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size,
2318                                eByteOrderLittle);
2319             strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size,
2320                                 eByteOrderLittle);
2321             if (function_starts_load_command.cmd) {
2322               const addr_t func_start_addr =
2323                   linkedit_load_addr + function_starts_load_command.dataoff -
2324                   linkedit_file_offset;
2325               function_starts_data.SetData(
2326                   (void *)func_start_addr,
2327                   function_starts_load_command.datasize, eByteOrderLittle);
2328             }
2329           }
2330         }
2331 #endif
2332 
2333         if (!data_was_read) {
2334           // Always load dyld - the dynamic linker - from memory if we didn't
2335           // find a binary anywhere else. lldb will not register
2336           // dylib/framework/bundle loads/unloads if we don't have the dyld
2337           // symbols, we force dyld to load from memory despite the user's
2338           // target.memory-module-load-level setting.
2339           if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2340               m_header.filetype == llvm::MachO::MH_DYLINKER) {
2341             DataBufferSP nlist_data_sp(
2342                 ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
2343             if (nlist_data_sp)
2344               nlist_data.SetData(nlist_data_sp, 0,
2345                                  nlist_data_sp->GetByteSize());
2346             if (m_dysymtab.nindirectsyms != 0) {
2347               const addr_t indirect_syms_addr = linkedit_load_addr +
2348                                                 m_dysymtab.indirectsymoff -
2349                                                 linkedit_file_offset;
2350               DataBufferSP indirect_syms_data_sp(
2351                   ReadMemory(process_sp, indirect_syms_addr,
2352                              m_dysymtab.nindirectsyms * 4));
2353               if (indirect_syms_data_sp)
2354                 indirect_symbol_index_data.SetData(
2355                     indirect_syms_data_sp, 0,
2356                     indirect_syms_data_sp->GetByteSize());
2357               // If this binary is outside the shared cache,
2358               // cache the string table.
2359               // Binaries in the shared cache all share a giant string table, and
2360               // we can't share the string tables across multiple ObjectFileMachO's,
2361               // so we'd end up re-reading this mega-strtab for every binary
2362               // in the shared cache - it would be a big perf problem.
2363               // For binaries outside the shared cache, it's faster to read the
2364               // entire strtab at once instead of piece-by-piece as we process
2365               // the nlist records.
2366               if ((m_header.flags & 0x80000000u) == 0) {
2367                 DataBufferSP strtab_data_sp (ReadMemory (process_sp, strtab_addr,
2368                       strtab_data_byte_size));
2369                 if (strtab_data_sp) {
2370                   strtab_data.SetData (strtab_data_sp, 0, strtab_data_sp->GetByteSize());
2371                 }
2372               }
2373             }
2374           }
2375           if (memory_module_load_level >=
2376                      eMemoryModuleLoadLevelPartial) {
2377             if (function_starts_load_command.cmd) {
2378               const addr_t func_start_addr =
2379                   linkedit_load_addr + function_starts_load_command.dataoff -
2380                   linkedit_file_offset;
2381               DataBufferSP func_start_data_sp(
2382                   ReadMemory(process_sp, func_start_addr,
2383                              function_starts_load_command.datasize));
2384               if (func_start_data_sp)
2385                 function_starts_data.SetData(func_start_data_sp, 0,
2386                                              func_start_data_sp->GetByteSize());
2387             }
2388           }
2389         }
2390       }
2391     } else {
2392       nlist_data.SetData(m_data, symtab_load_command.symoff,
2393                          nlist_data_byte_size);
2394       strtab_data.SetData(m_data, symtab_load_command.stroff,
2395                           strtab_data_byte_size);
2396 
2397       if (dyld_info.export_size > 0) {
2398         dyld_trie_data.SetData(m_data, dyld_info.export_off,
2399                                dyld_info.export_size);
2400       }
2401 
2402       if (m_dysymtab.nindirectsyms != 0) {
2403         indirect_symbol_index_data.SetData(m_data, m_dysymtab.indirectsymoff,
2404                                            m_dysymtab.nindirectsyms * 4);
2405       }
2406       if (function_starts_load_command.cmd) {
2407         function_starts_data.SetData(m_data,
2408                                      function_starts_load_command.dataoff,
2409                                      function_starts_load_command.datasize);
2410       }
2411     }
2412 
2413     if (nlist_data.GetByteSize() == 0 &&
2414         memory_module_load_level == eMemoryModuleLoadLevelComplete) {
2415       if (log)
2416         module_sp->LogMessage(log, "failed to read nlist data");
2417       return 0;
2418     }
2419 
2420     const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2421     if (!have_strtab_data) {
2422       if (process) {
2423         if (strtab_addr == LLDB_INVALID_ADDRESS) {
2424           if (log)
2425             module_sp->LogMessage(log, "failed to locate the strtab in memory");
2426           return 0;
2427         }
2428       } else {
2429         if (log)
2430           module_sp->LogMessage(log, "failed to read strtab data");
2431         return 0;
2432       }
2433     }
2434 
2435     ConstString g_segment_name_TEXT = GetSegmentNameTEXT();
2436     ConstString g_segment_name_DATA = GetSegmentNameDATA();
2437     ConstString g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
2438     ConstString g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
2439     ConstString g_segment_name_OBJC = GetSegmentNameOBJC();
2440     ConstString g_section_name_eh_frame = GetSectionNameEHFrame();
2441     SectionSP text_section_sp(
2442         section_list->FindSectionByName(g_segment_name_TEXT));
2443     SectionSP data_section_sp(
2444         section_list->FindSectionByName(g_segment_name_DATA));
2445     SectionSP data_dirty_section_sp(
2446         section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
2447     SectionSP data_const_section_sp(
2448         section_list->FindSectionByName(g_segment_name_DATA_CONST));
2449     SectionSP objc_section_sp(
2450         section_list->FindSectionByName(g_segment_name_OBJC));
2451     SectionSP eh_frame_section_sp;
2452     if (text_section_sp.get())
2453       eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2454           g_section_name_eh_frame);
2455     else
2456       eh_frame_section_sp =
2457           section_list->FindSectionByName(g_section_name_eh_frame);
2458 
2459     const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
2460 
2461     // lldb works best if it knows the start address of all functions in a
2462     // module. Linker symbols or debug info are normally the best source of
2463     // information for start addr / size but they may be stripped in a released
2464     // binary. Two additional sources of information exist in Mach-O binaries:
2465     //    LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2466     //    function's start address in the
2467     //                         binary, relative to the text section.
2468     //    eh_frame           - the eh_frame FDEs have the start addr & size of
2469     //    each function
2470     //  LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2471     //  all modern binaries.
2472     //  Binaries built to run on older releases may need to use eh_frame
2473     //  information.
2474 
2475     if (text_section_sp && function_starts_data.GetByteSize()) {
2476       FunctionStarts::Entry function_start_entry;
2477       function_start_entry.data = false;
2478       lldb::offset_t function_start_offset = 0;
2479       function_start_entry.addr = text_section_sp->GetFileAddress();
2480       uint64_t delta;
2481       while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
2482              0) {
2483         // Now append the current entry
2484         function_start_entry.addr += delta;
2485         function_starts.Append(function_start_entry);
2486       }
2487     } else {
2488       // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
2489       // load command claiming an eh_frame but it doesn't actually have the
2490       // eh_frame content.  And if we have a dSYM, we don't need to do any of
2491       // this fill-in-the-missing-symbols works anyway - the debug info should
2492       // give us all the functions in the module.
2493       if (text_section_sp.get() && eh_frame_section_sp.get() &&
2494           m_type != eTypeDebugInfo) {
2495         DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
2496                                     DWARFCallFrameInfo::EH);
2497         DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2498         eh_frame.GetFunctionAddressAndSizeVector(functions);
2499         addr_t text_base_addr = text_section_sp->GetFileAddress();
2500         size_t count = functions.GetSize();
2501         for (size_t i = 0; i < count; ++i) {
2502           const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func =
2503               functions.GetEntryAtIndex(i);
2504           if (func) {
2505             FunctionStarts::Entry function_start_entry;
2506             function_start_entry.addr = func->base - text_base_addr;
2507             function_starts.Append(function_start_entry);
2508           }
2509         }
2510       }
2511     }
2512 
2513     const size_t function_starts_count = function_starts.GetSize();
2514 
2515     // For user process binaries (executables, dylibs, frameworks, bundles), if
2516     // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
2517     // going to assume the binary has been stripped.  Don't allow assembly
2518     // language instruction emulation because we don't know proper function
2519     // start boundaries.
2520     //
2521     // For all other types of binaries (kernels, stand-alone bare board
2522     // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
2523     // sections - we should not make any assumptions about them based on that.
2524     if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2525       m_allow_assembly_emulation_unwind_plans = false;
2526       Log *unwind_or_symbol_log(lldb_private::GetLogIfAnyCategoriesSet(
2527           LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_UNWIND));
2528 
2529       if (unwind_or_symbol_log)
2530         module_sp->LogMessage(
2531             unwind_or_symbol_log,
2532             "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2533     }
2534 
2535     const user_id_t TEXT_eh_frame_sectID =
2536         eh_frame_section_sp.get() ? eh_frame_section_sp->GetID()
2537                                   : static_cast<user_id_t>(NO_SECT);
2538 
2539     lldb::offset_t nlist_data_offset = 0;
2540 
2541     uint32_t N_SO_index = UINT32_MAX;
2542 
2543     MachSymtabSectionInfo section_info(section_list);
2544     std::vector<uint32_t> N_FUN_indexes;
2545     std::vector<uint32_t> N_NSYM_indexes;
2546     std::vector<uint32_t> N_INCL_indexes;
2547     std::vector<uint32_t> N_BRAC_indexes;
2548     std::vector<uint32_t> N_COMM_indexes;
2549     typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2550     typedef std::map<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2551     typedef std::map<const char *, uint32_t> ConstNameToSymbolIndexMap;
2552     ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2553     ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2554     ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
2555     // Any symbols that get merged into another will get an entry in this map
2556     // so we know
2557     NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2558     uint32_t nlist_idx = 0;
2559     Symbol *symbol_ptr = nullptr;
2560 
2561     uint32_t sym_idx = 0;
2562     Symbol *sym = nullptr;
2563     size_t num_syms = 0;
2564     std::string memory_symbol_name;
2565     uint32_t unmapped_local_symbols_found = 0;
2566 
2567     std::vector<TrieEntryWithOffset> trie_entries;
2568     std::set<lldb::addr_t> resolver_addresses;
2569 
2570     if (dyld_trie_data.GetByteSize() > 0) {
2571       std::vector<llvm::StringRef> nameSlices;
2572       ParseTrieEntries(dyld_trie_data, 0, is_arm, nameSlices,
2573                        resolver_addresses, trie_entries);
2574 
2575       ConstString text_segment_name("__TEXT");
2576       SectionSP text_segment_sp =
2577           GetSectionList()->FindSectionByName(text_segment_name);
2578       if (text_segment_sp) {
2579         const lldb::addr_t text_segment_file_addr =
2580             text_segment_sp->GetFileAddress();
2581         if (text_segment_file_addr != LLDB_INVALID_ADDRESS) {
2582           for (auto &e : trie_entries)
2583             e.entry.address += text_segment_file_addr;
2584         }
2585       }
2586     }
2587 
2588     typedef std::set<ConstString> IndirectSymbols;
2589     IndirectSymbols indirect_symbol_names;
2590 
2591 #if defined(__APPLE__) &&                                                      \
2592     (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
2593 
2594     // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
2595     // optimized by moving LOCAL symbols out of the memory mapped portion of
2596     // the DSC. The symbol information has all been retained, but it isn't
2597     // available in the normal nlist data. However, there *are* duplicate
2598     // entries of *some*
2599     // LOCAL symbols in the normal nlist data. To handle this situation
2600     // correctly, we must first attempt
2601     // to parse any DSC unmapped symbol information. If we find any, we set a
2602     // flag that tells the normal nlist parser to ignore all LOCAL symbols.
2603 
2604     if (m_header.flags & 0x80000000u) {
2605       // Before we can start mapping the DSC, we need to make certain the
2606       // target process is actually using the cache we can find.
2607 
2608       // Next we need to determine the correct path for the dyld shared cache.
2609 
2610       ArchSpec header_arch;
2611       GetArchitecture(header_arch);
2612       char dsc_path[PATH_MAX];
2613       char dsc_path_development[PATH_MAX];
2614 
2615       snprintf(
2616           dsc_path, sizeof(dsc_path), "%s%s%s",
2617           "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2618                                                        */
2619           "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
2620           header_arch.GetArchitectureName());
2621 
2622       snprintf(
2623           dsc_path_development, sizeof(dsc_path), "%s%s%s%s",
2624           "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2625                                                        */
2626           "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
2627           header_arch.GetArchitectureName(), ".development");
2628 
2629       FileSpec dsc_nondevelopment_filespec(dsc_path, false);
2630       FileSpec dsc_development_filespec(dsc_path_development, false);
2631       FileSpec dsc_filespec;
2632 
2633       UUID dsc_uuid;
2634       UUID process_shared_cache_uuid;
2635       addr_t process_shared_cache_base_addr;
2636 
2637       if (process) {
2638         GetProcessSharedCacheUUID(process, process_shared_cache_base_addr, process_shared_cache_uuid);
2639       }
2640 
2641       // First see if we can find an exact match for the inferior process
2642       // shared cache UUID in the development or non-development shared caches
2643       // on disk.
2644       if (process_shared_cache_uuid.IsValid()) {
2645         if (FileSystem::Instance().Exists(dsc_development_filespec)) {
2646           UUID dsc_development_uuid = GetSharedCacheUUID(
2647               dsc_development_filespec, byte_order, addr_byte_size);
2648           if (dsc_development_uuid.IsValid() &&
2649               dsc_development_uuid == process_shared_cache_uuid) {
2650             dsc_filespec = dsc_development_filespec;
2651             dsc_uuid = dsc_development_uuid;
2652           }
2653         }
2654         if (!dsc_uuid.IsValid() &&
2655             FileSystem::Instance().Exists(dsc_nondevelopment_filespec)) {
2656           UUID dsc_nondevelopment_uuid = GetSharedCacheUUID(
2657               dsc_nondevelopment_filespec, byte_order, addr_byte_size);
2658           if (dsc_nondevelopment_uuid.IsValid() &&
2659               dsc_nondevelopment_uuid == process_shared_cache_uuid) {
2660             dsc_filespec = dsc_nondevelopment_filespec;
2661             dsc_uuid = dsc_nondevelopment_uuid;
2662           }
2663         }
2664       }
2665 
2666       // Failing a UUID match, prefer the development dyld_shared cache if both
2667       // are present.
2668       if (!FileSystem::Instance().Exists(dsc_filespec)) {
2669         if (FileSystem::Instance().Exists(dsc_development_filespec)) {
2670           dsc_filespec = dsc_development_filespec;
2671         } else {
2672           dsc_filespec = dsc_nondevelopment_filespec;
2673         }
2674       }
2675 
2676       /* The dyld_cache_header has a pointer to the
2677          dyld_cache_local_symbols_info structure (localSymbolsOffset).
2678          The dyld_cache_local_symbols_info structure gives us three things:
2679            1. The start and count of the nlist records in the dyld_shared_cache
2680          file
2681            2. The start and size of the strings for these nlist records
2682            3. The start and count of dyld_cache_local_symbols_entry entries
2683 
2684          There is one dyld_cache_local_symbols_entry per dylib/framework in the
2685          dyld shared cache.
2686          The "dylibOffset" field is the Mach-O header of this dylib/framework in
2687          the dyld shared cache.
2688          The dyld_cache_local_symbols_entry also lists the start of this
2689          dylib/framework's nlist records
2690          and the count of how many nlist records there are for this
2691          dylib/framework.
2692       */
2693 
2694       // Process the dyld shared cache header to find the unmapped symbols
2695 
2696       DataBufferSP dsc_data_sp = MapFileData(
2697           dsc_filespec, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
2698       if (!dsc_uuid.IsValid()) {
2699         dsc_uuid = GetSharedCacheUUID(dsc_filespec, byte_order, addr_byte_size);
2700       }
2701       if (dsc_data_sp) {
2702         DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2703 
2704         bool uuid_match = true;
2705         if (dsc_uuid.IsValid() && process) {
2706           if (process_shared_cache_uuid.IsValid() &&
2707               dsc_uuid != process_shared_cache_uuid) {
2708             // The on-disk dyld_shared_cache file is not the same as the one in
2709             // this process' memory, don't use it.
2710             uuid_match = false;
2711             ModuleSP module_sp(GetModule());
2712             if (module_sp)
2713               module_sp->ReportWarning("process shared cache does not match "
2714                                        "on-disk dyld_shared_cache file, some "
2715                                        "symbol names will be missing.");
2716           }
2717         }
2718 
2719         offset = offsetof(struct lldb_copy_dyld_cache_header_v1, mappingOffset);
2720 
2721         uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
2722 
2723         // If the mappingOffset points to a location inside the header, we've
2724         // opened an old dyld shared cache, and should not proceed further.
2725         if (uuid_match &&
2726             mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v1)) {
2727 
2728           DataBufferSP dsc_mapping_info_data_sp = MapFileData(
2729               dsc_filespec, sizeof(struct lldb_copy_dyld_cache_mapping_info),
2730               mappingOffset);
2731 
2732           DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp,
2733                                               byte_order, addr_byte_size);
2734           offset = 0;
2735 
2736           // The File addresses (from the in-memory Mach-O load commands) for
2737           // the shared libraries in the shared library cache need to be
2738           // adjusted by an offset to match up with the dylibOffset identifying
2739           // field in the dyld_cache_local_symbol_entry's.  This offset is
2740           // recorded in mapping_offset_value.
2741           const uint64_t mapping_offset_value =
2742               dsc_mapping_info_data.GetU64(&offset);
2743 
2744           offset = offsetof(struct lldb_copy_dyld_cache_header_v1,
2745                             localSymbolsOffset);
2746           uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2747           uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
2748 
2749           if (localSymbolsOffset && localSymbolsSize) {
2750             // Map the local symbols
2751             DataBufferSP dsc_local_symbols_data_sp =
2752                 MapFileData(dsc_filespec, localSymbolsSize, localSymbolsOffset);
2753 
2754             if (dsc_local_symbols_data_sp) {
2755               DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp,
2756                                                    byte_order, addr_byte_size);
2757 
2758               offset = 0;
2759 
2760               typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
2761               typedef std::map<uint32_t, ConstString> SymbolIndexToName;
2762               UndefinedNameToDescMap undefined_name_to_desc;
2763               SymbolIndexToName reexport_shlib_needs_fixup;
2764 
2765               // Read the local_symbols_infos struct in one shot
2766               struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
2767               dsc_local_symbols_data.GetU32(&offset,
2768                                             &local_symbols_info.nlistOffset, 6);
2769 
2770               SectionSP text_section_sp(
2771                   section_list->FindSectionByName(GetSegmentNameTEXT()));
2772 
2773               uint32_t header_file_offset =
2774                   (text_section_sp->GetFileAddress() - mapping_offset_value);
2775 
2776               offset = local_symbols_info.entriesOffset;
2777               for (uint32_t entry_index = 0;
2778                    entry_index < local_symbols_info.entriesCount;
2779                    entry_index++) {
2780                 struct lldb_copy_dyld_cache_local_symbols_entry
2781                     local_symbols_entry;
2782                 local_symbols_entry.dylibOffset =
2783                     dsc_local_symbols_data.GetU32(&offset);
2784                 local_symbols_entry.nlistStartIndex =
2785                     dsc_local_symbols_data.GetU32(&offset);
2786                 local_symbols_entry.nlistCount =
2787                     dsc_local_symbols_data.GetU32(&offset);
2788 
2789                 if (header_file_offset == local_symbols_entry.dylibOffset) {
2790                   unmapped_local_symbols_found = local_symbols_entry.nlistCount;
2791 
2792                   // The normal nlist code cannot correctly size the Symbols
2793                   // array, we need to allocate it here.
2794                   sym = symtab->Resize(
2795                       symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2796                       unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2797                   num_syms = symtab->GetNumSymbols();
2798 
2799                   nlist_data_offset =
2800                       local_symbols_info.nlistOffset +
2801                       (nlist_byte_size * local_symbols_entry.nlistStartIndex);
2802                   uint32_t string_table_offset =
2803                       local_symbols_info.stringsOffset;
2804 
2805                   for (uint32_t nlist_index = 0;
2806                        nlist_index < local_symbols_entry.nlistCount;
2807                        nlist_index++) {
2808                     /////////////////////////////
2809                     {
2810                       struct nlist_64 nlist;
2811                       if (!dsc_local_symbols_data.ValidOffsetForDataOfSize(
2812                               nlist_data_offset, nlist_byte_size))
2813                         break;
2814 
2815                       nlist.n_strx = dsc_local_symbols_data.GetU32_unchecked(
2816                           &nlist_data_offset);
2817                       nlist.n_type = dsc_local_symbols_data.GetU8_unchecked(
2818                           &nlist_data_offset);
2819                       nlist.n_sect = dsc_local_symbols_data.GetU8_unchecked(
2820                           &nlist_data_offset);
2821                       nlist.n_desc = dsc_local_symbols_data.GetU16_unchecked(
2822                           &nlist_data_offset);
2823                       nlist.n_value =
2824                           dsc_local_symbols_data.GetAddress_unchecked(
2825                               &nlist_data_offset);
2826 
2827                       SymbolType type = eSymbolTypeInvalid;
2828                       const char *symbol_name = dsc_local_symbols_data.PeekCStr(
2829                           string_table_offset + nlist.n_strx);
2830 
2831                       if (symbol_name == NULL) {
2832                         // No symbol should be NULL, even the symbols with no
2833                         // string values should have an offset zero which
2834                         // points to an empty C-string
2835                         Host::SystemLog(
2836                             Host::eSystemLogError,
2837                             "error: DSC unmapped local symbol[%u] has invalid "
2838                             "string table offset 0x%x in %s, ignoring symbol\n",
2839                             entry_index, nlist.n_strx,
2840                             module_sp->GetFileSpec().GetPath().c_str());
2841                         continue;
2842                       }
2843                       if (symbol_name[0] == '\0')
2844                         symbol_name = NULL;
2845 
2846                       const char *symbol_name_non_abi_mangled = NULL;
2847 
2848                       SectionSP symbol_section;
2849                       uint32_t symbol_byte_size = 0;
2850                       bool add_nlist = true;
2851                       bool is_debug = ((nlist.n_type & N_STAB) != 0);
2852                       bool demangled_is_synthesized = false;
2853                       bool is_gsym = false;
2854                       bool set_value = true;
2855 
2856                       assert(sym_idx < num_syms);
2857 
2858                       sym[sym_idx].SetDebug(is_debug);
2859 
2860                       if (is_debug) {
2861                         switch (nlist.n_type) {
2862                         case N_GSYM:
2863                           // global symbol: name,,NO_SECT,type,0
2864                           // Sometimes the N_GSYM value contains the address.
2865 
2866                           // FIXME: In the .o files, we have a GSYM and a debug
2867                           // symbol for all the ObjC data.  They
2868                           // have the same address, but we want to ensure that
2869                           // we always find only the real symbol, 'cause we
2870                           // don't currently correctly attribute the
2871                           // GSYM one to the ObjCClass/Ivar/MetaClass
2872                           // symbol type.  This is a temporary hack to make
2873                           // sure the ObjectiveC symbols get treated correctly.
2874                           // To do this right, we should coalesce all the GSYM
2875                           // & global symbols that have the same address.
2876 
2877                           is_gsym = true;
2878                           sym[sym_idx].SetExternal(true);
2879 
2880                           if (symbol_name && symbol_name[0] == '_' &&
2881                               symbol_name[1] == 'O') {
2882                             llvm::StringRef symbol_name_ref(symbol_name);
2883                             if (symbol_name_ref.startswith(
2884                                     g_objc_v2_prefix_class)) {
2885                               symbol_name_non_abi_mangled = symbol_name + 1;
2886                               symbol_name =
2887                                   symbol_name + g_objc_v2_prefix_class.size();
2888                               type = eSymbolTypeObjCClass;
2889                               demangled_is_synthesized = true;
2890 
2891                             } else if (symbol_name_ref.startswith(
2892                                            g_objc_v2_prefix_metaclass)) {
2893                               symbol_name_non_abi_mangled = symbol_name + 1;
2894                               symbol_name = symbol_name +
2895                                             g_objc_v2_prefix_metaclass.size();
2896                               type = eSymbolTypeObjCMetaClass;
2897                               demangled_is_synthesized = true;
2898                             } else if (symbol_name_ref.startswith(
2899                                            g_objc_v2_prefix_ivar)) {
2900                               symbol_name_non_abi_mangled = symbol_name + 1;
2901                               symbol_name =
2902                                   symbol_name + g_objc_v2_prefix_ivar.size();
2903                               type = eSymbolTypeObjCIVar;
2904                               demangled_is_synthesized = true;
2905                             }
2906                           } else {
2907                             if (nlist.n_value != 0)
2908                               symbol_section = section_info.GetSection(
2909                                   nlist.n_sect, nlist.n_value);
2910                             type = eSymbolTypeData;
2911                           }
2912                           break;
2913 
2914                         case N_FNAME:
2915                           // procedure name (f77 kludge): name,,NO_SECT,0,0
2916                           type = eSymbolTypeCompiler;
2917                           break;
2918 
2919                         case N_FUN:
2920                           // procedure: name,,n_sect,linenumber,address
2921                           if (symbol_name) {
2922                             type = eSymbolTypeCode;
2923                             symbol_section = section_info.GetSection(
2924                                 nlist.n_sect, nlist.n_value);
2925 
2926                             N_FUN_addr_to_sym_idx.insert(
2927                                 std::make_pair(nlist.n_value, sym_idx));
2928                             // We use the current number of symbols in the
2929                             // symbol table in lieu of using nlist_idx in case
2930                             // we ever start trimming entries out
2931                             N_FUN_indexes.push_back(sym_idx);
2932                           } else {
2933                             type = eSymbolTypeCompiler;
2934 
2935                             if (!N_FUN_indexes.empty()) {
2936                               // Copy the size of the function into the
2937                               // original
2938                               // STAB entry so we don't have
2939                               // to hunt for it later
2940                               symtab->SymbolAtIndex(N_FUN_indexes.back())
2941                                   ->SetByteSize(nlist.n_value);
2942                               N_FUN_indexes.pop_back();
2943                               // We don't really need the end function STAB as
2944                               // it contains the size which we already placed
2945                               // with the original symbol, so don't add it if
2946                               // we want a minimal symbol table
2947                               add_nlist = false;
2948                             }
2949                           }
2950                           break;
2951 
2952                         case N_STSYM:
2953                           // static symbol: name,,n_sect,type,address
2954                           N_STSYM_addr_to_sym_idx.insert(
2955                               std::make_pair(nlist.n_value, sym_idx));
2956                           symbol_section = section_info.GetSection(
2957                               nlist.n_sect, nlist.n_value);
2958                           if (symbol_name && symbol_name[0]) {
2959                             type = ObjectFile::GetSymbolTypeFromName(
2960                                 symbol_name + 1, eSymbolTypeData);
2961                           }
2962                           break;
2963 
2964                         case N_LCSYM:
2965                           // .lcomm symbol: name,,n_sect,type,address
2966                           symbol_section = section_info.GetSection(
2967                               nlist.n_sect, nlist.n_value);
2968                           type = eSymbolTypeCommonBlock;
2969                           break;
2970 
2971                         case N_BNSYM:
2972                           // We use the current number of symbols in the symbol
2973                           // table in lieu of using nlist_idx in case we ever
2974                           // start trimming entries out Skip these if we want
2975                           // minimal symbol tables
2976                           add_nlist = false;
2977                           break;
2978 
2979                         case N_ENSYM:
2980                           // Set the size of the N_BNSYM to the terminating
2981                           // index of this N_ENSYM so that we can always skip
2982                           // the entire symbol if we need to navigate more
2983                           // quickly at the source level when parsing STABS
2984                           // Skip these if we want minimal symbol tables
2985                           add_nlist = false;
2986                           break;
2987 
2988                         case N_OPT:
2989                           // emitted with gcc2_compiled and in gcc source
2990                           type = eSymbolTypeCompiler;
2991                           break;
2992 
2993                         case N_RSYM:
2994                           // register sym: name,,NO_SECT,type,register
2995                           type = eSymbolTypeVariable;
2996                           break;
2997 
2998                         case N_SLINE:
2999                           // src line: 0,,n_sect,linenumber,address
3000                           symbol_section = section_info.GetSection(
3001                               nlist.n_sect, nlist.n_value);
3002                           type = eSymbolTypeLineEntry;
3003                           break;
3004 
3005                         case N_SSYM:
3006                           // structure elt: name,,NO_SECT,type,struct_offset
3007                           type = eSymbolTypeVariableType;
3008                           break;
3009 
3010                         case N_SO:
3011                           // source file name
3012                           type = eSymbolTypeSourceFile;
3013                           if (symbol_name == NULL) {
3014                             add_nlist = false;
3015                             if (N_SO_index != UINT32_MAX) {
3016                               // Set the size of the N_SO to the terminating
3017                               // index of this N_SO so that we can always skip
3018                               // the entire N_SO if we need to navigate more
3019                               // quickly at the source level when parsing STABS
3020                               symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3021                               symbol_ptr->SetByteSize(sym_idx);
3022                               symbol_ptr->SetSizeIsSibling(true);
3023                             }
3024                             N_NSYM_indexes.clear();
3025                             N_INCL_indexes.clear();
3026                             N_BRAC_indexes.clear();
3027                             N_COMM_indexes.clear();
3028                             N_FUN_indexes.clear();
3029                             N_SO_index = UINT32_MAX;
3030                           } else {
3031                             // We use the current number of symbols in the
3032                             // symbol table in lieu of using nlist_idx in case
3033                             // we ever start trimming entries out
3034                             const bool N_SO_has_full_path =
3035                                 symbol_name[0] == '/';
3036                             if (N_SO_has_full_path) {
3037                               if ((N_SO_index == sym_idx - 1) &&
3038                                   ((sym_idx - 1) < num_syms)) {
3039                                 // We have two consecutive N_SO entries where
3040                                 // the first contains a directory and the
3041                                 // second contains a full path.
3042                                 sym[sym_idx - 1].GetMangled().SetValue(
3043                                     ConstString(symbol_name), false);
3044                                 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3045                                 add_nlist = false;
3046                               } else {
3047                                 // This is the first entry in a N_SO that
3048                                 // contains a directory or
3049                                 // a full path to the source file
3050                                 N_SO_index = sym_idx;
3051                               }
3052                             } else if ((N_SO_index == sym_idx - 1) &&
3053                                        ((sym_idx - 1) < num_syms)) {
3054                               // This is usually the second N_SO entry that
3055                               // contains just the filename, so here we combine
3056                               // it with the first one if we are minimizing the
3057                               // symbol table
3058                               const char *so_path =
3059                                   sym[sym_idx - 1]
3060                                       .GetMangled()
3061                                       .GetDemangledName(
3062                                           lldb::eLanguageTypeUnknown)
3063                                       .AsCString();
3064                               if (so_path && so_path[0]) {
3065                                 std::string full_so_path(so_path);
3066                                 const size_t double_slash_pos =
3067                                     full_so_path.find("//");
3068                                 if (double_slash_pos != std::string::npos) {
3069                                   // The linker has been generating bad N_SO
3070                                   // entries with doubled up paths
3071                                   // in the format "%s%s" where the first
3072                                   // string in the DW_AT_comp_dir, and the
3073                                   // second is the directory for the source
3074                                   // file so you end up with a path that looks
3075                                   // like "/tmp/src//tmp/src/"
3076                                   FileSpec so_dir(so_path, false);
3077                                   if (!FileSystem::Instance().Exists(so_dir)) {
3078                                     so_dir.SetFile(
3079                                         &full_so_path[double_slash_pos + 1],
3080                                         false);
3081                                     if (FileSystem::Instance().Exists(so_dir)) {
3082                                       // Trim off the incorrect path
3083                                       full_so_path.erase(0,
3084                                                          double_slash_pos + 1);
3085                                     }
3086                                   }
3087                                 }
3088                                 if (*full_so_path.rbegin() != '/')
3089                                   full_so_path += '/';
3090                                 full_so_path += symbol_name;
3091                                 sym[sym_idx - 1].GetMangled().SetValue(
3092                                     ConstString(full_so_path.c_str()), false);
3093                                 add_nlist = false;
3094                                 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3095                               }
3096                             } else {
3097                               // This could be a relative path to a N_SO
3098                               N_SO_index = sym_idx;
3099                             }
3100                           }
3101                           break;
3102 
3103                         case N_OSO:
3104                           // object file name: name,,0,0,st_mtime
3105                           type = eSymbolTypeObjectFile;
3106                           break;
3107 
3108                         case N_LSYM:
3109                           // local sym: name,,NO_SECT,type,offset
3110                           type = eSymbolTypeLocal;
3111                           break;
3112 
3113                         // INCL scopes
3114                         case N_BINCL:
3115                           // include file beginning: name,,NO_SECT,0,sum We use
3116                           // the current number of symbols in the symbol table
3117                           // in lieu of using nlist_idx in case we ever start
3118                           // trimming entries out
3119                           N_INCL_indexes.push_back(sym_idx);
3120                           type = eSymbolTypeScopeBegin;
3121                           break;
3122 
3123                         case N_EINCL:
3124                           // include file end: name,,NO_SECT,0,0
3125                           // Set the size of the N_BINCL to the terminating
3126                           // index of this N_EINCL so that we can always skip
3127                           // the entire symbol if we need to navigate more
3128                           // quickly at the source level when parsing STABS
3129                           if (!N_INCL_indexes.empty()) {
3130                             symbol_ptr =
3131                                 symtab->SymbolAtIndex(N_INCL_indexes.back());
3132                             symbol_ptr->SetByteSize(sym_idx + 1);
3133                             symbol_ptr->SetSizeIsSibling(true);
3134                             N_INCL_indexes.pop_back();
3135                           }
3136                           type = eSymbolTypeScopeEnd;
3137                           break;
3138 
3139                         case N_SOL:
3140                           // #included file name: name,,n_sect,0,address
3141                           type = eSymbolTypeHeaderFile;
3142 
3143                           // We currently don't use the header files on darwin
3144                           add_nlist = false;
3145                           break;
3146 
3147                         case N_PARAMS:
3148                           // compiler parameters: name,,NO_SECT,0,0
3149                           type = eSymbolTypeCompiler;
3150                           break;
3151 
3152                         case N_VERSION:
3153                           // compiler version: name,,NO_SECT,0,0
3154                           type = eSymbolTypeCompiler;
3155                           break;
3156 
3157                         case N_OLEVEL:
3158                           // compiler -O level: name,,NO_SECT,0,0
3159                           type = eSymbolTypeCompiler;
3160                           break;
3161 
3162                         case N_PSYM:
3163                           // parameter: name,,NO_SECT,type,offset
3164                           type = eSymbolTypeVariable;
3165                           break;
3166 
3167                         case N_ENTRY:
3168                           // alternate entry: name,,n_sect,linenumber,address
3169                           symbol_section = section_info.GetSection(
3170                               nlist.n_sect, nlist.n_value);
3171                           type = eSymbolTypeLineEntry;
3172                           break;
3173 
3174                         // Left and Right Braces
3175                         case N_LBRAC:
3176                           // left bracket: 0,,NO_SECT,nesting level,address We
3177                           // use the current number of symbols in the symbol
3178                           // table in lieu of using nlist_idx in case we ever
3179                           // start trimming entries out
3180                           symbol_section = section_info.GetSection(
3181                               nlist.n_sect, nlist.n_value);
3182                           N_BRAC_indexes.push_back(sym_idx);
3183                           type = eSymbolTypeScopeBegin;
3184                           break;
3185 
3186                         case N_RBRAC:
3187                           // right bracket: 0,,NO_SECT,nesting level,address
3188                           // Set the size of the N_LBRAC to the terminating
3189                           // index of this N_RBRAC so that we can always skip
3190                           // the entire symbol if we need to navigate more
3191                           // quickly at the source level when parsing STABS
3192                           symbol_section = section_info.GetSection(
3193                               nlist.n_sect, nlist.n_value);
3194                           if (!N_BRAC_indexes.empty()) {
3195                             symbol_ptr =
3196                                 symtab->SymbolAtIndex(N_BRAC_indexes.back());
3197                             symbol_ptr->SetByteSize(sym_idx + 1);
3198                             symbol_ptr->SetSizeIsSibling(true);
3199                             N_BRAC_indexes.pop_back();
3200                           }
3201                           type = eSymbolTypeScopeEnd;
3202                           break;
3203 
3204                         case N_EXCL:
3205                           // deleted include file: name,,NO_SECT,0,sum
3206                           type = eSymbolTypeHeaderFile;
3207                           break;
3208 
3209                         // COMM scopes
3210                         case N_BCOMM:
3211                           // begin common: name,,NO_SECT,0,0
3212                           // We use the current number of symbols in the symbol
3213                           // table in lieu of using nlist_idx in case we ever
3214                           // start trimming entries out
3215                           type = eSymbolTypeScopeBegin;
3216                           N_COMM_indexes.push_back(sym_idx);
3217                           break;
3218 
3219                         case N_ECOML:
3220                           // end common (local name): 0,,n_sect,0,address
3221                           symbol_section = section_info.GetSection(
3222                               nlist.n_sect, nlist.n_value);
3223                         // Fall through
3224 
3225                         case N_ECOMM:
3226                           // end common: name,,n_sect,0,0
3227                           // Set the size of the N_BCOMM to the terminating
3228                           // index of this N_ECOMM/N_ECOML so that we can
3229                           // always skip the entire symbol if we need to
3230                           // navigate more quickly at the source level when
3231                           // parsing STABS
3232                           if (!N_COMM_indexes.empty()) {
3233                             symbol_ptr =
3234                                 symtab->SymbolAtIndex(N_COMM_indexes.back());
3235                             symbol_ptr->SetByteSize(sym_idx + 1);
3236                             symbol_ptr->SetSizeIsSibling(true);
3237                             N_COMM_indexes.pop_back();
3238                           }
3239                           type = eSymbolTypeScopeEnd;
3240                           break;
3241 
3242                         case N_LENG:
3243                           // second stab entry with length information
3244                           type = eSymbolTypeAdditional;
3245                           break;
3246 
3247                         default:
3248                           break;
3249                         }
3250                       } else {
3251                         // uint8_t n_pext    = N_PEXT & nlist.n_type;
3252                         uint8_t n_type = N_TYPE & nlist.n_type;
3253                         sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
3254 
3255                         switch (n_type) {
3256                         case N_INDR: {
3257                           const char *reexport_name_cstr =
3258                               strtab_data.PeekCStr(nlist.n_value);
3259                           if (reexport_name_cstr && reexport_name_cstr[0]) {
3260                             type = eSymbolTypeReExported;
3261                             ConstString reexport_name(
3262                                 reexport_name_cstr +
3263                                 ((reexport_name_cstr[0] == '_') ? 1 : 0));
3264                             sym[sym_idx].SetReExportedSymbolName(reexport_name);
3265                             set_value = false;
3266                             reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3267                             indirect_symbol_names.insert(
3268                                 ConstString(symbol_name +
3269                                             ((symbol_name[0] == '_') ? 1 : 0)));
3270                           } else
3271                             type = eSymbolTypeUndefined;
3272                         } break;
3273 
3274                         case N_UNDF:
3275                           if (symbol_name && symbol_name[0]) {
3276                             ConstString undefined_name(
3277                                 symbol_name +
3278                                 ((symbol_name[0] == '_') ? 1 : 0));
3279                             undefined_name_to_desc[undefined_name] =
3280                                 nlist.n_desc;
3281                           }
3282                         // Fall through
3283                         case N_PBUD:
3284                           type = eSymbolTypeUndefined;
3285                           break;
3286 
3287                         case N_ABS:
3288                           type = eSymbolTypeAbsolute;
3289                           break;
3290 
3291                         case N_SECT: {
3292                           symbol_section = section_info.GetSection(
3293                               nlist.n_sect, nlist.n_value);
3294 
3295                           if (symbol_section == NULL) {
3296                             // TODO: warn about this?
3297                             add_nlist = false;
3298                             break;
3299                           }
3300 
3301                           if (TEXT_eh_frame_sectID == nlist.n_sect) {
3302                             type = eSymbolTypeException;
3303                           } else {
3304                             uint32_t section_type =
3305                                 symbol_section->Get() & SECTION_TYPE;
3306 
3307                             switch (section_type) {
3308                             case S_CSTRING_LITERALS:
3309                               type = eSymbolTypeData;
3310                               break; // section with only literal C strings
3311                             case S_4BYTE_LITERALS:
3312                               type = eSymbolTypeData;
3313                               break; // section with only 4 byte literals
3314                             case S_8BYTE_LITERALS:
3315                               type = eSymbolTypeData;
3316                               break; // section with only 8 byte literals
3317                             case S_LITERAL_POINTERS:
3318                               type = eSymbolTypeTrampoline;
3319                               break; // section with only pointers to literals
3320                             case S_NON_LAZY_SYMBOL_POINTERS:
3321                               type = eSymbolTypeTrampoline;
3322                               break; // section with only non-lazy symbol
3323                                      // pointers
3324                             case S_LAZY_SYMBOL_POINTERS:
3325                               type = eSymbolTypeTrampoline;
3326                               break; // section with only lazy symbol pointers
3327                             case S_SYMBOL_STUBS:
3328                               type = eSymbolTypeTrampoline;
3329                               break; // section with only symbol stubs, byte
3330                                      // size of stub in the reserved2 field
3331                             case S_MOD_INIT_FUNC_POINTERS:
3332                               type = eSymbolTypeCode;
3333                               break; // section with only function pointers for
3334                                      // initialization
3335                             case S_MOD_TERM_FUNC_POINTERS:
3336                               type = eSymbolTypeCode;
3337                               break; // section with only function pointers for
3338                                      // termination
3339                             case S_INTERPOSING:
3340                               type = eSymbolTypeTrampoline;
3341                               break; // section with only pairs of function
3342                                      // pointers for interposing
3343                             case S_16BYTE_LITERALS:
3344                               type = eSymbolTypeData;
3345                               break; // section with only 16 byte literals
3346                             case S_DTRACE_DOF:
3347                               type = eSymbolTypeInstrumentation;
3348                               break;
3349                             case S_LAZY_DYLIB_SYMBOL_POINTERS:
3350                               type = eSymbolTypeTrampoline;
3351                               break;
3352                             default:
3353                               switch (symbol_section->GetType()) {
3354                               case lldb::eSectionTypeCode:
3355                                 type = eSymbolTypeCode;
3356                                 break;
3357                               case eSectionTypeData:
3358                               case eSectionTypeDataCString: // Inlined C string
3359                                                             // data
3360                               case eSectionTypeDataCStringPointers: // Pointers
3361                                                                     // to C
3362                                                                     // string
3363                                                                     // data
3364                               case eSectionTypeDataSymbolAddress: // Address of
3365                                                                   // a symbol in
3366                                                                   // the symbol
3367                                                                   // table
3368                               case eSectionTypeData4:
3369                               case eSectionTypeData8:
3370                               case eSectionTypeData16:
3371                                 type = eSymbolTypeData;
3372                                 break;
3373                               default:
3374                                 break;
3375                               }
3376                               break;
3377                             }
3378 
3379                             if (type == eSymbolTypeInvalid) {
3380                               const char *symbol_sect_name =
3381                                   symbol_section->GetName().AsCString();
3382                               if (symbol_section->IsDescendant(
3383                                       text_section_sp.get())) {
3384                                 if (symbol_section->IsClear(
3385                                         S_ATTR_PURE_INSTRUCTIONS |
3386                                         S_ATTR_SELF_MODIFYING_CODE |
3387                                         S_ATTR_SOME_INSTRUCTIONS))
3388                                   type = eSymbolTypeData;
3389                                 else
3390                                   type = eSymbolTypeCode;
3391                               } else if (symbol_section->IsDescendant(
3392                                              data_section_sp.get()) ||
3393                                          symbol_section->IsDescendant(
3394                                              data_dirty_section_sp.get()) ||
3395                                          symbol_section->IsDescendant(
3396                                              data_const_section_sp.get())) {
3397                                 if (symbol_sect_name &&
3398                                     ::strstr(symbol_sect_name, "__objc") ==
3399                                         symbol_sect_name) {
3400                                   type = eSymbolTypeRuntime;
3401 
3402                                   if (symbol_name) {
3403                                     llvm::StringRef symbol_name_ref(
3404                                         symbol_name);
3405                                     if (symbol_name_ref.startswith("_OBJC_")) {
3406                                       static const llvm::StringRef
3407                                           g_objc_v2_prefix_class(
3408                                               "_OBJC_CLASS_$_");
3409                                       static const llvm::StringRef
3410                                           g_objc_v2_prefix_metaclass(
3411                                               "_OBJC_METACLASS_$_");
3412                                       static const llvm::StringRef
3413                                           g_objc_v2_prefix_ivar(
3414                                               "_OBJC_IVAR_$_");
3415                                       if (symbol_name_ref.startswith(
3416                                               g_objc_v2_prefix_class)) {
3417                                         symbol_name_non_abi_mangled =
3418                                             symbol_name + 1;
3419                                         symbol_name =
3420                                             symbol_name +
3421                                             g_objc_v2_prefix_class.size();
3422                                         type = eSymbolTypeObjCClass;
3423                                         demangled_is_synthesized = true;
3424                                       } else if (
3425                                           symbol_name_ref.startswith(
3426                                               g_objc_v2_prefix_metaclass)) {
3427                                         symbol_name_non_abi_mangled =
3428                                             symbol_name + 1;
3429                                         symbol_name =
3430                                             symbol_name +
3431                                             g_objc_v2_prefix_metaclass.size();
3432                                         type = eSymbolTypeObjCMetaClass;
3433                                         demangled_is_synthesized = true;
3434                                       } else if (symbol_name_ref.startswith(
3435                                                      g_objc_v2_prefix_ivar)) {
3436                                         symbol_name_non_abi_mangled =
3437                                             symbol_name + 1;
3438                                         symbol_name =
3439                                             symbol_name +
3440                                             g_objc_v2_prefix_ivar.size();
3441                                         type = eSymbolTypeObjCIVar;
3442                                         demangled_is_synthesized = true;
3443                                       }
3444                                     }
3445                                   }
3446                                 } else if (symbol_sect_name &&
3447                                            ::strstr(symbol_sect_name,
3448                                                     "__gcc_except_tab") ==
3449                                                symbol_sect_name) {
3450                                   type = eSymbolTypeException;
3451                                 } else {
3452                                   type = eSymbolTypeData;
3453                                 }
3454                               } else if (symbol_sect_name &&
3455                                          ::strstr(symbol_sect_name,
3456                                                   "__IMPORT") ==
3457                                              symbol_sect_name) {
3458                                 type = eSymbolTypeTrampoline;
3459                               } else if (symbol_section->IsDescendant(
3460                                              objc_section_sp.get())) {
3461                                 type = eSymbolTypeRuntime;
3462                                 if (symbol_name && symbol_name[0] == '.') {
3463                                   llvm::StringRef symbol_name_ref(symbol_name);
3464                                   static const llvm::StringRef
3465                                       g_objc_v1_prefix_class(
3466                                           ".objc_class_name_");
3467                                   if (symbol_name_ref.startswith(
3468                                           g_objc_v1_prefix_class)) {
3469                                     symbol_name_non_abi_mangled = symbol_name;
3470                                     symbol_name = symbol_name +
3471                                                   g_objc_v1_prefix_class.size();
3472                                     type = eSymbolTypeObjCClass;
3473                                     demangled_is_synthesized = true;
3474                                   }
3475                                 }
3476                               }
3477                             }
3478                           }
3479                         } break;
3480                         }
3481                       }
3482 
3483                       if (add_nlist) {
3484                         uint64_t symbol_value = nlist.n_value;
3485                         if (symbol_name_non_abi_mangled) {
3486                           sym[sym_idx].GetMangled().SetMangledName(
3487                               ConstString(symbol_name_non_abi_mangled));
3488                           sym[sym_idx].GetMangled().SetDemangledName(
3489                               ConstString(symbol_name));
3490                         } else {
3491                           bool symbol_name_is_mangled = false;
3492 
3493                           if (symbol_name && symbol_name[0] == '_') {
3494                             symbol_name_is_mangled = symbol_name[1] == '_';
3495                             symbol_name++; // Skip the leading underscore
3496                           }
3497 
3498                           if (symbol_name) {
3499                             ConstString const_symbol_name(symbol_name);
3500                             sym[sym_idx].GetMangled().SetValue(
3501                                 const_symbol_name, symbol_name_is_mangled);
3502                             if (is_gsym && is_debug) {
3503                               const char *gsym_name =
3504                                   sym[sym_idx]
3505                                       .GetMangled()
3506                                       .GetName(lldb::eLanguageTypeUnknown,
3507                                                Mangled::ePreferMangled)
3508                                       .GetCString();
3509                               if (gsym_name)
3510                                 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3511                             }
3512                           }
3513                         }
3514                         if (symbol_section) {
3515                           const addr_t section_file_addr =
3516                               symbol_section->GetFileAddress();
3517                           if (symbol_byte_size == 0 &&
3518                               function_starts_count > 0) {
3519                             addr_t symbol_lookup_file_addr = nlist.n_value;
3520                             // Do an exact address match for non-ARM addresses,
3521                             // else get the closest since the symbol might be a
3522                             // thumb symbol which has an address with bit zero
3523                             // set
3524                             FunctionStarts::Entry *func_start_entry =
3525                                 function_starts.FindEntry(
3526                                     symbol_lookup_file_addr, !is_arm);
3527                             if (is_arm && func_start_entry) {
3528                               // Verify that the function start address is the
3529                               // symbol address (ARM) or the symbol address + 1
3530                               // (thumb)
3531                               if (func_start_entry->addr !=
3532                                       symbol_lookup_file_addr &&
3533                                   func_start_entry->addr !=
3534                                       (symbol_lookup_file_addr + 1)) {
3535                                 // Not the right entry, NULL it out...
3536                                 func_start_entry = NULL;
3537                               }
3538                             }
3539                             if (func_start_entry) {
3540                               func_start_entry->data = true;
3541 
3542                               addr_t symbol_file_addr = func_start_entry->addr;
3543                               uint32_t symbol_flags = 0;
3544                               if (is_arm) {
3545                                 if (symbol_file_addr & 1)
3546                                   symbol_flags =
3547                                       MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3548                                 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3549                               }
3550 
3551                               const FunctionStarts::Entry
3552                                   *next_func_start_entry =
3553                                       function_starts.FindNextEntry(
3554                                           func_start_entry);
3555                               const addr_t section_end_file_addr =
3556                                   section_file_addr +
3557                                   symbol_section->GetByteSize();
3558                               if (next_func_start_entry) {
3559                                 addr_t next_symbol_file_addr =
3560                                     next_func_start_entry->addr;
3561                                 // Be sure the clear the Thumb address bit when
3562                                 // we calculate the size from the current and
3563                                 // next address
3564                                 if (is_arm)
3565                                   next_symbol_file_addr &=
3566                                       THUMB_ADDRESS_BIT_MASK;
3567                                 symbol_byte_size = std::min<lldb::addr_t>(
3568                                     next_symbol_file_addr - symbol_file_addr,
3569                                     section_end_file_addr - symbol_file_addr);
3570                               } else {
3571                                 symbol_byte_size =
3572                                     section_end_file_addr - symbol_file_addr;
3573                               }
3574                             }
3575                           }
3576                           symbol_value -= section_file_addr;
3577                         }
3578 
3579                         if (is_debug == false) {
3580                           if (type == eSymbolTypeCode) {
3581                             // See if we can find a N_FUN entry for any code
3582                             // symbols. If we do find a match, and the name
3583                             // matches, then we can merge the two into just the
3584                             // function symbol to avoid duplicate entries in
3585                             // the symbol table
3586                             std::pair<ValueToSymbolIndexMap::const_iterator,
3587                                       ValueToSymbolIndexMap::const_iterator>
3588                                 range;
3589                             range = N_FUN_addr_to_sym_idx.equal_range(
3590                                 nlist.n_value);
3591                             if (range.first != range.second) {
3592                               bool found_it = false;
3593                               for (ValueToSymbolIndexMap::const_iterator pos =
3594                                        range.first;
3595                                    pos != range.second; ++pos) {
3596                                 if (sym[sym_idx].GetMangled().GetName(
3597                                         lldb::eLanguageTypeUnknown,
3598                                         Mangled::ePreferMangled) ==
3599                                     sym[pos->second].GetMangled().GetName(
3600                                         lldb::eLanguageTypeUnknown,
3601                                         Mangled::ePreferMangled)) {
3602                                   m_nlist_idx_to_sym_idx[nlist_idx] =
3603                                       pos->second;
3604                                   // We just need the flags from the linker
3605                                   // symbol, so put these flags
3606                                   // into the N_FUN flags to avoid duplicate
3607                                   // symbols in the symbol table
3608                                   sym[pos->second].SetExternal(
3609                                       sym[sym_idx].IsExternal());
3610                                   sym[pos->second].SetFlags(nlist.n_type << 16 |
3611                                                             nlist.n_desc);
3612                                   if (resolver_addresses.find(nlist.n_value) !=
3613                                       resolver_addresses.end())
3614                                     sym[pos->second].SetType(
3615                                         eSymbolTypeResolver);
3616                                   sym[sym_idx].Clear();
3617                                   found_it = true;
3618                                   break;
3619                                 }
3620                               }
3621                               if (found_it)
3622                                 continue;
3623                             } else {
3624                               if (resolver_addresses.find(nlist.n_value) !=
3625                                   resolver_addresses.end())
3626                                 type = eSymbolTypeResolver;
3627                             }
3628                           } else if (type == eSymbolTypeData ||
3629                                      type == eSymbolTypeObjCClass ||
3630                                      type == eSymbolTypeObjCMetaClass ||
3631                                      type == eSymbolTypeObjCIVar) {
3632                             // See if we can find a N_STSYM entry for any data
3633                             // symbols. If we do find a match, and the name
3634                             // matches, then we can merge the two into just the
3635                             // Static symbol to avoid duplicate entries in the
3636                             // symbol table
3637                             std::pair<ValueToSymbolIndexMap::const_iterator,
3638                                       ValueToSymbolIndexMap::const_iterator>
3639                                 range;
3640                             range = N_STSYM_addr_to_sym_idx.equal_range(
3641                                 nlist.n_value);
3642                             if (range.first != range.second) {
3643                               bool found_it = false;
3644                               for (ValueToSymbolIndexMap::const_iterator pos =
3645                                        range.first;
3646                                    pos != range.second; ++pos) {
3647                                 if (sym[sym_idx].GetMangled().GetName(
3648                                         lldb::eLanguageTypeUnknown,
3649                                         Mangled::ePreferMangled) ==
3650                                     sym[pos->second].GetMangled().GetName(
3651                                         lldb::eLanguageTypeUnknown,
3652                                         Mangled::ePreferMangled)) {
3653                                   m_nlist_idx_to_sym_idx[nlist_idx] =
3654                                       pos->second;
3655                                   // We just need the flags from the linker
3656                                   // symbol, so put these flags
3657                                   // into the N_STSYM flags to avoid duplicate
3658                                   // symbols in the symbol table
3659                                   sym[pos->second].SetExternal(
3660                                       sym[sym_idx].IsExternal());
3661                                   sym[pos->second].SetFlags(nlist.n_type << 16 |
3662                                                             nlist.n_desc);
3663                                   sym[sym_idx].Clear();
3664                                   found_it = true;
3665                                   break;
3666                                 }
3667                               }
3668                               if (found_it)
3669                                 continue;
3670                             } else {
3671                               const char *gsym_name =
3672                                   sym[sym_idx]
3673                                       .GetMangled()
3674                                       .GetName(lldb::eLanguageTypeUnknown,
3675                                                Mangled::ePreferMangled)
3676                                       .GetCString();
3677                               if (gsym_name) {
3678                                 // Combine N_GSYM stab entries with the non
3679                                 // stab symbol
3680                                 ConstNameToSymbolIndexMap::const_iterator pos =
3681                                     N_GSYM_name_to_sym_idx.find(gsym_name);
3682                                 if (pos != N_GSYM_name_to_sym_idx.end()) {
3683                                   const uint32_t GSYM_sym_idx = pos->second;
3684                                   m_nlist_idx_to_sym_idx[nlist_idx] =
3685                                       GSYM_sym_idx;
3686                                   // Copy the address, because often the N_GSYM
3687                                   // address has an invalid address of zero
3688                                   // when the global is a common symbol
3689                                   sym[GSYM_sym_idx].GetAddressRef().SetSection(
3690                                       symbol_section);
3691                                   sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3692                                       symbol_value);
3693                                   // We just need the flags from the linker
3694                                   // symbol, so put these flags
3695                                   // into the N_GSYM flags to avoid duplicate
3696                                   // symbols in the symbol table
3697                                   sym[GSYM_sym_idx].SetFlags(
3698                                       nlist.n_type << 16 | nlist.n_desc);
3699                                   sym[sym_idx].Clear();
3700                                   continue;
3701                                 }
3702                               }
3703                             }
3704                           }
3705                         }
3706 
3707                         sym[sym_idx].SetID(nlist_idx);
3708                         sym[sym_idx].SetType(type);
3709                         if (set_value) {
3710                           sym[sym_idx].GetAddressRef().SetSection(
3711                               symbol_section);
3712                           sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
3713                         }
3714                         sym[sym_idx].SetFlags(nlist.n_type << 16 |
3715                                               nlist.n_desc);
3716 
3717                         if (symbol_byte_size > 0)
3718                           sym[sym_idx].SetByteSize(symbol_byte_size);
3719 
3720                         if (demangled_is_synthesized)
3721                           sym[sym_idx].SetDemangledNameIsSynthesized(true);
3722                         ++sym_idx;
3723                       } else {
3724                         sym[sym_idx].Clear();
3725                       }
3726                     }
3727                     /////////////////////////////
3728                   }
3729                   break; // No more entries to consider
3730                 }
3731               }
3732 
3733               for (const auto &pos : reexport_shlib_needs_fixup) {
3734                 const auto undef_pos = undefined_name_to_desc.find(pos.second);
3735                 if (undef_pos != undefined_name_to_desc.end()) {
3736                   const uint8_t dylib_ordinal =
3737                       llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3738                   if (dylib_ordinal > 0 &&
3739                       dylib_ordinal < dylib_files.GetSize())
3740                     sym[pos.first].SetReExportedSymbolSharedLibrary(
3741                         dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3742                 }
3743               }
3744             }
3745           }
3746         }
3747       }
3748     }
3749 
3750     // Must reset this in case it was mutated above!
3751     nlist_data_offset = 0;
3752 #endif
3753 
3754     if (nlist_data.GetByteSize() > 0) {
3755 
3756       // If the sym array was not created while parsing the DSC unmapped
3757       // symbols, create it now.
3758       if (sym == nullptr) {
3759         sym = symtab->Resize(symtab_load_command.nsyms +
3760                              m_dysymtab.nindirectsyms);
3761         num_syms = symtab->GetNumSymbols();
3762       }
3763 
3764       if (unmapped_local_symbols_found) {
3765         assert(m_dysymtab.ilocalsym == 0);
3766         nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3767         nlist_idx = m_dysymtab.nlocalsym;
3768       } else {
3769         nlist_idx = 0;
3770       }
3771 
3772       typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
3773       typedef std::map<uint32_t, ConstString> SymbolIndexToName;
3774       UndefinedNameToDescMap undefined_name_to_desc;
3775       SymbolIndexToName reexport_shlib_needs_fixup;
3776       for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
3777         struct nlist_64 nlist;
3778         if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset,
3779                                                  nlist_byte_size))
3780           break;
3781 
3782         nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
3783         nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
3784         nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
3785         nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
3786         nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
3787 
3788         SymbolType type = eSymbolTypeInvalid;
3789         const char *symbol_name = nullptr;
3790 
3791         if (have_strtab_data) {
3792           symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3793 
3794           if (symbol_name == nullptr) {
3795             // No symbol should be NULL, even the symbols with no string values
3796             // should have an offset zero which points to an empty C-string
3797             Host::SystemLog(Host::eSystemLogError,
3798                             "error: symbol[%u] has invalid string table offset "
3799                             "0x%x in %s, ignoring symbol\n",
3800                             nlist_idx, nlist.n_strx,
3801                             module_sp->GetFileSpec().GetPath().c_str());
3802             continue;
3803           }
3804           if (symbol_name[0] == '\0')
3805             symbol_name = nullptr;
3806         } else {
3807           const addr_t str_addr = strtab_addr + nlist.n_strx;
3808           Status str_error;
3809           if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
3810                                              str_error))
3811             symbol_name = memory_symbol_name.c_str();
3812         }
3813         const char *symbol_name_non_abi_mangled = nullptr;
3814 
3815         SectionSP symbol_section;
3816         lldb::addr_t symbol_byte_size = 0;
3817         bool add_nlist = true;
3818         bool is_gsym = false;
3819         bool is_debug = ((nlist.n_type & N_STAB) != 0);
3820         bool demangled_is_synthesized = false;
3821         bool set_value = true;
3822         assert(sym_idx < num_syms);
3823 
3824         sym[sym_idx].SetDebug(is_debug);
3825 
3826         if (is_debug) {
3827           switch (nlist.n_type) {
3828           case N_GSYM:
3829             // global symbol: name,,NO_SECT,type,0
3830             // Sometimes the N_GSYM value contains the address.
3831 
3832             // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3833             // the ObjC data.  They
3834             // have the same address, but we want to ensure that we always find
3835             // only the real symbol, 'cause we don't currently correctly
3836             // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3837             // type.  This is a temporary hack to make sure the ObjectiveC
3838             // symbols get treated correctly.  To do this right, we should
3839             // coalesce all the GSYM & global symbols that have the same
3840             // address.
3841             is_gsym = true;
3842             sym[sym_idx].SetExternal(true);
3843 
3844             if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3845               llvm::StringRef symbol_name_ref(symbol_name);
3846               if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
3847                 symbol_name_non_abi_mangled = symbol_name + 1;
3848                 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3849                 type = eSymbolTypeObjCClass;
3850                 demangled_is_synthesized = true;
3851 
3852               } else if (symbol_name_ref.startswith(
3853                              g_objc_v2_prefix_metaclass)) {
3854                 symbol_name_non_abi_mangled = symbol_name + 1;
3855                 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3856                 type = eSymbolTypeObjCMetaClass;
3857                 demangled_is_synthesized = true;
3858               } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
3859                 symbol_name_non_abi_mangled = symbol_name + 1;
3860                 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3861                 type = eSymbolTypeObjCIVar;
3862                 demangled_is_synthesized = true;
3863               }
3864             } else {
3865               if (nlist.n_value != 0)
3866                 symbol_section =
3867                     section_info.GetSection(nlist.n_sect, nlist.n_value);
3868               type = eSymbolTypeData;
3869             }
3870             break;
3871 
3872           case N_FNAME:
3873             // procedure name (f77 kludge): name,,NO_SECT,0,0
3874             type = eSymbolTypeCompiler;
3875             break;
3876 
3877           case N_FUN:
3878             // procedure: name,,n_sect,linenumber,address
3879             if (symbol_name) {
3880               type = eSymbolTypeCode;
3881               symbol_section =
3882                   section_info.GetSection(nlist.n_sect, nlist.n_value);
3883 
3884               N_FUN_addr_to_sym_idx.insert(
3885                   std::make_pair(nlist.n_value, sym_idx));
3886               // We use the current number of symbols in the symbol table in
3887               // lieu of using nlist_idx in case we ever start trimming entries
3888               // out
3889               N_FUN_indexes.push_back(sym_idx);
3890             } else {
3891               type = eSymbolTypeCompiler;
3892 
3893               if (!N_FUN_indexes.empty()) {
3894                 // Copy the size of the function into the original STAB entry
3895                 // so we don't have to hunt for it later
3896                 symtab->SymbolAtIndex(N_FUN_indexes.back())
3897                     ->SetByteSize(nlist.n_value);
3898                 N_FUN_indexes.pop_back();
3899                 // We don't really need the end function STAB as it contains
3900                 // the size which we already placed with the original symbol,
3901                 // so don't add it if we want a minimal symbol table
3902                 add_nlist = false;
3903               }
3904             }
3905             break;
3906 
3907           case N_STSYM:
3908             // static symbol: name,,n_sect,type,address
3909             N_STSYM_addr_to_sym_idx.insert(
3910                 std::make_pair(nlist.n_value, sym_idx));
3911             symbol_section =
3912                 section_info.GetSection(nlist.n_sect, nlist.n_value);
3913             if (symbol_name && symbol_name[0]) {
3914               type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
3915                                                        eSymbolTypeData);
3916             }
3917             break;
3918 
3919           case N_LCSYM:
3920             // .lcomm symbol: name,,n_sect,type,address
3921             symbol_section =
3922                 section_info.GetSection(nlist.n_sect, nlist.n_value);
3923             type = eSymbolTypeCommonBlock;
3924             break;
3925 
3926           case N_BNSYM:
3927             // We use the current number of symbols in the symbol table in lieu
3928             // of using nlist_idx in case we ever start trimming entries out
3929             // Skip these if we want minimal symbol tables
3930             add_nlist = false;
3931             break;
3932 
3933           case N_ENSYM:
3934             // Set the size of the N_BNSYM to the terminating index of this
3935             // N_ENSYM so that we can always skip the entire symbol if we need
3936             // to navigate more quickly at the source level when parsing STABS
3937             // Skip these if we want minimal symbol tables
3938             add_nlist = false;
3939             break;
3940 
3941           case N_OPT:
3942             // emitted with gcc2_compiled and in gcc source
3943             type = eSymbolTypeCompiler;
3944             break;
3945 
3946           case N_RSYM:
3947             // register sym: name,,NO_SECT,type,register
3948             type = eSymbolTypeVariable;
3949             break;
3950 
3951           case N_SLINE:
3952             // src line: 0,,n_sect,linenumber,address
3953             symbol_section =
3954                 section_info.GetSection(nlist.n_sect, nlist.n_value);
3955             type = eSymbolTypeLineEntry;
3956             break;
3957 
3958           case N_SSYM:
3959             // structure elt: name,,NO_SECT,type,struct_offset
3960             type = eSymbolTypeVariableType;
3961             break;
3962 
3963           case N_SO:
3964             // source file name
3965             type = eSymbolTypeSourceFile;
3966             if (symbol_name == nullptr) {
3967               add_nlist = false;
3968               if (N_SO_index != UINT32_MAX) {
3969                 // Set the size of the N_SO to the terminating index of this
3970                 // N_SO so that we can always skip the entire N_SO if we need
3971                 // to navigate more quickly at the source level when parsing
3972                 // STABS
3973                 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3974                 symbol_ptr->SetByteSize(sym_idx);
3975                 symbol_ptr->SetSizeIsSibling(true);
3976               }
3977               N_NSYM_indexes.clear();
3978               N_INCL_indexes.clear();
3979               N_BRAC_indexes.clear();
3980               N_COMM_indexes.clear();
3981               N_FUN_indexes.clear();
3982               N_SO_index = UINT32_MAX;
3983             } else {
3984               // We use the current number of symbols in the symbol table in
3985               // lieu of using nlist_idx in case we ever start trimming entries
3986               // out
3987               const bool N_SO_has_full_path = symbol_name[0] == '/';
3988               if (N_SO_has_full_path) {
3989                 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3990                   // We have two consecutive N_SO entries where the first
3991                   // contains a directory and the second contains a full path.
3992                   sym[sym_idx - 1].GetMangled().SetValue(
3993                       ConstString(symbol_name), false);
3994                   m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3995                   add_nlist = false;
3996                 } else {
3997                   // This is the first entry in a N_SO that contains a
3998                   // directory or a full path to the source file
3999                   N_SO_index = sym_idx;
4000                 }
4001               } else if ((N_SO_index == sym_idx - 1) &&
4002                          ((sym_idx - 1) < num_syms)) {
4003                 // This is usually the second N_SO entry that contains just the
4004                 // filename, so here we combine it with the first one if we are
4005                 // minimizing the symbol table
4006                 const char *so_path =
4007                     sym[sym_idx - 1]
4008                         .GetMangled()
4009                         .GetDemangledName(lldb::eLanguageTypeUnknown)
4010                         .AsCString();
4011                 if (so_path && so_path[0]) {
4012                   std::string full_so_path(so_path);
4013                   const size_t double_slash_pos = full_so_path.find("//");
4014                   if (double_slash_pos != std::string::npos) {
4015                     // The linker has been generating bad N_SO entries with
4016                     // doubled up paths in the format "%s%s" where the first
4017                     // string in the DW_AT_comp_dir, and the second is the
4018                     // directory for the source file so you end up with a path
4019                     // that looks like "/tmp/src//tmp/src/"
4020                     FileSpec so_dir(so_path);
4021                     if (!FileSystem::Instance().Exists(so_dir)) {
4022                       so_dir.SetFile(&full_so_path[double_slash_pos + 1],
4023                                      FileSpec::Style::native);
4024                       if (FileSystem::Instance().Exists(so_dir)) {
4025                         // Trim off the incorrect path
4026                         full_so_path.erase(0, double_slash_pos + 1);
4027                       }
4028                     }
4029                   }
4030                   if (*full_so_path.rbegin() != '/')
4031                     full_so_path += '/';
4032                   full_so_path += symbol_name;
4033                   sym[sym_idx - 1].GetMangled().SetValue(
4034                       ConstString(full_so_path.c_str()), false);
4035                   add_nlist = false;
4036                   m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
4037                 }
4038               } else {
4039                 // This could be a relative path to a N_SO
4040                 N_SO_index = sym_idx;
4041               }
4042             }
4043             break;
4044 
4045           case N_OSO:
4046             // object file name: name,,0,0,st_mtime
4047             type = eSymbolTypeObjectFile;
4048             break;
4049 
4050           case N_LSYM:
4051             // local sym: name,,NO_SECT,type,offset
4052             type = eSymbolTypeLocal;
4053             break;
4054 
4055           // INCL scopes
4056           case N_BINCL:
4057             // include file beginning: name,,NO_SECT,0,sum We use the current
4058             // number of symbols in the symbol table in lieu of using nlist_idx
4059             // in case we ever start trimming entries out
4060             N_INCL_indexes.push_back(sym_idx);
4061             type = eSymbolTypeScopeBegin;
4062             break;
4063 
4064           case N_EINCL:
4065             // include file end: name,,NO_SECT,0,0
4066             // Set the size of the N_BINCL to the terminating index of this
4067             // N_EINCL so that we can always skip the entire symbol if we need
4068             // to navigate more quickly at the source level when parsing STABS
4069             if (!N_INCL_indexes.empty()) {
4070               symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
4071               symbol_ptr->SetByteSize(sym_idx + 1);
4072               symbol_ptr->SetSizeIsSibling(true);
4073               N_INCL_indexes.pop_back();
4074             }
4075             type = eSymbolTypeScopeEnd;
4076             break;
4077 
4078           case N_SOL:
4079             // #included file name: name,,n_sect,0,address
4080             type = eSymbolTypeHeaderFile;
4081 
4082             // We currently don't use the header files on darwin
4083             add_nlist = false;
4084             break;
4085 
4086           case N_PARAMS:
4087             // compiler parameters: name,,NO_SECT,0,0
4088             type = eSymbolTypeCompiler;
4089             break;
4090 
4091           case N_VERSION:
4092             // compiler version: name,,NO_SECT,0,0
4093             type = eSymbolTypeCompiler;
4094             break;
4095 
4096           case N_OLEVEL:
4097             // compiler -O level: name,,NO_SECT,0,0
4098             type = eSymbolTypeCompiler;
4099             break;
4100 
4101           case N_PSYM:
4102             // parameter: name,,NO_SECT,type,offset
4103             type = eSymbolTypeVariable;
4104             break;
4105 
4106           case N_ENTRY:
4107             // alternate entry: name,,n_sect,linenumber,address
4108             symbol_section =
4109                 section_info.GetSection(nlist.n_sect, nlist.n_value);
4110             type = eSymbolTypeLineEntry;
4111             break;
4112 
4113           // Left and Right Braces
4114           case N_LBRAC:
4115             // left bracket: 0,,NO_SECT,nesting level,address We use the
4116             // current number of symbols in the symbol table in lieu of using
4117             // nlist_idx in case we ever start trimming entries out
4118             symbol_section =
4119                 section_info.GetSection(nlist.n_sect, nlist.n_value);
4120             N_BRAC_indexes.push_back(sym_idx);
4121             type = eSymbolTypeScopeBegin;
4122             break;
4123 
4124           case N_RBRAC:
4125             // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4126             // the N_LBRAC to the terminating index of this N_RBRAC so that we
4127             // can always skip the entire symbol if we need to navigate more
4128             // quickly at the source level when parsing STABS
4129             symbol_section =
4130                 section_info.GetSection(nlist.n_sect, nlist.n_value);
4131             if (!N_BRAC_indexes.empty()) {
4132               symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
4133               symbol_ptr->SetByteSize(sym_idx + 1);
4134               symbol_ptr->SetSizeIsSibling(true);
4135               N_BRAC_indexes.pop_back();
4136             }
4137             type = eSymbolTypeScopeEnd;
4138             break;
4139 
4140           case N_EXCL:
4141             // deleted include file: name,,NO_SECT,0,sum
4142             type = eSymbolTypeHeaderFile;
4143             break;
4144 
4145           // COMM scopes
4146           case N_BCOMM:
4147             // begin common: name,,NO_SECT,0,0
4148             // We use the current number of symbols in the symbol table in lieu
4149             // of using nlist_idx in case we ever start trimming entries out
4150             type = eSymbolTypeScopeBegin;
4151             N_COMM_indexes.push_back(sym_idx);
4152             break;
4153 
4154           case N_ECOML:
4155             // end common (local name): 0,,n_sect,0,address
4156             symbol_section =
4157                 section_info.GetSection(nlist.n_sect, nlist.n_value);
4158             LLVM_FALLTHROUGH;
4159 
4160           case N_ECOMM:
4161             // end common: name,,n_sect,0,0
4162             // Set the size of the N_BCOMM to the terminating index of this
4163             // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4164             // we need to navigate more quickly at the source level when
4165             // parsing STABS
4166             if (!N_COMM_indexes.empty()) {
4167               symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
4168               symbol_ptr->SetByteSize(sym_idx + 1);
4169               symbol_ptr->SetSizeIsSibling(true);
4170               N_COMM_indexes.pop_back();
4171             }
4172             type = eSymbolTypeScopeEnd;
4173             break;
4174 
4175           case N_LENG:
4176             // second stab entry with length information
4177             type = eSymbolTypeAdditional;
4178             break;
4179 
4180           default:
4181             break;
4182           }
4183         } else {
4184           // uint8_t n_pext    = N_PEXT & nlist.n_type;
4185           uint8_t n_type = N_TYPE & nlist.n_type;
4186           sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4187 
4188           switch (n_type) {
4189           case N_INDR: {
4190             const char *reexport_name_cstr =
4191                 strtab_data.PeekCStr(nlist.n_value);
4192             if (reexport_name_cstr && reexport_name_cstr[0]) {
4193               type = eSymbolTypeReExported;
4194               ConstString reexport_name(
4195                   reexport_name_cstr +
4196                   ((reexport_name_cstr[0] == '_') ? 1 : 0));
4197               sym[sym_idx].SetReExportedSymbolName(reexport_name);
4198               set_value = false;
4199               reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4200               indirect_symbol_names.insert(
4201                   ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4202             } else
4203               type = eSymbolTypeUndefined;
4204           } break;
4205 
4206           case N_UNDF:
4207             if (symbol_name && symbol_name[0]) {
4208               ConstString undefined_name(symbol_name +
4209                                          ((symbol_name[0] == '_') ? 1 : 0));
4210               undefined_name_to_desc[undefined_name] = nlist.n_desc;
4211             }
4212             LLVM_FALLTHROUGH;
4213 
4214           case N_PBUD:
4215             type = eSymbolTypeUndefined;
4216             break;
4217 
4218           case N_ABS:
4219             type = eSymbolTypeAbsolute;
4220             break;
4221 
4222           case N_SECT: {
4223             symbol_section =
4224                 section_info.GetSection(nlist.n_sect, nlist.n_value);
4225 
4226             if (!symbol_section) {
4227               // TODO: warn about this?
4228               add_nlist = false;
4229               break;
4230             }
4231 
4232             if (TEXT_eh_frame_sectID == nlist.n_sect) {
4233               type = eSymbolTypeException;
4234             } else {
4235               uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4236 
4237               switch (section_type) {
4238               case S_CSTRING_LITERALS:
4239                 type = eSymbolTypeData;
4240                 break; // section with only literal C strings
4241               case S_4BYTE_LITERALS:
4242                 type = eSymbolTypeData;
4243                 break; // section with only 4 byte literals
4244               case S_8BYTE_LITERALS:
4245                 type = eSymbolTypeData;
4246                 break; // section with only 8 byte literals
4247               case S_LITERAL_POINTERS:
4248                 type = eSymbolTypeTrampoline;
4249                 break; // section with only pointers to literals
4250               case S_NON_LAZY_SYMBOL_POINTERS:
4251                 type = eSymbolTypeTrampoline;
4252                 break; // section with only non-lazy symbol pointers
4253               case S_LAZY_SYMBOL_POINTERS:
4254                 type = eSymbolTypeTrampoline;
4255                 break; // section with only lazy symbol pointers
4256               case S_SYMBOL_STUBS:
4257                 type = eSymbolTypeTrampoline;
4258                 break; // section with only symbol stubs, byte size of stub in
4259                        // the reserved2 field
4260               case S_MOD_INIT_FUNC_POINTERS:
4261                 type = eSymbolTypeCode;
4262                 break; // section with only function pointers for initialization
4263               case S_MOD_TERM_FUNC_POINTERS:
4264                 type = eSymbolTypeCode;
4265                 break; // section with only function pointers for termination
4266               case S_INTERPOSING:
4267                 type = eSymbolTypeTrampoline;
4268                 break; // section with only pairs of function pointers for
4269                        // interposing
4270               case S_16BYTE_LITERALS:
4271                 type = eSymbolTypeData;
4272                 break; // section with only 16 byte literals
4273               case S_DTRACE_DOF:
4274                 type = eSymbolTypeInstrumentation;
4275                 break;
4276               case S_LAZY_DYLIB_SYMBOL_POINTERS:
4277                 type = eSymbolTypeTrampoline;
4278                 break;
4279               default:
4280                 switch (symbol_section->GetType()) {
4281                 case lldb::eSectionTypeCode:
4282                   type = eSymbolTypeCode;
4283                   break;
4284                 case eSectionTypeData:
4285                 case eSectionTypeDataCString:         // Inlined C string data
4286                 case eSectionTypeDataCStringPointers: // Pointers to C string
4287                                                       // data
4288                 case eSectionTypeDataSymbolAddress:   // Address of a symbol in
4289                                                       // the symbol table
4290                 case eSectionTypeData4:
4291                 case eSectionTypeData8:
4292                 case eSectionTypeData16:
4293                   type = eSymbolTypeData;
4294                   break;
4295                 default:
4296                   break;
4297                 }
4298                 break;
4299               }
4300 
4301               if (type == eSymbolTypeInvalid) {
4302                 const char *symbol_sect_name =
4303                     symbol_section->GetName().AsCString();
4304                 if (symbol_section->IsDescendant(text_section_sp.get())) {
4305                   if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4306                                               S_ATTR_SELF_MODIFYING_CODE |
4307                                               S_ATTR_SOME_INSTRUCTIONS))
4308                     type = eSymbolTypeData;
4309                   else
4310                     type = eSymbolTypeCode;
4311                 } else if (symbol_section->IsDescendant(
4312                                data_section_sp.get()) ||
4313                            symbol_section->IsDescendant(
4314                                data_dirty_section_sp.get()) ||
4315                            symbol_section->IsDescendant(
4316                                data_const_section_sp.get())) {
4317                   if (symbol_sect_name &&
4318                       ::strstr(symbol_sect_name, "__objc") ==
4319                           symbol_sect_name) {
4320                     type = eSymbolTypeRuntime;
4321 
4322                     if (symbol_name) {
4323                       llvm::StringRef symbol_name_ref(symbol_name);
4324                       if (symbol_name_ref.startswith("_OBJC_")) {
4325                         static const llvm::StringRef g_objc_v2_prefix_class(
4326                             "_OBJC_CLASS_$_");
4327                         static const llvm::StringRef g_objc_v2_prefix_metaclass(
4328                             "_OBJC_METACLASS_$_");
4329                         static const llvm::StringRef g_objc_v2_prefix_ivar(
4330                             "_OBJC_IVAR_$_");
4331                         if (symbol_name_ref.startswith(
4332                                 g_objc_v2_prefix_class)) {
4333                           symbol_name_non_abi_mangled = symbol_name + 1;
4334                           symbol_name =
4335                               symbol_name + g_objc_v2_prefix_class.size();
4336                           type = eSymbolTypeObjCClass;
4337                           demangled_is_synthesized = true;
4338                         } else if (symbol_name_ref.startswith(
4339                                        g_objc_v2_prefix_metaclass)) {
4340                           symbol_name_non_abi_mangled = symbol_name + 1;
4341                           symbol_name =
4342                               symbol_name + g_objc_v2_prefix_metaclass.size();
4343                           type = eSymbolTypeObjCMetaClass;
4344                           demangled_is_synthesized = true;
4345                         } else if (symbol_name_ref.startswith(
4346                                        g_objc_v2_prefix_ivar)) {
4347                           symbol_name_non_abi_mangled = symbol_name + 1;
4348                           symbol_name =
4349                               symbol_name + g_objc_v2_prefix_ivar.size();
4350                           type = eSymbolTypeObjCIVar;
4351                           demangled_is_synthesized = true;
4352                         }
4353                       }
4354                     }
4355                   } else if (symbol_sect_name &&
4356                              ::strstr(symbol_sect_name, "__gcc_except_tab") ==
4357                                  symbol_sect_name) {
4358                     type = eSymbolTypeException;
4359                   } else {
4360                     type = eSymbolTypeData;
4361                   }
4362                 } else if (symbol_sect_name &&
4363                            ::strstr(symbol_sect_name, "__IMPORT") ==
4364                                symbol_sect_name) {
4365                   type = eSymbolTypeTrampoline;
4366                 } else if (symbol_section->IsDescendant(
4367                                objc_section_sp.get())) {
4368                   type = eSymbolTypeRuntime;
4369                   if (symbol_name && symbol_name[0] == '.') {
4370                     llvm::StringRef symbol_name_ref(symbol_name);
4371                     static const llvm::StringRef g_objc_v1_prefix_class(
4372                         ".objc_class_name_");
4373                     if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) {
4374                       symbol_name_non_abi_mangled = symbol_name;
4375                       symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4376                       type = eSymbolTypeObjCClass;
4377                       demangled_is_synthesized = true;
4378                     }
4379                   }
4380                 }
4381               }
4382             }
4383           } break;
4384           }
4385         }
4386 
4387         if (add_nlist) {
4388           uint64_t symbol_value = nlist.n_value;
4389 
4390           if (symbol_name_non_abi_mangled) {
4391             sym[sym_idx].GetMangled().SetMangledName(
4392                 ConstString(symbol_name_non_abi_mangled));
4393             sym[sym_idx].GetMangled().SetDemangledName(
4394                 ConstString(symbol_name));
4395           } else {
4396             bool symbol_name_is_mangled = false;
4397 
4398             if (symbol_name && symbol_name[0] == '_') {
4399               symbol_name_is_mangled = symbol_name[1] == '_';
4400               symbol_name++; // Skip the leading underscore
4401             }
4402 
4403             if (symbol_name) {
4404               ConstString const_symbol_name(symbol_name);
4405               sym[sym_idx].GetMangled().SetValue(const_symbol_name,
4406                                                  symbol_name_is_mangled);
4407             }
4408           }
4409 
4410           if (is_gsym) {
4411             const char *gsym_name = sym[sym_idx]
4412                                         .GetMangled()
4413                                         .GetName(lldb::eLanguageTypeUnknown,
4414                                                  Mangled::ePreferMangled)
4415                                         .GetCString();
4416             if (gsym_name)
4417               N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4418           }
4419 
4420           if (symbol_section) {
4421             const addr_t section_file_addr = symbol_section->GetFileAddress();
4422             if (symbol_byte_size == 0 && function_starts_count > 0) {
4423               addr_t symbol_lookup_file_addr = nlist.n_value;
4424               // Do an exact address match for non-ARM addresses, else get the
4425               // closest since the symbol might be a thumb symbol which has an
4426               // address with bit zero set
4427               FunctionStarts::Entry *func_start_entry =
4428                   function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
4429               if (is_arm && func_start_entry) {
4430                 // Verify that the function start address is the symbol address
4431                 // (ARM) or the symbol address + 1 (thumb)
4432                 if (func_start_entry->addr != symbol_lookup_file_addr &&
4433                     func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4434                   // Not the right entry, NULL it out...
4435                   func_start_entry = nullptr;
4436                 }
4437               }
4438               if (func_start_entry) {
4439                 func_start_entry->data = true;
4440 
4441                 addr_t symbol_file_addr = func_start_entry->addr;
4442                 if (is_arm)
4443                   symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4444 
4445                 const FunctionStarts::Entry *next_func_start_entry =
4446                     function_starts.FindNextEntry(func_start_entry);
4447                 const addr_t section_end_file_addr =
4448                     section_file_addr + symbol_section->GetByteSize();
4449                 if (next_func_start_entry) {
4450                   addr_t next_symbol_file_addr = next_func_start_entry->addr;
4451                   // Be sure the clear the Thumb address bit when we calculate
4452                   // the size from the current and next address
4453                   if (is_arm)
4454                     next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4455                   symbol_byte_size = std::min<lldb::addr_t>(
4456                       next_symbol_file_addr - symbol_file_addr,
4457                       section_end_file_addr - symbol_file_addr);
4458                 } else {
4459                   symbol_byte_size = section_end_file_addr - symbol_file_addr;
4460                 }
4461               }
4462             }
4463             symbol_value -= section_file_addr;
4464           }
4465 
4466           if (!is_debug) {
4467             if (type == eSymbolTypeCode) {
4468               // See if we can find a N_FUN entry for any code symbols. If we
4469               // do find a match, and the name matches, then we can merge the
4470               // two into just the function symbol to avoid duplicate entries
4471               // in the symbol table
4472               std::pair<ValueToSymbolIndexMap::const_iterator,
4473                         ValueToSymbolIndexMap::const_iterator>
4474                   range;
4475               range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4476               if (range.first != range.second) {
4477                 bool found_it = false;
4478                 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4479                      pos != range.second; ++pos) {
4480                   if (sym[sym_idx].GetMangled().GetName(
4481                           lldb::eLanguageTypeUnknown,
4482                           Mangled::ePreferMangled) ==
4483                       sym[pos->second].GetMangled().GetName(
4484                           lldb::eLanguageTypeUnknown,
4485                           Mangled::ePreferMangled)) {
4486                     m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4487                     // We just need the flags from the linker symbol, so put
4488                     // these flags into the N_FUN flags to avoid duplicate
4489                     // symbols in the symbol table
4490                     sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4491                     sym[pos->second].SetFlags(nlist.n_type << 16 |
4492                                               nlist.n_desc);
4493                     if (resolver_addresses.find(nlist.n_value) !=
4494                         resolver_addresses.end())
4495                       sym[pos->second].SetType(eSymbolTypeResolver);
4496                     sym[sym_idx].Clear();
4497                     found_it = true;
4498                     break;
4499                   }
4500                 }
4501                 if (found_it)
4502                   continue;
4503               } else {
4504                 if (resolver_addresses.find(nlist.n_value) !=
4505                     resolver_addresses.end())
4506                   type = eSymbolTypeResolver;
4507               }
4508             } else if (type == eSymbolTypeData ||
4509                        type == eSymbolTypeObjCClass ||
4510                        type == eSymbolTypeObjCMetaClass ||
4511                        type == eSymbolTypeObjCIVar) {
4512               // See if we can find a N_STSYM entry for any data symbols. If we
4513               // do find a match, and the name matches, then we can merge the
4514               // two into just the Static symbol to avoid duplicate entries in
4515               // the symbol table
4516               std::pair<ValueToSymbolIndexMap::const_iterator,
4517                         ValueToSymbolIndexMap::const_iterator>
4518                   range;
4519               range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4520               if (range.first != range.second) {
4521                 bool found_it = false;
4522                 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4523                      pos != range.second; ++pos) {
4524                   if (sym[sym_idx].GetMangled().GetName(
4525                           lldb::eLanguageTypeUnknown,
4526                           Mangled::ePreferMangled) ==
4527                       sym[pos->second].GetMangled().GetName(
4528                           lldb::eLanguageTypeUnknown,
4529                           Mangled::ePreferMangled)) {
4530                     m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4531                     // We just need the flags from the linker symbol, so put
4532                     // these flags into the N_STSYM flags to avoid duplicate
4533                     // symbols in the symbol table
4534                     sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4535                     sym[pos->second].SetFlags(nlist.n_type << 16 |
4536                                               nlist.n_desc);
4537                     sym[sym_idx].Clear();
4538                     found_it = true;
4539                     break;
4540                   }
4541                 }
4542                 if (found_it)
4543                   continue;
4544               } else {
4545                 // Combine N_GSYM stab entries with the non stab symbol
4546                 const char *gsym_name = sym[sym_idx]
4547                                             .GetMangled()
4548                                             .GetName(lldb::eLanguageTypeUnknown,
4549                                                      Mangled::ePreferMangled)
4550                                             .GetCString();
4551                 if (gsym_name) {
4552                   ConstNameToSymbolIndexMap::const_iterator pos =
4553                       N_GSYM_name_to_sym_idx.find(gsym_name);
4554                   if (pos != N_GSYM_name_to_sym_idx.end()) {
4555                     const uint32_t GSYM_sym_idx = pos->second;
4556                     m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
4557                     // Copy the address, because often the N_GSYM address has
4558                     // an invalid address of zero when the global is a common
4559                     // symbol
4560                     sym[GSYM_sym_idx].GetAddressRef().SetSection(
4561                         symbol_section);
4562                     sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4563                     // We just need the flags from the linker symbol, so put
4564                     // these flags into the N_GSYM flags to avoid duplicate
4565                     // symbols in the symbol table
4566                     sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
4567                                                nlist.n_desc);
4568                     sym[sym_idx].Clear();
4569                     continue;
4570                   }
4571                 }
4572               }
4573             }
4574           }
4575 
4576           sym[sym_idx].SetID(nlist_idx);
4577           sym[sym_idx].SetType(type);
4578           if (set_value) {
4579             sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4580             sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4581           }
4582           sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4583           if (nlist.n_desc & N_WEAK_REF)
4584             sym[sym_idx].SetIsWeak(true);
4585 
4586           if (symbol_byte_size > 0)
4587             sym[sym_idx].SetByteSize(symbol_byte_size);
4588 
4589           if (demangled_is_synthesized)
4590             sym[sym_idx].SetDemangledNameIsSynthesized(true);
4591 
4592           ++sym_idx;
4593         } else {
4594           sym[sym_idx].Clear();
4595         }
4596       }
4597 
4598       for (const auto &pos : reexport_shlib_needs_fixup) {
4599         const auto undef_pos = undefined_name_to_desc.find(pos.second);
4600         if (undef_pos != undefined_name_to_desc.end()) {
4601           const uint8_t dylib_ordinal =
4602               llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4603           if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4604             sym[pos.first].SetReExportedSymbolSharedLibrary(
4605                 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
4606         }
4607       }
4608     }
4609 
4610     uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4611 
4612     if (function_starts_count > 0) {
4613       uint32_t num_synthetic_function_symbols = 0;
4614       for (i = 0; i < function_starts_count; ++i) {
4615         if (!function_starts.GetEntryRef(i).data)
4616           ++num_synthetic_function_symbols;
4617       }
4618 
4619       if (num_synthetic_function_symbols > 0) {
4620         if (num_syms < sym_idx + num_synthetic_function_symbols) {
4621           num_syms = sym_idx + num_synthetic_function_symbols;
4622           sym = symtab->Resize(num_syms);
4623         }
4624         for (i = 0; i < function_starts_count; ++i) {
4625           const FunctionStarts::Entry *func_start_entry =
4626               function_starts.GetEntryAtIndex(i);
4627           if (!func_start_entry->data) {
4628             addr_t symbol_file_addr = func_start_entry->addr;
4629             uint32_t symbol_flags = 0;
4630             if (is_arm) {
4631               if (symbol_file_addr & 1)
4632                 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4633               symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4634             }
4635             Address symbol_addr;
4636             if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
4637               SectionSP symbol_section(symbol_addr.GetSection());
4638               uint32_t symbol_byte_size = 0;
4639               if (symbol_section) {
4640                 const addr_t section_file_addr =
4641                     symbol_section->GetFileAddress();
4642                 const FunctionStarts::Entry *next_func_start_entry =
4643                     function_starts.FindNextEntry(func_start_entry);
4644                 const addr_t section_end_file_addr =
4645                     section_file_addr + symbol_section->GetByteSize();
4646                 if (next_func_start_entry) {
4647                   addr_t next_symbol_file_addr = next_func_start_entry->addr;
4648                   if (is_arm)
4649                     next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4650                   symbol_byte_size = std::min<lldb::addr_t>(
4651                       next_symbol_file_addr - symbol_file_addr,
4652                       section_end_file_addr - symbol_file_addr);
4653                 } else {
4654                   symbol_byte_size = section_end_file_addr - symbol_file_addr;
4655                 }
4656                 sym[sym_idx].SetID(synthetic_sym_id++);
4657                 sym[sym_idx].GetMangled().SetDemangledName(
4658                     GetNextSyntheticSymbolName());
4659                 sym[sym_idx].SetType(eSymbolTypeCode);
4660                 sym[sym_idx].SetIsSynthetic(true);
4661                 sym[sym_idx].GetAddressRef() = symbol_addr;
4662                 if (symbol_flags)
4663                   sym[sym_idx].SetFlags(symbol_flags);
4664                 if (symbol_byte_size)
4665                   sym[sym_idx].SetByteSize(symbol_byte_size);
4666                 ++sym_idx;
4667               }
4668             }
4669           }
4670         }
4671       }
4672     }
4673 
4674     // Trim our symbols down to just what we ended up with after removing any
4675     // symbols.
4676     if (sym_idx < num_syms) {
4677       num_syms = sym_idx;
4678       sym = symtab->Resize(num_syms);
4679     }
4680 
4681     // Now synthesize indirect symbols
4682     if (m_dysymtab.nindirectsyms != 0) {
4683       if (indirect_symbol_index_data.GetByteSize()) {
4684         NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4685             m_nlist_idx_to_sym_idx.end();
4686 
4687         for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4688              ++sect_idx) {
4689           if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4690               S_SYMBOL_STUBS) {
4691             uint32_t symbol_stub_byte_size =
4692                 m_mach_sections[sect_idx].reserved2;
4693             if (symbol_stub_byte_size == 0)
4694               continue;
4695 
4696             const uint32_t num_symbol_stubs =
4697                 m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4698 
4699             if (num_symbol_stubs == 0)
4700               continue;
4701 
4702             const uint32_t symbol_stub_index_offset =
4703                 m_mach_sections[sect_idx].reserved1;
4704             for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs;
4705                  ++stub_idx) {
4706               const uint32_t symbol_stub_index =
4707                   symbol_stub_index_offset + stub_idx;
4708               const lldb::addr_t symbol_stub_addr =
4709                   m_mach_sections[sect_idx].addr +
4710                   (stub_idx * symbol_stub_byte_size);
4711               lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4712               if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4713                       symbol_stub_offset, 4)) {
4714                 const uint32_t stub_sym_id =
4715                     indirect_symbol_index_data.GetU32(&symbol_stub_offset);
4716                 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4717                   continue;
4718 
4719                 NListIndexToSymbolIndexMap::const_iterator index_pos =
4720                     m_nlist_idx_to_sym_idx.find(stub_sym_id);
4721                 Symbol *stub_symbol = nullptr;
4722                 if (index_pos != end_index_pos) {
4723                   // We have a remapping from the original nlist index to a
4724                   // current symbol index, so just look this up by index
4725                   stub_symbol = symtab->SymbolAtIndex(index_pos->second);
4726                 } else {
4727                   // We need to lookup a symbol using the original nlist symbol
4728                   // index since this index is coming from the S_SYMBOL_STUBS
4729                   stub_symbol = symtab->FindSymbolByID(stub_sym_id);
4730                 }
4731 
4732                 if (stub_symbol) {
4733                   Address so_addr(symbol_stub_addr, section_list);
4734 
4735                   if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4736                     // Change the external symbol into a trampoline that makes
4737                     // sense These symbols were N_UNDF N_EXT, and are useless
4738                     // to us, so we can re-use them so we don't have to make up
4739                     // a synthetic symbol for no good reason.
4740                     if (resolver_addresses.find(symbol_stub_addr) ==
4741                         resolver_addresses.end())
4742                       stub_symbol->SetType(eSymbolTypeTrampoline);
4743                     else
4744                       stub_symbol->SetType(eSymbolTypeResolver);
4745                     stub_symbol->SetExternal(false);
4746                     stub_symbol->GetAddressRef() = so_addr;
4747                     stub_symbol->SetByteSize(symbol_stub_byte_size);
4748                   } else {
4749                     // Make a synthetic symbol to describe the trampoline stub
4750                     Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4751                     if (sym_idx >= num_syms) {
4752                       sym = symtab->Resize(++num_syms);
4753                       stub_symbol = nullptr; // this pointer no longer valid
4754                     }
4755                     sym[sym_idx].SetID(synthetic_sym_id++);
4756                     sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4757                     if (resolver_addresses.find(symbol_stub_addr) ==
4758                         resolver_addresses.end())
4759                       sym[sym_idx].SetType(eSymbolTypeTrampoline);
4760                     else
4761                       sym[sym_idx].SetType(eSymbolTypeResolver);
4762                     sym[sym_idx].SetIsSynthetic(true);
4763                     sym[sym_idx].GetAddressRef() = so_addr;
4764                     sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4765                     ++sym_idx;
4766                   }
4767                 } else {
4768                   if (log)
4769                     log->Warning("symbol stub referencing symbol table symbol "
4770                                  "%u that isn't in our minimal symbol table, "
4771                                  "fix this!!!",
4772                                  stub_sym_id);
4773                 }
4774               }
4775             }
4776           }
4777         }
4778       }
4779     }
4780 
4781     if (!trie_entries.empty()) {
4782       for (const auto &e : trie_entries) {
4783         if (e.entry.import_name) {
4784           // Only add indirect symbols from the Trie entries if we didn't have
4785           // a N_INDR nlist entry for this already
4786           if (indirect_symbol_names.find(e.entry.name) ==
4787               indirect_symbol_names.end()) {
4788             // Make a synthetic symbol to describe re-exported symbol.
4789             if (sym_idx >= num_syms)
4790               sym = symtab->Resize(++num_syms);
4791             sym[sym_idx].SetID(synthetic_sym_id++);
4792             sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4793             sym[sym_idx].SetType(eSymbolTypeReExported);
4794             sym[sym_idx].SetIsSynthetic(true);
4795             sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4796             if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4797               sym[sym_idx].SetReExportedSymbolSharedLibrary(
4798                   dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
4799             }
4800             ++sym_idx;
4801           }
4802         }
4803       }
4804     }
4805 
4806     //        StreamFile s(stdout, false);
4807     //        s.Printf ("Symbol table before CalculateSymbolSizes():\n");
4808     //        symtab->Dump(&s, NULL, eSortOrderNone);
4809     // Set symbol byte sizes correctly since mach-o nlist entries don't have
4810     // sizes
4811     symtab->CalculateSymbolSizes();
4812 
4813     //        s.Printf ("Symbol table after CalculateSymbolSizes():\n");
4814     //        symtab->Dump(&s, NULL, eSortOrderNone);
4815 
4816     return symtab->GetNumSymbols();
4817   }
4818   return 0;
4819 }
4820 
4821 void ObjectFileMachO::Dump(Stream *s) {
4822   ModuleSP module_sp(GetModule());
4823   if (module_sp) {
4824     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4825     s->Printf("%p: ", static_cast<void *>(this));
4826     s->Indent();
4827     if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4828       s->PutCString("ObjectFileMachO64");
4829     else
4830       s->PutCString("ObjectFileMachO32");
4831 
4832     ArchSpec header_arch = GetArchitecture();
4833 
4834     *s << ", file = '" << m_file
4835        << "', triple = " << header_arch.GetTriple().getTriple() << "\n";
4836 
4837     SectionList *sections = GetSectionList();
4838     if (sections)
4839       sections->Dump(s, nullptr, true, UINT32_MAX);
4840 
4841     if (m_symtab_up)
4842       m_symtab_up->Dump(s, nullptr, eSortOrderNone);
4843   }
4844 }
4845 
4846 UUID ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4847                               const lldb_private::DataExtractor &data,
4848                               lldb::offset_t lc_offset) {
4849   uint32_t i;
4850   struct uuid_command load_cmd;
4851 
4852   lldb::offset_t offset = lc_offset;
4853   for (i = 0; i < header.ncmds; ++i) {
4854     const lldb::offset_t cmd_offset = offset;
4855     if (data.GetU32(&offset, &load_cmd, 2) == nullptr)
4856       break;
4857 
4858     if (load_cmd.cmd == LC_UUID) {
4859       const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4860 
4861       if (uuid_bytes) {
4862         // OpenCL on Mac OS X uses the same UUID for each of its object files.
4863         // We pretend these object files have no UUID to prevent crashing.
4864 
4865         const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4866                                        0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4867                                        0xbb, 0x14, 0xf0, 0x0d};
4868 
4869         if (!memcmp(uuid_bytes, opencl_uuid, 16))
4870           return UUID();
4871 
4872         return UUID::fromOptionalData(uuid_bytes, 16);
4873       }
4874       return UUID();
4875     }
4876     offset = cmd_offset + load_cmd.cmdsize;
4877   }
4878   return UUID();
4879 }
4880 
4881 static llvm::StringRef GetOSName(uint32_t cmd) {
4882   switch (cmd) {
4883   case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
4884     return llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4885   case llvm::MachO::LC_VERSION_MIN_MACOSX:
4886     return llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4887   case llvm::MachO::LC_VERSION_MIN_TVOS:
4888     return llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4889   case llvm::MachO::LC_VERSION_MIN_WATCHOS:
4890     return llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4891   default:
4892     llvm_unreachable("unexpected LC_VERSION load command");
4893   }
4894 }
4895 
4896 namespace {
4897   struct OSEnv {
4898     llvm::StringRef os_type;
4899     llvm::StringRef environment;
4900     OSEnv(uint32_t cmd) {
4901       switch (cmd) {
4902       case PLATFORM_MACOS:
4903         os_type = llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4904         return;
4905       case PLATFORM_IOS:
4906         os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4907         return;
4908       case PLATFORM_TVOS:
4909         os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4910         return;
4911       case PLATFORM_WATCHOS:
4912         os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4913         return;
4914 // NEED_BRIDGEOS_TRIPLE      case PLATFORM_BRIDGEOS:
4915 // NEED_BRIDGEOS_TRIPLE        os_type = llvm::Triple::getOSTypeName(llvm::Triple::BridgeOS);
4916 // NEED_BRIDGEOS_TRIPLE        return;
4917 #if defined (PLATFORM_IOSSIMULATOR) && defined (PLATFORM_TVOSSIMULATOR) && defined (PLATFORM_WATCHOSSIMULATOR)
4918       case PLATFORM_IOSSIMULATOR:
4919         os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4920         environment =
4921             llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4922         return;
4923       case PLATFORM_TVOSSIMULATOR:
4924         os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4925         environment =
4926             llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4927         return;
4928       case PLATFORM_WATCHOSSIMULATOR:
4929         os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4930         environment =
4931             llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4932         return;
4933 #endif
4934       default: {
4935         Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
4936                                                         LIBLLDB_LOG_PROCESS));
4937         LLDB_LOGF(log, "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   LLDB_LOGF(
5722       log,
5723       "inferior process shared cache has a UUID of %s, base address 0x%" PRIx64,
5724       uuid.GetAsString().c_str(), base_addr);
5725 }
5726 
5727 // From dyld SPI header dyld_process_info.h
5728 typedef void *dyld_process_info;
5729 struct lldb_copy__dyld_process_cache_info {
5730   uuid_t cacheUUID;          // UUID of cache used by process
5731   uint64_t cacheBaseAddress; // load address of dyld shared cache
5732   bool noCache;              // process is running without a dyld cache
5733   bool privateCache; // process is using a private copy of its dyld cache
5734 };
5735 
5736 // #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with llvm
5737 // enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile errors.
5738 // So we need to use the actual underlying types of task_t and kern_return_t
5739 // below.
5740 extern "C" unsigned int /*task_t*/ mach_task_self();
5741 
5742 void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
5743   uuid.Clear();
5744   base_addr = LLDB_INVALID_ADDRESS;
5745 
5746 #if defined(__APPLE__) &&                                                      \
5747     (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
5748   uint8_t *(*dyld_get_all_image_infos)(void);
5749   dyld_get_all_image_infos =
5750       (uint8_t * (*)())dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5751   if (dyld_get_all_image_infos) {
5752     uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5753     if (dyld_all_image_infos_address) {
5754       uint32_t *version = (uint32_t *)
5755           dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5756       if (*version >= 13) {
5757         uuid_t *sharedCacheUUID_address = 0;
5758         int wordsize = sizeof(uint8_t *);
5759         if (wordsize == 8) {
5760           sharedCacheUUID_address =
5761               (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5762                          160); // sharedCacheUUID <mach-o/dyld_images.h>
5763           if (*version >= 15)
5764             base_addr = *(uint64_t *) ((uint8_t *) dyld_all_image_infos_address
5765                           + 176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5766         } else {
5767           sharedCacheUUID_address =
5768               (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5769                          84); // sharedCacheUUID <mach-o/dyld_images.h>
5770           if (*version >= 15) {
5771             base_addr = 0;
5772             base_addr = *(uint32_t *) ((uint8_t *) dyld_all_image_infos_address
5773                           + 100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5774           }
5775         }
5776         uuid = UUID::fromOptionalData(sharedCacheUUID_address, sizeof(uuid_t));
5777       }
5778     }
5779   } else {
5780     // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
5781     dyld_process_info (*dyld_process_info_create)(unsigned int /* task_t */ task, uint64_t timestamp, unsigned int /*kern_return_t*/ *kernelError);
5782     void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
5783     void (*dyld_process_info_release)(dyld_process_info info);
5784 
5785     dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t, unsigned int /*kern_return_t*/ *))
5786                dlsym (RTLD_DEFAULT, "_dyld_process_info_create");
5787     dyld_process_info_get_cache = (void (*)(void *, void *))
5788                dlsym (RTLD_DEFAULT, "_dyld_process_info_get_cache");
5789     dyld_process_info_release = (void (*)(void *))
5790                dlsym (RTLD_DEFAULT, "_dyld_process_info_release");
5791 
5792     if (dyld_process_info_create && dyld_process_info_get_cache) {
5793       unsigned int /*kern_return_t */ kern_ret;
5794 		  dyld_process_info process_info = dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
5795       if (process_info) {
5796         struct lldb_copy__dyld_process_cache_info sc_info;
5797         memset (&sc_info, 0, sizeof (struct lldb_copy__dyld_process_cache_info));
5798         dyld_process_info_get_cache (process_info, &sc_info);
5799         if (sc_info.cacheBaseAddress != 0) {
5800           base_addr = sc_info.cacheBaseAddress;
5801           uuid = UUID::fromOptionalData(sc_info.cacheUUID, sizeof(uuid_t));
5802         }
5803         dyld_process_info_release (process_info);
5804       }
5805     }
5806   }
5807   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_PROCESS));
5808   if (log && uuid.IsValid())
5809     LLDB_LOGF(log,
5810               "lldb's in-memory shared cache has a UUID of %s base address of "
5811               "0x%" PRIx64,
5812               uuid.GetAsString().c_str(), base_addr);
5813 #endif
5814 }
5815 
5816 llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() {
5817   if (!m_min_os_version) {
5818     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5819     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5820       const lldb::offset_t load_cmd_offset = offset;
5821 
5822       version_min_command lc;
5823       if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5824         break;
5825       if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5826           lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5827           lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5828           lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5829         if (m_data.GetU32(&offset, &lc.version,
5830                           (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5831           const uint32_t xxxx = lc.version >> 16;
5832           const uint32_t yy = (lc.version >> 8) & 0xffu;
5833           const uint32_t zz = lc.version & 0xffu;
5834           if (xxxx) {
5835             m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5836             break;
5837           }
5838         }
5839       } else if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5840         // struct build_version_command {
5841         //     uint32_t    cmd;            /* LC_BUILD_VERSION */
5842         //     uint32_t    cmdsize;        /* sizeof(struct build_version_command) plus */
5843         //                                 /* ntools * sizeof(struct build_tool_version) */
5844         //     uint32_t    platform;       /* platform */
5845         //     uint32_t    minos;          /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
5846         //     uint32_t    sdk;            /* X.Y.Z is encoded in nibbles xxxx.yy.zz */
5847         //     uint32_t    ntools;         /* number of tool entries following this */
5848         // };
5849 
5850         offset += 4;  // skip platform
5851         uint32_t minos = m_data.GetU32(&offset);
5852 
5853         const uint32_t xxxx = minos >> 16;
5854         const uint32_t yy = (minos >> 8) & 0xffu;
5855         const uint32_t zz = minos & 0xffu;
5856         if (xxxx) {
5857             m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5858             break;
5859         }
5860       }
5861 
5862       offset = load_cmd_offset + lc.cmdsize;
5863     }
5864 
5865     if (!m_min_os_version) {
5866       // Set version to an empty value so we don't keep trying to
5867       m_min_os_version = llvm::VersionTuple();
5868     }
5869   }
5870 
5871   return *m_min_os_version;
5872 }
5873 
5874 llvm::VersionTuple ObjectFileMachO::GetSDKVersion() {
5875   if (!m_sdk_versions.hasValue()) {
5876     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5877     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5878       const lldb::offset_t load_cmd_offset = offset;
5879 
5880       version_min_command lc;
5881       if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5882         break;
5883       if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5884           lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5885           lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5886           lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5887         if (m_data.GetU32(&offset, &lc.version,
5888                           (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5889           const uint32_t xxxx = lc.sdk >> 16;
5890           const uint32_t yy = (lc.sdk >> 8) & 0xffu;
5891           const uint32_t zz = lc.sdk & 0xffu;
5892           if (xxxx) {
5893             m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz);
5894             break;
5895           } else {
5896             GetModule()->ReportWarning(
5897                 "minimum OS version load command with invalid (0) version found.");
5898           }
5899         }
5900       }
5901       offset = load_cmd_offset + lc.cmdsize;
5902     }
5903 
5904     if (!m_sdk_versions.hasValue()) {
5905       offset = MachHeaderSizeFromMagic(m_header.magic);
5906       for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5907         const lldb::offset_t load_cmd_offset = offset;
5908 
5909         version_min_command lc;
5910         if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5911           break;
5912         if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5913           // struct build_version_command {
5914           //     uint32_t    cmd;            /* LC_BUILD_VERSION */
5915           //     uint32_t    cmdsize;        /* sizeof(struct
5916           //     build_version_command) plus */
5917           //                                 /* ntools * sizeof(struct
5918           //                                 build_tool_version) */
5919           //     uint32_t    platform;       /* platform */
5920           //     uint32_t    minos;          /* X.Y.Z is encoded in nibbles
5921           //     xxxx.yy.zz */ uint32_t    sdk;            /* X.Y.Z is encoded
5922           //     in nibbles xxxx.yy.zz */ uint32_t    ntools;         /* number
5923           //     of tool entries following this */
5924           // };
5925 
5926           offset += 4; // skip platform
5927           uint32_t minos = m_data.GetU32(&offset);
5928 
5929           const uint32_t xxxx = minos >> 16;
5930           const uint32_t yy = (minos >> 8) & 0xffu;
5931           const uint32_t zz = minos & 0xffu;
5932           if (xxxx) {
5933             m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz);
5934             break;
5935           }
5936         }
5937         offset = load_cmd_offset + lc.cmdsize;
5938       }
5939     }
5940 
5941     if (!m_sdk_versions.hasValue())
5942       m_sdk_versions = llvm::VersionTuple();
5943   }
5944 
5945   return m_sdk_versions.getValue();
5946 }
5947 
5948 bool ObjectFileMachO::GetIsDynamicLinkEditor() {
5949   return m_header.filetype == llvm::MachO::MH_DYLINKER;
5950 }
5951 
5952 bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
5953   return m_allow_assembly_emulation_unwind_plans;
5954 }
5955 
5956 // PluginInterface protocol
5957 lldb_private::ConstString ObjectFileMachO::GetPluginName() {
5958   return GetPluginNameStatic();
5959 }
5960 
5961 uint32_t ObjectFileMachO::GetPluginVersion() { return 1; }
5962 
5963 Section *ObjectFileMachO::GetMachHeaderSection() {
5964   // Find the first address of the mach header which is the first non-zero file
5965   // sized section whose file offset is zero. This is the base file address of
5966   // the mach-o file which can be subtracted from the vmaddr of the other
5967   // segments found in memory and added to the load address
5968   ModuleSP module_sp = GetModule();
5969   if (!module_sp)
5970     return nullptr;
5971   SectionList *section_list = GetSectionList();
5972   if (!section_list)
5973     return nullptr;
5974   const size_t num_sections = section_list->GetSize();
5975   for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5976     Section *section = section_list->GetSectionAtIndex(sect_idx).get();
5977     if (section->GetFileOffset() == 0 && SectionIsLoadable(section))
5978       return section;
5979   }
5980   return nullptr;
5981 }
5982 
5983 bool ObjectFileMachO::SectionIsLoadable(const Section *section) {
5984   if (!section)
5985     return false;
5986   const bool is_dsym = (m_header.filetype == MH_DSYM);
5987   if (section->GetFileSize() == 0 && !is_dsym)
5988     return false;
5989   if (section->IsThreadSpecific())
5990     return false;
5991   if (GetModule().get() != section->GetModule().get())
5992     return false;
5993   // Be careful with __LINKEDIT and __DWARF segments
5994   if (section->GetName() == GetSegmentNameLINKEDIT() ||
5995       section->GetName() == GetSegmentNameDWARF()) {
5996     // Only map __LINKEDIT and __DWARF if we have an in memory image and
5997     // this isn't a kernel binary like a kext or mach_kernel.
5998     const bool is_memory_image = (bool)m_process_wp.lock();
5999     const Strata strata = GetStrata();
6000     if (is_memory_image == false || strata == eStrataKernel)
6001       return false;
6002   }
6003   return true;
6004 }
6005 
6006 lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
6007     lldb::addr_t header_load_address, const Section *header_section,
6008     const Section *section) {
6009   ModuleSP module_sp = GetModule();
6010   if (module_sp && header_section && section &&
6011       header_load_address != LLDB_INVALID_ADDRESS) {
6012     lldb::addr_t file_addr = header_section->GetFileAddress();
6013     if (file_addr != LLDB_INVALID_ADDRESS && SectionIsLoadable(section))
6014       return section->GetFileAddress() - file_addr + header_load_address;
6015   }
6016   return LLDB_INVALID_ADDRESS;
6017 }
6018 
6019 bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
6020                                      bool value_is_offset) {
6021   ModuleSP module_sp = GetModule();
6022   if (module_sp) {
6023     size_t num_loaded_sections = 0;
6024     SectionList *section_list = GetSectionList();
6025     if (section_list) {
6026       const size_t num_sections = section_list->GetSize();
6027 
6028       if (value_is_offset) {
6029         // "value" is an offset to apply to each top level segment
6030         for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6031           // Iterate through the object file sections to find all of the
6032           // sections that size on disk (to avoid __PAGEZERO) and load them
6033           SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
6034           if (SectionIsLoadable(section_sp.get()))
6035             if (target.GetSectionLoadList().SetSectionLoadAddress(
6036                     section_sp, section_sp->GetFileAddress() + value))
6037               ++num_loaded_sections;
6038         }
6039       } else {
6040         // "value" is the new base address of the mach_header, adjust each
6041         // section accordingly
6042 
6043         Section *mach_header_section = GetMachHeaderSection();
6044         if (mach_header_section) {
6045           for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6046             SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
6047 
6048             lldb::addr_t section_load_addr =
6049                 CalculateSectionLoadAddressForMemoryImage(
6050                     value, mach_header_section, section_sp.get());
6051             if (section_load_addr != LLDB_INVALID_ADDRESS) {
6052               if (target.GetSectionLoadList().SetSectionLoadAddress(
6053                       section_sp, section_load_addr))
6054                 ++num_loaded_sections;
6055             }
6056           }
6057         }
6058       }
6059     }
6060     return num_loaded_sections > 0;
6061   }
6062   return false;
6063 }
6064 
6065 bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
6066                                const FileSpec &outfile, Status &error) {
6067   if (process_sp) {
6068     Target &target = process_sp->GetTarget();
6069     const ArchSpec target_arch = target.GetArchitecture();
6070     const llvm::Triple &target_triple = target_arch.GetTriple();
6071     if (target_triple.getVendor() == llvm::Triple::Apple &&
6072         (target_triple.getOS() == llvm::Triple::MacOSX ||
6073          target_triple.getOS() == llvm::Triple::IOS ||
6074          target_triple.getOS() == llvm::Triple::WatchOS ||
6075          target_triple.getOS() == llvm::Triple::TvOS)) {
6076          // NEED_BRIDGEOS_TRIPLE target_triple.getOS() == llvm::Triple::BridgeOS)) {
6077       bool make_core = false;
6078       switch (target_arch.GetMachine()) {
6079       case llvm::Triple::aarch64:
6080       case llvm::Triple::arm:
6081       case llvm::Triple::thumb:
6082       case llvm::Triple::x86:
6083       case llvm::Triple::x86_64:
6084         make_core = true;
6085         break;
6086       default:
6087         error.SetErrorStringWithFormat("unsupported core architecture: %s",
6088                                        target_triple.str().c_str());
6089         break;
6090       }
6091 
6092       if (make_core) {
6093         std::vector<segment_command_64> segment_load_commands;
6094         //                uint32_t range_info_idx = 0;
6095         MemoryRegionInfo range_info;
6096         Status range_error = process_sp->GetMemoryRegionInfo(0, range_info);
6097         const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
6098         const ByteOrder byte_order = target_arch.GetByteOrder();
6099         if (range_error.Success()) {
6100           while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
6101             const addr_t addr = range_info.GetRange().GetRangeBase();
6102             const addr_t size = range_info.GetRange().GetByteSize();
6103 
6104             if (size == 0)
6105               break;
6106 
6107             // Calculate correct protections
6108             uint32_t prot = 0;
6109             if (range_info.GetReadable() == MemoryRegionInfo::eYes)
6110               prot |= VM_PROT_READ;
6111             if (range_info.GetWritable() == MemoryRegionInfo::eYes)
6112               prot |= VM_PROT_WRITE;
6113             if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
6114               prot |= VM_PROT_EXECUTE;
6115 
6116             if (prot != 0) {
6117               uint32_t cmd_type = LC_SEGMENT_64;
6118               uint32_t segment_size = sizeof(segment_command_64);
6119               if (addr_byte_size == 4) {
6120                 cmd_type = LC_SEGMENT;
6121                 segment_size = sizeof(segment_command);
6122               }
6123               segment_command_64 segment = {
6124                   cmd_type,     // uint32_t cmd;
6125                   segment_size, // uint32_t cmdsize;
6126                   {0},          // char segname[16];
6127                   addr, // uint64_t vmaddr;    // uint32_t for 32-bit Mach-O
6128                   size, // uint64_t vmsize;    // uint32_t for 32-bit Mach-O
6129                   0,    // uint64_t fileoff;   // uint32_t for 32-bit Mach-O
6130                   size, // uint64_t filesize;  // uint32_t for 32-bit Mach-O
6131                   prot, // uint32_t maxprot;
6132                   prot, // uint32_t initprot;
6133                   0,    // uint32_t nsects;
6134                   0};   // uint32_t flags;
6135               segment_load_commands.push_back(segment);
6136             } else {
6137               // No protections and a size of 1 used to be returned from old
6138               // debugservers when we asked about a region that was past the
6139               // last memory region and it indicates the end...
6140               if (size == 1)
6141                 break;
6142             }
6143 
6144             range_error = process_sp->GetMemoryRegionInfo(
6145                 range_info.GetRange().GetRangeEnd(), range_info);
6146             if (range_error.Fail())
6147               break;
6148           }
6149 
6150           StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
6151 
6152           mach_header_64 mach_header;
6153           if (addr_byte_size == 8) {
6154             mach_header.magic = MH_MAGIC_64;
6155           } else {
6156             mach_header.magic = MH_MAGIC;
6157           }
6158           mach_header.cputype = target_arch.GetMachOCPUType();
6159           mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
6160           mach_header.filetype = MH_CORE;
6161           mach_header.ncmds = segment_load_commands.size();
6162           mach_header.flags = 0;
6163           mach_header.reserved = 0;
6164           ThreadList &thread_list = process_sp->GetThreadList();
6165           const uint32_t num_threads = thread_list.GetSize();
6166 
6167           // Make an array of LC_THREAD data items. Each one contains the
6168           // contents of the LC_THREAD load command. The data doesn't contain
6169           // the load command + load command size, we will add the load command
6170           // and load command size as we emit the data.
6171           std::vector<StreamString> LC_THREAD_datas(num_threads);
6172           for (auto &LC_THREAD_data : LC_THREAD_datas) {
6173             LC_THREAD_data.GetFlags().Set(Stream::eBinary);
6174             LC_THREAD_data.SetAddressByteSize(addr_byte_size);
6175             LC_THREAD_data.SetByteOrder(byte_order);
6176           }
6177           for (uint32_t thread_idx = 0; thread_idx < num_threads;
6178                ++thread_idx) {
6179             ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
6180             if (thread_sp) {
6181               switch (mach_header.cputype) {
6182               case llvm::MachO::CPU_TYPE_ARM64:
6183                 RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
6184                     thread_sp.get(), LC_THREAD_datas[thread_idx]);
6185                 break;
6186 
6187               case llvm::MachO::CPU_TYPE_ARM:
6188                 RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
6189                     thread_sp.get(), LC_THREAD_datas[thread_idx]);
6190                 break;
6191 
6192               case llvm::MachO::CPU_TYPE_I386:
6193                 RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
6194                     thread_sp.get(), LC_THREAD_datas[thread_idx]);
6195                 break;
6196 
6197               case llvm::MachO::CPU_TYPE_X86_64:
6198                 RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
6199                     thread_sp.get(), LC_THREAD_datas[thread_idx]);
6200                 break;
6201               }
6202             }
6203           }
6204 
6205           // The size of the load command is the size of the segments...
6206           if (addr_byte_size == 8) {
6207             mach_header.sizeofcmds = segment_load_commands.size() *
6208                                      sizeof(struct segment_command_64);
6209           } else {
6210             mach_header.sizeofcmds =
6211                 segment_load_commands.size() * sizeof(struct segment_command);
6212           }
6213 
6214           // and the size of all LC_THREAD load command
6215           for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6216             ++mach_header.ncmds;
6217             mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
6218           }
6219 
6220           // Write the mach header
6221           buffer.PutHex32(mach_header.magic);
6222           buffer.PutHex32(mach_header.cputype);
6223           buffer.PutHex32(mach_header.cpusubtype);
6224           buffer.PutHex32(mach_header.filetype);
6225           buffer.PutHex32(mach_header.ncmds);
6226           buffer.PutHex32(mach_header.sizeofcmds);
6227           buffer.PutHex32(mach_header.flags);
6228           if (addr_byte_size == 8) {
6229             buffer.PutHex32(mach_header.reserved);
6230           }
6231 
6232           // Skip the mach header and all load commands and align to the next
6233           // 0x1000 byte boundary
6234           addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
6235           if (file_offset & 0x00000fff) {
6236             file_offset += 0x00001000ull;
6237             file_offset &= (~0x00001000ull + 1);
6238           }
6239 
6240           for (auto &segment : segment_load_commands) {
6241             segment.fileoff = file_offset;
6242             file_offset += segment.filesize;
6243           }
6244 
6245           // Write out all of the LC_THREAD load commands
6246           for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6247             const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6248             buffer.PutHex32(LC_THREAD);
6249             buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
6250             buffer.Write(LC_THREAD_data.GetString().data(),
6251                          LC_THREAD_data_size);
6252           }
6253 
6254           // Write out all of the segment load commands
6255           for (const auto &segment : segment_load_commands) {
6256             printf("0x%8.8x 0x%8.8x [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
6257                    ") [0x%16.16" PRIx64 " 0x%16.16" PRIx64
6258                    ") 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x]\n",
6259                    segment.cmd, segment.cmdsize, segment.vmaddr,
6260                    segment.vmaddr + segment.vmsize, segment.fileoff,
6261                    segment.filesize, segment.maxprot, segment.initprot,
6262                    segment.nsects, segment.flags);
6263 
6264             buffer.PutHex32(segment.cmd);
6265             buffer.PutHex32(segment.cmdsize);
6266             buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
6267             if (addr_byte_size == 8) {
6268               buffer.PutHex64(segment.vmaddr);
6269               buffer.PutHex64(segment.vmsize);
6270               buffer.PutHex64(segment.fileoff);
6271               buffer.PutHex64(segment.filesize);
6272             } else {
6273               buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
6274               buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
6275               buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
6276               buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
6277             }
6278             buffer.PutHex32(segment.maxprot);
6279             buffer.PutHex32(segment.initprot);
6280             buffer.PutHex32(segment.nsects);
6281             buffer.PutHex32(segment.flags);
6282           }
6283 
6284           File core_file;
6285           std::string core_file_path(outfile.GetPath());
6286           error = FileSystem::Instance().Open(core_file, outfile,
6287                                               File::eOpenOptionWrite |
6288                                                   File::eOpenOptionTruncate |
6289                                                   File::eOpenOptionCanCreate);
6290           if (error.Success()) {
6291             // Read 1 page at a time
6292             uint8_t bytes[0x1000];
6293             // Write the mach header and load commands out to the core file
6294             size_t bytes_written = buffer.GetString().size();
6295             error = core_file.Write(buffer.GetString().data(), bytes_written);
6296             if (error.Success()) {
6297               // Now write the file data for all memory segments in the process
6298               for (const auto &segment : segment_load_commands) {
6299                 if (core_file.SeekFromStart(segment.fileoff) == -1) {
6300                   error.SetErrorStringWithFormat(
6301                       "unable to seek to offset 0x%" PRIx64 " in '%s'",
6302                       segment.fileoff, core_file_path.c_str());
6303                   break;
6304                 }
6305 
6306                 printf("Saving %" PRId64
6307                        " bytes of data for memory region at 0x%" PRIx64 "\n",
6308                        segment.vmsize, segment.vmaddr);
6309                 addr_t bytes_left = segment.vmsize;
6310                 addr_t addr = segment.vmaddr;
6311                 Status memory_read_error;
6312                 while (bytes_left > 0 && error.Success()) {
6313                   const size_t bytes_to_read =
6314                       bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6315 
6316                   // In a savecore setting, we don't really care about caching,
6317                   // as the data is dumped and very likely never read again,
6318                   // so we call ReadMemoryFromInferior to bypass it.
6319                   const size_t bytes_read = process_sp->ReadMemoryFromInferior(
6320                       addr, bytes, bytes_to_read, memory_read_error);
6321 
6322                   if (bytes_read == bytes_to_read) {
6323                     size_t bytes_written = bytes_read;
6324                     error = core_file.Write(bytes, bytes_written);
6325                     bytes_left -= bytes_read;
6326                     addr += bytes_read;
6327                   } else {
6328                     // Some pages within regions are not readable, those should
6329                     // be zero filled
6330                     memset(bytes, 0, bytes_to_read);
6331                     size_t bytes_written = bytes_to_read;
6332                     error = core_file.Write(bytes, bytes_written);
6333                     bytes_left -= bytes_to_read;
6334                     addr += bytes_to_read;
6335                   }
6336                 }
6337               }
6338             }
6339           }
6340         } else {
6341           error.SetErrorString(
6342               "process doesn't support getting memory region info");
6343         }
6344       }
6345       return true; // This is the right plug to handle saving core files for
6346                    // this process
6347     }
6348   }
6349   return false;
6350 }
6351