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