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