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 = GetArchitecture();
2542     char dsc_path[PATH_MAX];
2543     char dsc_path_development[PATH_MAX];
2544 
2545     snprintf(
2546         dsc_path, sizeof(dsc_path), "%s%s%s",
2547         "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2548                                                    */
2549         "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
2550         header_arch.GetArchitectureName());
2551 
2552     snprintf(
2553         dsc_path_development, sizeof(dsc_path), "%s%s%s%s",
2554         "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR
2555                                                    */
2556         "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */
2557         header_arch.GetArchitectureName(), ".development");
2558 
2559     FileSpec dsc_nondevelopment_filespec(dsc_path);
2560     FileSpec dsc_development_filespec(dsc_path_development);
2561     FileSpec dsc_filespec;
2562 
2563     UUID dsc_uuid;
2564     UUID process_shared_cache_uuid;
2565     addr_t process_shared_cache_base_addr;
2566 
2567     if (process) {
2568       GetProcessSharedCacheUUID(process, process_shared_cache_base_addr,
2569                                 process_shared_cache_uuid);
2570     }
2571 
2572     // First see if we can find an exact match for the inferior process
2573     // shared cache UUID in the development or non-development shared caches
2574     // on disk.
2575     if (process_shared_cache_uuid.IsValid()) {
2576       if (FileSystem::Instance().Exists(dsc_development_filespec)) {
2577         UUID dsc_development_uuid = GetSharedCacheUUID(
2578             dsc_development_filespec, byte_order, addr_byte_size);
2579         if (dsc_development_uuid.IsValid() &&
2580             dsc_development_uuid == process_shared_cache_uuid) {
2581           dsc_filespec = dsc_development_filespec;
2582           dsc_uuid = dsc_development_uuid;
2583         }
2584       }
2585       if (!dsc_uuid.IsValid() &&
2586           FileSystem::Instance().Exists(dsc_nondevelopment_filespec)) {
2587         UUID dsc_nondevelopment_uuid = GetSharedCacheUUID(
2588             dsc_nondevelopment_filespec, byte_order, addr_byte_size);
2589         if (dsc_nondevelopment_uuid.IsValid() &&
2590             dsc_nondevelopment_uuid == process_shared_cache_uuid) {
2591           dsc_filespec = dsc_nondevelopment_filespec;
2592           dsc_uuid = dsc_nondevelopment_uuid;
2593         }
2594       }
2595     }
2596 
2597     // Failing a UUID match, prefer the development dyld_shared cache if both
2598     // are present.
2599     if (!FileSystem::Instance().Exists(dsc_filespec)) {
2600       if (FileSystem::Instance().Exists(dsc_development_filespec)) {
2601         dsc_filespec = dsc_development_filespec;
2602       } else {
2603         dsc_filespec = dsc_nondevelopment_filespec;
2604       }
2605     }
2606 
2607     /* The dyld_cache_header has a pointer to the
2608        dyld_cache_local_symbols_info structure (localSymbolsOffset).
2609        The dyld_cache_local_symbols_info structure gives us three things:
2610          1. The start and count of the nlist records in the dyld_shared_cache
2611        file
2612          2. The start and size of the strings for these nlist records
2613          3. The start and count of dyld_cache_local_symbols_entry entries
2614 
2615        There is one dyld_cache_local_symbols_entry per dylib/framework in the
2616        dyld shared cache.
2617        The "dylibOffset" field is the Mach-O header of this dylib/framework in
2618        the dyld shared cache.
2619        The dyld_cache_local_symbols_entry also lists the start of this
2620        dylib/framework's nlist records
2621        and the count of how many nlist records there are for this
2622        dylib/framework.
2623     */
2624 
2625     // Process the dyld shared cache header to find the unmapped symbols
2626 
2627     DataBufferSP dsc_data_sp = MapFileData(
2628         dsc_filespec, sizeof(struct lldb_copy_dyld_cache_header_v1), 0);
2629     if (!dsc_uuid.IsValid()) {
2630       dsc_uuid = GetSharedCacheUUID(dsc_filespec, byte_order, addr_byte_size);
2631     }
2632     if (dsc_data_sp) {
2633       DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2634 
2635       bool uuid_match = true;
2636       if (dsc_uuid.IsValid() && process) {
2637         if (process_shared_cache_uuid.IsValid() &&
2638             dsc_uuid != process_shared_cache_uuid) {
2639           // The on-disk dyld_shared_cache file is not the same as the one in
2640           // this process' memory, don't use it.
2641           uuid_match = false;
2642           ModuleSP module_sp(GetModule());
2643           if (module_sp)
2644             module_sp->ReportWarning("process shared cache does not match "
2645                                      "on-disk dyld_shared_cache file, some "
2646                                      "symbol names will be missing.");
2647         }
2648       }
2649 
2650       offset = offsetof(struct lldb_copy_dyld_cache_header_v1, mappingOffset);
2651 
2652       uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
2653 
2654       // If the mappingOffset points to a location inside the header, we've
2655       // opened an old dyld shared cache, and should not proceed further.
2656       if (uuid_match &&
2657           mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v1)) {
2658 
2659         DataBufferSP dsc_mapping_info_data_sp = MapFileData(
2660             dsc_filespec, sizeof(struct lldb_copy_dyld_cache_mapping_info),
2661             mappingOffset);
2662 
2663         DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp,
2664                                             byte_order, addr_byte_size);
2665         offset = 0;
2666 
2667         // The File addresses (from the in-memory Mach-O load commands) for
2668         // the shared libraries in the shared library cache need to be
2669         // adjusted by an offset to match up with the dylibOffset identifying
2670         // field in the dyld_cache_local_symbol_entry's.  This offset is
2671         // recorded in mapping_offset_value.
2672         const uint64_t mapping_offset_value =
2673             dsc_mapping_info_data.GetU64(&offset);
2674 
2675         offset =
2676             offsetof(struct lldb_copy_dyld_cache_header_v1, localSymbolsOffset);
2677         uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2678         uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
2679 
2680         if (localSymbolsOffset && localSymbolsSize) {
2681           // Map the local symbols
2682           DataBufferSP dsc_local_symbols_data_sp =
2683               MapFileData(dsc_filespec, localSymbolsSize, localSymbolsOffset);
2684 
2685           if (dsc_local_symbols_data_sp) {
2686             DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp,
2687                                                  byte_order, addr_byte_size);
2688 
2689             offset = 0;
2690 
2691             typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
2692             typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
2693             UndefinedNameToDescMap undefined_name_to_desc;
2694             SymbolIndexToName reexport_shlib_needs_fixup;
2695 
2696             // Read the local_symbols_infos struct in one shot
2697             struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
2698             dsc_local_symbols_data.GetU32(&offset,
2699                                           &local_symbols_info.nlistOffset, 6);
2700 
2701             SectionSP text_section_sp(
2702                 section_list->FindSectionByName(GetSegmentNameTEXT()));
2703 
2704             uint32_t header_file_offset =
2705                 (text_section_sp->GetFileAddress() - mapping_offset_value);
2706 
2707             offset = local_symbols_info.entriesOffset;
2708             for (uint32_t entry_index = 0;
2709                  entry_index < local_symbols_info.entriesCount; entry_index++) {
2710               struct lldb_copy_dyld_cache_local_symbols_entry
2711                   local_symbols_entry;
2712               local_symbols_entry.dylibOffset =
2713                   dsc_local_symbols_data.GetU32(&offset);
2714               local_symbols_entry.nlistStartIndex =
2715                   dsc_local_symbols_data.GetU32(&offset);
2716               local_symbols_entry.nlistCount =
2717                   dsc_local_symbols_data.GetU32(&offset);
2718 
2719               if (header_file_offset == local_symbols_entry.dylibOffset) {
2720                 unmapped_local_symbols_found = local_symbols_entry.nlistCount;
2721 
2722                 // The normal nlist code cannot correctly size the Symbols
2723                 // array, we need to allocate it here.
2724                 sym = symtab->Resize(
2725                     symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2726                     unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2727                 num_syms = symtab->GetNumSymbols();
2728 
2729                 nlist_data_offset =
2730                     local_symbols_info.nlistOffset +
2731                     (nlist_byte_size * local_symbols_entry.nlistStartIndex);
2732                 uint32_t string_table_offset = local_symbols_info.stringsOffset;
2733 
2734                 for (uint32_t nlist_index = 0;
2735                      nlist_index < local_symbols_entry.nlistCount;
2736                      nlist_index++) {
2737                   /////////////////////////////
2738                   {
2739                     llvm::Optional<struct nlist_64> nlist_maybe =
2740                         ParseNList(dsc_local_symbols_data, nlist_data_offset,
2741                                    nlist_byte_size);
2742                     if (!nlist_maybe)
2743                       break;
2744                     struct nlist_64 nlist = *nlist_maybe;
2745 
2746                     SymbolType type = eSymbolTypeInvalid;
2747                     const char *symbol_name = dsc_local_symbols_data.PeekCStr(
2748                         string_table_offset + nlist.n_strx);
2749 
2750                     if (symbol_name == NULL) {
2751                       // No symbol should be NULL, even the symbols with no
2752                       // string values should have an offset zero which
2753                       // points to an empty C-string
2754                       Host::SystemLog(
2755                           Host::eSystemLogError,
2756                           "error: DSC unmapped local symbol[%u] has invalid "
2757                           "string table offset 0x%x in %s, ignoring symbol\n",
2758                           entry_index, nlist.n_strx,
2759                           module_sp->GetFileSpec().GetPath().c_str());
2760                       continue;
2761                     }
2762                     if (symbol_name[0] == '\0')
2763                       symbol_name = NULL;
2764 
2765                     const char *symbol_name_non_abi_mangled = NULL;
2766 
2767                     SectionSP symbol_section;
2768                     uint32_t symbol_byte_size = 0;
2769                     bool add_nlist = true;
2770                     bool is_debug = ((nlist.n_type & N_STAB) != 0);
2771                     bool demangled_is_synthesized = false;
2772                     bool is_gsym = false;
2773                     bool set_value = true;
2774 
2775                     assert(sym_idx < num_syms);
2776 
2777                     sym[sym_idx].SetDebug(is_debug);
2778 
2779                     if (is_debug) {
2780                       switch (nlist.n_type) {
2781                       case N_GSYM:
2782                         // global symbol: name,,NO_SECT,type,0
2783                         // Sometimes the N_GSYM value contains the address.
2784 
2785                         // FIXME: In the .o files, we have a GSYM and a debug
2786                         // symbol for all the ObjC data.  They
2787                         // have the same address, but we want to ensure that
2788                         // we always find only the real symbol, 'cause we
2789                         // don't currently correctly attribute the
2790                         // GSYM one to the ObjCClass/Ivar/MetaClass
2791                         // symbol type.  This is a temporary hack to make
2792                         // sure the ObjectiveC symbols get treated correctly.
2793                         // To do this right, we should coalesce all the GSYM
2794                         // & global symbols that have the same address.
2795 
2796                         is_gsym = true;
2797                         sym[sym_idx].SetExternal(true);
2798 
2799                         if (symbol_name && symbol_name[0] == '_' &&
2800                             symbol_name[1] == 'O') {
2801                           llvm::StringRef symbol_name_ref(symbol_name);
2802                           if (symbol_name_ref.startswith(
2803                                   g_objc_v2_prefix_class)) {
2804                             symbol_name_non_abi_mangled = symbol_name + 1;
2805                             symbol_name =
2806                                 symbol_name + g_objc_v2_prefix_class.size();
2807                             type = eSymbolTypeObjCClass;
2808                             demangled_is_synthesized = true;
2809 
2810                           } else if (symbol_name_ref.startswith(
2811                                          g_objc_v2_prefix_metaclass)) {
2812                             symbol_name_non_abi_mangled = symbol_name + 1;
2813                             symbol_name =
2814                                 symbol_name + g_objc_v2_prefix_metaclass.size();
2815                             type = eSymbolTypeObjCMetaClass;
2816                             demangled_is_synthesized = true;
2817                           } else if (symbol_name_ref.startswith(
2818                                          g_objc_v2_prefix_ivar)) {
2819                             symbol_name_non_abi_mangled = symbol_name + 1;
2820                             symbol_name =
2821                                 symbol_name + g_objc_v2_prefix_ivar.size();
2822                             type = eSymbolTypeObjCIVar;
2823                             demangled_is_synthesized = true;
2824                           }
2825                         } else {
2826                           if (nlist.n_value != 0)
2827                             symbol_section = section_info.GetSection(
2828                                 nlist.n_sect, nlist.n_value);
2829                           type = eSymbolTypeData;
2830                         }
2831                         break;
2832 
2833                       case N_FNAME:
2834                         // procedure name (f77 kludge): name,,NO_SECT,0,0
2835                         type = eSymbolTypeCompiler;
2836                         break;
2837 
2838                       case N_FUN:
2839                         // procedure: name,,n_sect,linenumber,address
2840                         if (symbol_name) {
2841                           type = eSymbolTypeCode;
2842                           symbol_section = section_info.GetSection(
2843                               nlist.n_sect, nlist.n_value);
2844 
2845                           N_FUN_addr_to_sym_idx.insert(
2846                               std::make_pair(nlist.n_value, sym_idx));
2847                           // We use the current number of symbols in the
2848                           // symbol table in lieu of using nlist_idx in case
2849                           // we ever start trimming entries out
2850                           N_FUN_indexes.push_back(sym_idx);
2851                         } else {
2852                           type = eSymbolTypeCompiler;
2853 
2854                           if (!N_FUN_indexes.empty()) {
2855                             // Copy the size of the function into the
2856                             // original
2857                             // STAB entry so we don't have
2858                             // to hunt for it later
2859                             symtab->SymbolAtIndex(N_FUN_indexes.back())
2860                                 ->SetByteSize(nlist.n_value);
2861                             N_FUN_indexes.pop_back();
2862                             // We don't really need the end function STAB as
2863                             // it contains the size which we already placed
2864                             // with the original symbol, so don't add it if
2865                             // we want a minimal symbol table
2866                             add_nlist = false;
2867                           }
2868                         }
2869                         break;
2870 
2871                       case N_STSYM:
2872                         // static symbol: name,,n_sect,type,address
2873                         N_STSYM_addr_to_sym_idx.insert(
2874                             std::make_pair(nlist.n_value, sym_idx));
2875                         symbol_section = section_info.GetSection(nlist.n_sect,
2876                                                                  nlist.n_value);
2877                         if (symbol_name && symbol_name[0]) {
2878                           type = ObjectFile::GetSymbolTypeFromName(
2879                               symbol_name + 1, eSymbolTypeData);
2880                         }
2881                         break;
2882 
2883                       case N_LCSYM:
2884                         // .lcomm symbol: name,,n_sect,type,address
2885                         symbol_section = section_info.GetSection(nlist.n_sect,
2886                                                                  nlist.n_value);
2887                         type = eSymbolTypeCommonBlock;
2888                         break;
2889 
2890                       case N_BNSYM:
2891                         // We use the current number of symbols in the symbol
2892                         // table in lieu of using nlist_idx in case we ever
2893                         // start trimming entries out Skip these if we want
2894                         // minimal symbol tables
2895                         add_nlist = false;
2896                         break;
2897 
2898                       case N_ENSYM:
2899                         // Set the size of the N_BNSYM to the terminating
2900                         // index of this N_ENSYM so that we can always skip
2901                         // the entire symbol if we need to navigate more
2902                         // quickly at the source level when parsing STABS
2903                         // Skip these if we want minimal symbol tables
2904                         add_nlist = false;
2905                         break;
2906 
2907                       case N_OPT:
2908                         // emitted with gcc2_compiled and in gcc source
2909                         type = eSymbolTypeCompiler;
2910                         break;
2911 
2912                       case N_RSYM:
2913                         // register sym: name,,NO_SECT,type,register
2914                         type = eSymbolTypeVariable;
2915                         break;
2916 
2917                       case N_SLINE:
2918                         // src line: 0,,n_sect,linenumber,address
2919                         symbol_section = section_info.GetSection(nlist.n_sect,
2920                                                                  nlist.n_value);
2921                         type = eSymbolTypeLineEntry;
2922                         break;
2923 
2924                       case N_SSYM:
2925                         // structure elt: name,,NO_SECT,type,struct_offset
2926                         type = eSymbolTypeVariableType;
2927                         break;
2928 
2929                       case N_SO:
2930                         // source file name
2931                         type = eSymbolTypeSourceFile;
2932                         if (symbol_name == NULL) {
2933                           add_nlist = false;
2934                           if (N_SO_index != UINT32_MAX) {
2935                             // Set the size of the N_SO to the terminating
2936                             // index of this N_SO so that we can always skip
2937                             // the entire N_SO if we need to navigate more
2938                             // quickly at the source level when parsing STABS
2939                             symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
2940                             symbol_ptr->SetByteSize(sym_idx);
2941                             symbol_ptr->SetSizeIsSibling(true);
2942                           }
2943                           N_NSYM_indexes.clear();
2944                           N_INCL_indexes.clear();
2945                           N_BRAC_indexes.clear();
2946                           N_COMM_indexes.clear();
2947                           N_FUN_indexes.clear();
2948                           N_SO_index = UINT32_MAX;
2949                         } else {
2950                           // We use the current number of symbols in the
2951                           // symbol table in lieu of using nlist_idx in case
2952                           // we ever start trimming entries out
2953                           const bool N_SO_has_full_path = symbol_name[0] == '/';
2954                           if (N_SO_has_full_path) {
2955                             if ((N_SO_index == sym_idx - 1) &&
2956                                 ((sym_idx - 1) < num_syms)) {
2957                               // We have two consecutive N_SO entries where
2958                               // the first contains a directory and the
2959                               // second contains a full path.
2960                               sym[sym_idx - 1].GetMangled().SetValue(
2961                                   ConstString(symbol_name), false);
2962                               m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
2963                               add_nlist = false;
2964                             } else {
2965                               // This is the first entry in a N_SO that
2966                               // contains a directory or
2967                               // a full path to the source file
2968                               N_SO_index = sym_idx;
2969                             }
2970                           } else if ((N_SO_index == sym_idx - 1) &&
2971                                      ((sym_idx - 1) < num_syms)) {
2972                             // This is usually the second N_SO entry that
2973                             // contains just the filename, so here we combine
2974                             // it with the first one if we are minimizing the
2975                             // symbol table
2976                             const char *so_path =
2977                                 sym[sym_idx - 1]
2978                                     .GetMangled()
2979                                     .GetDemangledName(
2980                                         lldb::eLanguageTypeUnknown)
2981                                     .AsCString();
2982                             if (so_path && so_path[0]) {
2983                               std::string full_so_path(so_path);
2984                               const size_t double_slash_pos =
2985                                   full_so_path.find("//");
2986                               if (double_slash_pos != std::string::npos) {
2987                                 // The linker has been generating bad N_SO
2988                                 // entries with doubled up paths
2989                                 // in the format "%s%s" where the first
2990                                 // string in the DW_AT_comp_dir, and the
2991                                 // second is the directory for the source
2992                                 // file so you end up with a path that looks
2993                                 // like "/tmp/src//tmp/src/"
2994                                 FileSpec so_dir(so_path);
2995                                 if (!FileSystem::Instance().Exists(so_dir)) {
2996                                   so_dir.SetFile(
2997                                       &full_so_path[double_slash_pos + 1],
2998                                       FileSpec::Style::native);
2999                                   if (FileSystem::Instance().Exists(so_dir)) {
3000                                     // Trim off the incorrect path
3001                                     full_so_path.erase(0, double_slash_pos + 1);
3002                                   }
3003                                 }
3004                               }
3005                               if (*full_so_path.rbegin() != '/')
3006                                 full_so_path += '/';
3007                               full_so_path += symbol_name;
3008                               sym[sym_idx - 1].GetMangled().SetValue(
3009                                   ConstString(full_so_path.c_str()), false);
3010                               add_nlist = false;
3011                               m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3012                             }
3013                           } else {
3014                             // This could be a relative path to a N_SO
3015                             N_SO_index = sym_idx;
3016                           }
3017                         }
3018                         break;
3019 
3020                       case N_OSO:
3021                         // object file name: name,,0,0,st_mtime
3022                         type = eSymbolTypeObjectFile;
3023                         break;
3024 
3025                       case N_LSYM:
3026                         // local sym: name,,NO_SECT,type,offset
3027                         type = eSymbolTypeLocal;
3028                         break;
3029 
3030                       // INCL scopes
3031                       case N_BINCL:
3032                         // include file beginning: name,,NO_SECT,0,sum We use
3033                         // the current number of symbols in the symbol table
3034                         // in lieu of using nlist_idx in case we ever start
3035                         // trimming entries out
3036                         N_INCL_indexes.push_back(sym_idx);
3037                         type = eSymbolTypeScopeBegin;
3038                         break;
3039 
3040                       case N_EINCL:
3041                         // include file end: name,,NO_SECT,0,0
3042                         // Set the size of the N_BINCL to the terminating
3043                         // index of this N_EINCL so that we can always skip
3044                         // the entire symbol if we need to navigate more
3045                         // quickly at the source level when parsing STABS
3046                         if (!N_INCL_indexes.empty()) {
3047                           symbol_ptr =
3048                               symtab->SymbolAtIndex(N_INCL_indexes.back());
3049                           symbol_ptr->SetByteSize(sym_idx + 1);
3050                           symbol_ptr->SetSizeIsSibling(true);
3051                           N_INCL_indexes.pop_back();
3052                         }
3053                         type = eSymbolTypeScopeEnd;
3054                         break;
3055 
3056                       case N_SOL:
3057                         // #included file name: name,,n_sect,0,address
3058                         type = eSymbolTypeHeaderFile;
3059 
3060                         // We currently don't use the header files on darwin
3061                         add_nlist = false;
3062                         break;
3063 
3064                       case N_PARAMS:
3065                         // compiler parameters: name,,NO_SECT,0,0
3066                         type = eSymbolTypeCompiler;
3067                         break;
3068 
3069                       case N_VERSION:
3070                         // compiler version: name,,NO_SECT,0,0
3071                         type = eSymbolTypeCompiler;
3072                         break;
3073 
3074                       case N_OLEVEL:
3075                         // compiler -O level: name,,NO_SECT,0,0
3076                         type = eSymbolTypeCompiler;
3077                         break;
3078 
3079                       case N_PSYM:
3080                         // parameter: name,,NO_SECT,type,offset
3081                         type = eSymbolTypeVariable;
3082                         break;
3083 
3084                       case N_ENTRY:
3085                         // alternate entry: name,,n_sect,linenumber,address
3086                         symbol_section = section_info.GetSection(nlist.n_sect,
3087                                                                  nlist.n_value);
3088                         type = eSymbolTypeLineEntry;
3089                         break;
3090 
3091                       // Left and Right Braces
3092                       case N_LBRAC:
3093                         // left bracket: 0,,NO_SECT,nesting level,address We
3094                         // use the current number of symbols in the symbol
3095                         // table in lieu of using nlist_idx in case we ever
3096                         // start trimming entries out
3097                         symbol_section = section_info.GetSection(nlist.n_sect,
3098                                                                  nlist.n_value);
3099                         N_BRAC_indexes.push_back(sym_idx);
3100                         type = eSymbolTypeScopeBegin;
3101                         break;
3102 
3103                       case N_RBRAC:
3104                         // right bracket: 0,,NO_SECT,nesting level,address
3105                         // Set the size of the N_LBRAC to the terminating
3106                         // index of this N_RBRAC so that we can always skip
3107                         // the entire symbol if we need to navigate more
3108                         // quickly at the source level when parsing STABS
3109                         symbol_section = section_info.GetSection(nlist.n_sect,
3110                                                                  nlist.n_value);
3111                         if (!N_BRAC_indexes.empty()) {
3112                           symbol_ptr =
3113                               symtab->SymbolAtIndex(N_BRAC_indexes.back());
3114                           symbol_ptr->SetByteSize(sym_idx + 1);
3115                           symbol_ptr->SetSizeIsSibling(true);
3116                           N_BRAC_indexes.pop_back();
3117                         }
3118                         type = eSymbolTypeScopeEnd;
3119                         break;
3120 
3121                       case N_EXCL:
3122                         // deleted include file: name,,NO_SECT,0,sum
3123                         type = eSymbolTypeHeaderFile;
3124                         break;
3125 
3126                       // COMM scopes
3127                       case N_BCOMM:
3128                         // begin common: name,,NO_SECT,0,0
3129                         // We use the current number of symbols in the symbol
3130                         // table in lieu of using nlist_idx in case we ever
3131                         // start trimming entries out
3132                         type = eSymbolTypeScopeBegin;
3133                         N_COMM_indexes.push_back(sym_idx);
3134                         break;
3135 
3136                       case N_ECOML:
3137                         // end common (local name): 0,,n_sect,0,address
3138                         symbol_section = section_info.GetSection(nlist.n_sect,
3139                                                                  nlist.n_value);
3140                         // Fall through
3141 
3142                       case N_ECOMM:
3143                         // end common: name,,n_sect,0,0
3144                         // Set the size of the N_BCOMM to the terminating
3145                         // index of this N_ECOMM/N_ECOML so that we can
3146                         // always skip the entire symbol if we need to
3147                         // navigate more quickly at the source level when
3148                         // parsing STABS
3149                         if (!N_COMM_indexes.empty()) {
3150                           symbol_ptr =
3151                               symtab->SymbolAtIndex(N_COMM_indexes.back());
3152                           symbol_ptr->SetByteSize(sym_idx + 1);
3153                           symbol_ptr->SetSizeIsSibling(true);
3154                           N_COMM_indexes.pop_back();
3155                         }
3156                         type = eSymbolTypeScopeEnd;
3157                         break;
3158 
3159                       case N_LENG:
3160                         // second stab entry with length information
3161                         type = eSymbolTypeAdditional;
3162                         break;
3163 
3164                       default:
3165                         break;
3166                       }
3167                     } else {
3168                       // uint8_t n_pext    = N_PEXT & nlist.n_type;
3169                       uint8_t n_type = N_TYPE & nlist.n_type;
3170                       sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
3171 
3172                       switch (n_type) {
3173                       case N_INDR: {
3174                         const char *reexport_name_cstr =
3175                             strtab_data.PeekCStr(nlist.n_value);
3176                         if (reexport_name_cstr && reexport_name_cstr[0]) {
3177                           type = eSymbolTypeReExported;
3178                           ConstString reexport_name(
3179                               reexport_name_cstr +
3180                               ((reexport_name_cstr[0] == '_') ? 1 : 0));
3181                           sym[sym_idx].SetReExportedSymbolName(reexport_name);
3182                           set_value = false;
3183                           reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3184                           indirect_symbol_names.insert(ConstString(
3185                               symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
3186                         } else
3187                           type = eSymbolTypeUndefined;
3188                       } break;
3189 
3190                       case N_UNDF:
3191                         if (symbol_name && symbol_name[0]) {
3192                           ConstString undefined_name(
3193                               symbol_name + ((symbol_name[0] == '_') ? 1 : 0));
3194                           undefined_name_to_desc[undefined_name] = nlist.n_desc;
3195                         }
3196                       // Fall through
3197                       case N_PBUD:
3198                         type = eSymbolTypeUndefined;
3199                         break;
3200 
3201                       case N_ABS:
3202                         type = eSymbolTypeAbsolute;
3203                         break;
3204 
3205                       case N_SECT: {
3206                         symbol_section = section_info.GetSection(nlist.n_sect,
3207                                                                  nlist.n_value);
3208 
3209                         if (symbol_section == NULL) {
3210                           // TODO: warn about this?
3211                           add_nlist = false;
3212                           break;
3213                         }
3214 
3215                         if (TEXT_eh_frame_sectID == nlist.n_sect) {
3216                           type = eSymbolTypeException;
3217                         } else {
3218                           uint32_t section_type =
3219                               symbol_section->Get() & SECTION_TYPE;
3220 
3221                           switch (section_type) {
3222                           case S_CSTRING_LITERALS:
3223                             type = eSymbolTypeData;
3224                             break; // section with only literal C strings
3225                           case S_4BYTE_LITERALS:
3226                             type = eSymbolTypeData;
3227                             break; // section with only 4 byte literals
3228                           case S_8BYTE_LITERALS:
3229                             type = eSymbolTypeData;
3230                             break; // section with only 8 byte literals
3231                           case S_LITERAL_POINTERS:
3232                             type = eSymbolTypeTrampoline;
3233                             break; // section with only pointers to literals
3234                           case S_NON_LAZY_SYMBOL_POINTERS:
3235                             type = eSymbolTypeTrampoline;
3236                             break; // section with only non-lazy symbol
3237                                    // pointers
3238                           case S_LAZY_SYMBOL_POINTERS:
3239                             type = eSymbolTypeTrampoline;
3240                             break; // section with only lazy symbol pointers
3241                           case S_SYMBOL_STUBS:
3242                             type = eSymbolTypeTrampoline;
3243                             break; // section with only symbol stubs, byte
3244                                    // size of stub in the reserved2 field
3245                           case S_MOD_INIT_FUNC_POINTERS:
3246                             type = eSymbolTypeCode;
3247                             break; // section with only function pointers for
3248                                    // initialization
3249                           case S_MOD_TERM_FUNC_POINTERS:
3250                             type = eSymbolTypeCode;
3251                             break; // section with only function pointers for
3252                                    // termination
3253                           case S_INTERPOSING:
3254                             type = eSymbolTypeTrampoline;
3255                             break; // section with only pairs of function
3256                                    // pointers for interposing
3257                           case S_16BYTE_LITERALS:
3258                             type = eSymbolTypeData;
3259                             break; // section with only 16 byte literals
3260                           case S_DTRACE_DOF:
3261                             type = eSymbolTypeInstrumentation;
3262                             break;
3263                           case S_LAZY_DYLIB_SYMBOL_POINTERS:
3264                             type = eSymbolTypeTrampoline;
3265                             break;
3266                           default:
3267                             switch (symbol_section->GetType()) {
3268                             case lldb::eSectionTypeCode:
3269                               type = eSymbolTypeCode;
3270                               break;
3271                             case eSectionTypeData:
3272                             case eSectionTypeDataCString: // Inlined C string
3273                                                           // data
3274                             case eSectionTypeDataCStringPointers: // Pointers
3275                                                                   // to C
3276                                                                   // string
3277                                                                   // data
3278                             case eSectionTypeDataSymbolAddress:   // Address of
3279                                                                   // a symbol in
3280                                                                   // the symbol
3281                                                                   // table
3282                             case eSectionTypeData4:
3283                             case eSectionTypeData8:
3284                             case eSectionTypeData16:
3285                               type = eSymbolTypeData;
3286                               break;
3287                             default:
3288                               break;
3289                             }
3290                             break;
3291                           }
3292 
3293                           if (type == eSymbolTypeInvalid) {
3294                             const char *symbol_sect_name =
3295                                 symbol_section->GetName().AsCString();
3296                             if (symbol_section->IsDescendant(
3297                                     text_section_sp.get())) {
3298                               if (symbol_section->IsClear(
3299                                       S_ATTR_PURE_INSTRUCTIONS |
3300                                       S_ATTR_SELF_MODIFYING_CODE |
3301                                       S_ATTR_SOME_INSTRUCTIONS))
3302                                 type = eSymbolTypeData;
3303                               else
3304                                 type = eSymbolTypeCode;
3305                             } else if (symbol_section->IsDescendant(
3306                                            data_section_sp.get()) ||
3307                                        symbol_section->IsDescendant(
3308                                            data_dirty_section_sp.get()) ||
3309                                        symbol_section->IsDescendant(
3310                                            data_const_section_sp.get())) {
3311                               if (symbol_sect_name &&
3312                                   ::strstr(symbol_sect_name, "__objc") ==
3313                                       symbol_sect_name) {
3314                                 type = eSymbolTypeRuntime;
3315 
3316                                 if (symbol_name) {
3317                                   llvm::StringRef symbol_name_ref(symbol_name);
3318                                   if (symbol_name_ref.startswith("_OBJC_")) {
3319                                     llvm::StringRef
3320                                         g_objc_v2_prefix_class(
3321                                             "_OBJC_CLASS_$_");
3322                                     llvm::StringRef
3323                                         g_objc_v2_prefix_metaclass(
3324                                             "_OBJC_METACLASS_$_");
3325                                     llvm::StringRef
3326                                         g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
3327                                     if (symbol_name_ref.startswith(
3328                                             g_objc_v2_prefix_class)) {
3329                                       symbol_name_non_abi_mangled =
3330                                           symbol_name + 1;
3331                                       symbol_name =
3332                                           symbol_name +
3333                                           g_objc_v2_prefix_class.size();
3334                                       type = eSymbolTypeObjCClass;
3335                                       demangled_is_synthesized = true;
3336                                     } else if (
3337                                         symbol_name_ref.startswith(
3338                                             g_objc_v2_prefix_metaclass)) {
3339                                       symbol_name_non_abi_mangled =
3340                                           symbol_name + 1;
3341                                       symbol_name =
3342                                           symbol_name +
3343                                           g_objc_v2_prefix_metaclass.size();
3344                                       type = eSymbolTypeObjCMetaClass;
3345                                       demangled_is_synthesized = true;
3346                                     } else if (symbol_name_ref.startswith(
3347                                                    g_objc_v2_prefix_ivar)) {
3348                                       symbol_name_non_abi_mangled =
3349                                           symbol_name + 1;
3350                                       symbol_name =
3351                                           symbol_name +
3352                                           g_objc_v2_prefix_ivar.size();
3353                                       type = eSymbolTypeObjCIVar;
3354                                       demangled_is_synthesized = true;
3355                                     }
3356                                   }
3357                                 }
3358                               } else if (symbol_sect_name &&
3359                                          ::strstr(symbol_sect_name,
3360                                                   "__gcc_except_tab") ==
3361                                              symbol_sect_name) {
3362                                 type = eSymbolTypeException;
3363                               } else {
3364                                 type = eSymbolTypeData;
3365                               }
3366                             } else if (symbol_sect_name &&
3367                                        ::strstr(symbol_sect_name, "__IMPORT") ==
3368                                            symbol_sect_name) {
3369                               type = eSymbolTypeTrampoline;
3370                             } else if (symbol_section->IsDescendant(
3371                                            objc_section_sp.get())) {
3372                               type = eSymbolTypeRuntime;
3373                               if (symbol_name && symbol_name[0] == '.') {
3374                                 llvm::StringRef symbol_name_ref(symbol_name);
3375                                 llvm::StringRef
3376                                     g_objc_v1_prefix_class(".objc_class_name_");
3377                                 if (symbol_name_ref.startswith(
3378                                         g_objc_v1_prefix_class)) {
3379                                   symbol_name_non_abi_mangled = symbol_name;
3380                                   symbol_name = symbol_name +
3381                                                 g_objc_v1_prefix_class.size();
3382                                   type = eSymbolTypeObjCClass;
3383                                   demangled_is_synthesized = true;
3384                                 }
3385                               }
3386                             }
3387                           }
3388                         }
3389                       } break;
3390                       }
3391                     }
3392 
3393                     if (add_nlist) {
3394                       uint64_t symbol_value = nlist.n_value;
3395                       if (symbol_name_non_abi_mangled) {
3396                         sym[sym_idx].GetMangled().SetMangledName(
3397                             ConstString(symbol_name_non_abi_mangled));
3398                         sym[sym_idx].GetMangled().SetDemangledName(
3399                             ConstString(symbol_name));
3400                       } else {
3401                         bool symbol_name_is_mangled = false;
3402 
3403                         if (symbol_name && symbol_name[0] == '_') {
3404                           symbol_name_is_mangled = symbol_name[1] == '_';
3405                           symbol_name++; // Skip the leading underscore
3406                         }
3407 
3408                         if (symbol_name) {
3409                           ConstString const_symbol_name(symbol_name);
3410                           sym[sym_idx].GetMangled().SetValue(
3411                               const_symbol_name, symbol_name_is_mangled);
3412                           if (is_gsym && is_debug) {
3413                             const char *gsym_name =
3414                                 sym[sym_idx]
3415                                     .GetMangled()
3416                                     .GetName(lldb::eLanguageTypeUnknown,
3417                                              Mangled::ePreferMangled)
3418                                     .GetCString();
3419                             if (gsym_name)
3420                               N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3421                           }
3422                         }
3423                       }
3424                       if (symbol_section) {
3425                         const addr_t section_file_addr =
3426                             symbol_section->GetFileAddress();
3427                         if (symbol_byte_size == 0 &&
3428                             function_starts_count > 0) {
3429                           addr_t symbol_lookup_file_addr = nlist.n_value;
3430                           // Do an exact address match for non-ARM addresses,
3431                           // else get the closest since the symbol might be a
3432                           // thumb symbol which has an address with bit zero
3433                           // set
3434                           FunctionStarts::Entry *func_start_entry =
3435                               function_starts.FindEntry(symbol_lookup_file_addr,
3436                                                         !is_arm);
3437                           if (is_arm && func_start_entry) {
3438                             // Verify that the function start address is the
3439                             // symbol address (ARM) or the symbol address + 1
3440                             // (thumb)
3441                             if (func_start_entry->addr !=
3442                                     symbol_lookup_file_addr &&
3443                                 func_start_entry->addr !=
3444                                     (symbol_lookup_file_addr + 1)) {
3445                               // Not the right entry, NULL it out...
3446                               func_start_entry = NULL;
3447                             }
3448                           }
3449                           if (func_start_entry) {
3450                             func_start_entry->data = true;
3451 
3452                             addr_t symbol_file_addr = func_start_entry->addr;
3453                             uint32_t symbol_flags = 0;
3454                             if (is_arm) {
3455                               if (symbol_file_addr & 1)
3456                                 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3457                               symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3458                             }
3459 
3460                             const FunctionStarts::Entry *next_func_start_entry =
3461                                 function_starts.FindNextEntry(func_start_entry);
3462                             const addr_t section_end_file_addr =
3463                                 section_file_addr +
3464                                 symbol_section->GetByteSize();
3465                             if (next_func_start_entry) {
3466                               addr_t next_symbol_file_addr =
3467                                   next_func_start_entry->addr;
3468                               // Be sure the clear the Thumb address bit when
3469                               // we calculate the size from the current and
3470                               // next address
3471                               if (is_arm)
3472                                 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3473                               symbol_byte_size = std::min<lldb::addr_t>(
3474                                   next_symbol_file_addr - symbol_file_addr,
3475                                   section_end_file_addr - symbol_file_addr);
3476                             } else {
3477                               symbol_byte_size =
3478                                   section_end_file_addr - symbol_file_addr;
3479                             }
3480                           }
3481                         }
3482                         symbol_value -= section_file_addr;
3483                       }
3484 
3485                       if (is_debug == false) {
3486                         if (type == eSymbolTypeCode) {
3487                           // See if we can find a N_FUN entry for any code
3488                           // symbols. If we do find a match, and the name
3489                           // matches, then we can merge the two into just the
3490                           // function symbol to avoid duplicate entries in
3491                           // the symbol table
3492                           auto range =
3493                               N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
3494                           if (range.first != range.second) {
3495                             bool found_it = false;
3496                             for (const auto pos = range.first;
3497                                  pos != range.second; ++pos) {
3498                               if (sym[sym_idx].GetMangled().GetName(
3499                                       lldb::eLanguageTypeUnknown,
3500                                       Mangled::ePreferMangled) ==
3501                                   sym[pos->second].GetMangled().GetName(
3502                                       lldb::eLanguageTypeUnknown,
3503                                       Mangled::ePreferMangled)) {
3504                                 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3505                                 // We just need the flags from the linker
3506                                 // symbol, so put these flags
3507                                 // into the N_FUN flags to avoid duplicate
3508                                 // symbols in the symbol table
3509                                 sym[pos->second].SetExternal(
3510                                     sym[sym_idx].IsExternal());
3511                                 sym[pos->second].SetFlags(nlist.n_type << 16 |
3512                                                           nlist.n_desc);
3513                                 if (resolver_addresses.find(nlist.n_value) !=
3514                                     resolver_addresses.end())
3515                                   sym[pos->second].SetType(eSymbolTypeResolver);
3516                                 sym[sym_idx].Clear();
3517                                 found_it = true;
3518                                 break;
3519                               }
3520                             }
3521                             if (found_it)
3522                               continue;
3523                           } else {
3524                             if (resolver_addresses.find(nlist.n_value) !=
3525                                 resolver_addresses.end())
3526                               type = eSymbolTypeResolver;
3527                           }
3528                         } else if (type == eSymbolTypeData ||
3529                                    type == eSymbolTypeObjCClass ||
3530                                    type == eSymbolTypeObjCMetaClass ||
3531                                    type == eSymbolTypeObjCIVar) {
3532                           // See if we can find a N_STSYM entry for any data
3533                           // symbols. If we do find a match, and the name
3534                           // matches, then we can merge the two into just the
3535                           // Static symbol to avoid duplicate entries in the
3536                           // symbol table
3537                           auto range = N_STSYM_addr_to_sym_idx.equal_range(
3538                               nlist.n_value);
3539                           if (range.first != range.second) {
3540                             bool found_it = false;
3541                             for (const auto pos = range.first;
3542                                  pos != range.second; ++pos) {
3543                               if (sym[sym_idx].GetMangled().GetName(
3544                                       lldb::eLanguageTypeUnknown,
3545                                       Mangled::ePreferMangled) ==
3546                                   sym[pos->second].GetMangled().GetName(
3547                                       lldb::eLanguageTypeUnknown,
3548                                       Mangled::ePreferMangled)) {
3549                                 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3550                                 // We just need the flags from the linker
3551                                 // symbol, so put these flags
3552                                 // into the N_STSYM flags to avoid duplicate
3553                                 // symbols in the symbol table
3554                                 sym[pos->second].SetExternal(
3555                                     sym[sym_idx].IsExternal());
3556                                 sym[pos->second].SetFlags(nlist.n_type << 16 |
3557                                                           nlist.n_desc);
3558                                 sym[sym_idx].Clear();
3559                                 found_it = true;
3560                                 break;
3561                               }
3562                             }
3563                             if (found_it)
3564                               continue;
3565                           } else {
3566                             const char *gsym_name =
3567                                 sym[sym_idx]
3568                                     .GetMangled()
3569                                     .GetName(lldb::eLanguageTypeUnknown,
3570                                              Mangled::ePreferMangled)
3571                                     .GetCString();
3572                             if (gsym_name) {
3573                               // Combine N_GSYM stab entries with the non
3574                               // stab symbol
3575                               ConstNameToSymbolIndexMap::const_iterator pos =
3576                                   N_GSYM_name_to_sym_idx.find(gsym_name);
3577                               if (pos != N_GSYM_name_to_sym_idx.end()) {
3578                                 const uint32_t GSYM_sym_idx = pos->second;
3579                                 m_nlist_idx_to_sym_idx[nlist_idx] =
3580                                     GSYM_sym_idx;
3581                                 // Copy the address, because often the N_GSYM
3582                                 // address has an invalid address of zero
3583                                 // when the global is a common symbol
3584                                 sym[GSYM_sym_idx].GetAddressRef().SetSection(
3585                                     symbol_section);
3586                                 sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3587                                     symbol_value);
3588                                 // We just need the flags from the linker
3589                                 // symbol, so put these flags
3590                                 // into the N_GSYM flags to avoid duplicate
3591                                 // symbols in the symbol table
3592                                 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
3593                                                            nlist.n_desc);
3594                                 sym[sym_idx].Clear();
3595                                 continue;
3596                               }
3597                             }
3598                           }
3599                         }
3600                       }
3601 
3602                       sym[sym_idx].SetID(nlist_idx);
3603                       sym[sym_idx].SetType(type);
3604                       if (set_value) {
3605                         sym[sym_idx].GetAddressRef().SetSection(symbol_section);
3606                         sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
3607                       }
3608                       sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
3609 
3610                       if (symbol_byte_size > 0)
3611                         sym[sym_idx].SetByteSize(symbol_byte_size);
3612 
3613                       if (demangled_is_synthesized)
3614                         sym[sym_idx].SetDemangledNameIsSynthesized(true);
3615                       ++sym_idx;
3616                     } else {
3617                       sym[sym_idx].Clear();
3618                     }
3619                   }
3620                   /////////////////////////////
3621                 }
3622                 break; // No more entries to consider
3623               }
3624             }
3625 
3626             for (const auto &pos : reexport_shlib_needs_fixup) {
3627               const auto undef_pos = undefined_name_to_desc.find(pos.second);
3628               if (undef_pos != undefined_name_to_desc.end()) {
3629                 const uint8_t dylib_ordinal =
3630                     llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3631                 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
3632                   sym[pos.first].SetReExportedSymbolSharedLibrary(
3633                       dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3634               }
3635             }
3636           }
3637         }
3638       }
3639     }
3640   }
3641 
3642   // Must reset this in case it was mutated above!
3643   nlist_data_offset = 0;
3644 #endif
3645 
3646   if (nlist_data.GetByteSize() > 0) {
3647 
3648     // If the sym array was not created while parsing the DSC unmapped
3649     // symbols, create it now.
3650     if (sym == nullptr) {
3651       sym =
3652           symtab->Resize(symtab_load_command.nsyms + m_dysymtab.nindirectsyms);
3653       num_syms = symtab->GetNumSymbols();
3654     }
3655 
3656     if (unmapped_local_symbols_found) {
3657       assert(m_dysymtab.ilocalsym == 0);
3658       nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3659       nlist_idx = m_dysymtab.nlocalsym;
3660     } else {
3661       nlist_idx = 0;
3662     }
3663 
3664     typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
3665     typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
3666     UndefinedNameToDescMap undefined_name_to_desc;
3667     SymbolIndexToName reexport_shlib_needs_fixup;
3668 
3669     // Symtab parsing is a huge mess. Everything is entangled and the code
3670     // requires access to a ridiculous amount of variables. LLDB depends
3671     // heavily on the proper merging of symbols and to get that right we need
3672     // to make sure we have parsed all the debug symbols first. Therefore we
3673     // invoke the lambda twice, once to parse only the debug symbols and then
3674     // once more to parse the remaining symbols.
3675     auto ParseSymbolLambda = [&](struct nlist_64 &nlist, uint32_t nlist_idx,
3676                                  bool debug_only) {
3677       const bool is_debug = ((nlist.n_type & N_STAB) != 0);
3678       if (is_debug != debug_only)
3679         return true;
3680 
3681       const char *symbol_name_non_abi_mangled = nullptr;
3682       const char *symbol_name = nullptr;
3683 
3684       if (have_strtab_data) {
3685         symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3686 
3687         if (symbol_name == nullptr) {
3688           // No symbol should be NULL, even the symbols with no string values
3689           // should have an offset zero which points to an empty C-string
3690           Host::SystemLog(Host::eSystemLogError,
3691                           "error: symbol[%u] has invalid string table offset "
3692                           "0x%x in %s, ignoring symbol\n",
3693                           nlist_idx, nlist.n_strx,
3694                           module_sp->GetFileSpec().GetPath().c_str());
3695           return true;
3696         }
3697         if (symbol_name[0] == '\0')
3698           symbol_name = nullptr;
3699       } else {
3700         const addr_t str_addr = strtab_addr + nlist.n_strx;
3701         Status str_error;
3702         if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
3703                                            str_error))
3704           symbol_name = memory_symbol_name.c_str();
3705       }
3706 
3707       SymbolType type = eSymbolTypeInvalid;
3708       SectionSP symbol_section;
3709       lldb::addr_t symbol_byte_size = 0;
3710       bool add_nlist = true;
3711       bool is_gsym = false;
3712       bool demangled_is_synthesized = false;
3713       bool set_value = true;
3714 
3715       assert(sym_idx < num_syms);
3716       sym[sym_idx].SetDebug(is_debug);
3717 
3718       if (is_debug) {
3719         switch (nlist.n_type) {
3720         case N_GSYM:
3721           // global symbol: name,,NO_SECT,type,0
3722           // Sometimes the N_GSYM value contains the address.
3723 
3724           // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3725           // the ObjC data.  They
3726           // have the same address, but we want to ensure that we always find
3727           // only the real symbol, 'cause we don't currently correctly
3728           // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3729           // type.  This is a temporary hack to make sure the ObjectiveC
3730           // symbols get treated correctly.  To do this right, we should
3731           // coalesce all the GSYM & global symbols that have the same
3732           // address.
3733           is_gsym = true;
3734           sym[sym_idx].SetExternal(true);
3735 
3736           if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3737             llvm::StringRef symbol_name_ref(symbol_name);
3738             if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
3739               symbol_name_non_abi_mangled = symbol_name + 1;
3740               symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3741               type = eSymbolTypeObjCClass;
3742               demangled_is_synthesized = true;
3743 
3744             } else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass)) {
3745               symbol_name_non_abi_mangled = symbol_name + 1;
3746               symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3747               type = eSymbolTypeObjCMetaClass;
3748               demangled_is_synthesized = true;
3749             } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) {
3750               symbol_name_non_abi_mangled = symbol_name + 1;
3751               symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3752               type = eSymbolTypeObjCIVar;
3753               demangled_is_synthesized = true;
3754             }
3755           } else {
3756             if (nlist.n_value != 0)
3757               symbol_section =
3758                   section_info.GetSection(nlist.n_sect, nlist.n_value);
3759             type = eSymbolTypeData;
3760           }
3761           break;
3762 
3763         case N_FNAME:
3764           // procedure name (f77 kludge): name,,NO_SECT,0,0
3765           type = eSymbolTypeCompiler;
3766           break;
3767 
3768         case N_FUN:
3769           // procedure: name,,n_sect,linenumber,address
3770           if (symbol_name) {
3771             type = eSymbolTypeCode;
3772             symbol_section =
3773                 section_info.GetSection(nlist.n_sect, nlist.n_value);
3774 
3775             N_FUN_addr_to_sym_idx.insert(
3776                 std::make_pair(nlist.n_value, sym_idx));
3777             // We use the current number of symbols in the symbol table in
3778             // lieu of using nlist_idx in case we ever start trimming entries
3779             // out
3780             N_FUN_indexes.push_back(sym_idx);
3781           } else {
3782             type = eSymbolTypeCompiler;
3783 
3784             if (!N_FUN_indexes.empty()) {
3785               // Copy the size of the function into the original STAB entry
3786               // so we don't have to hunt for it later
3787               symtab->SymbolAtIndex(N_FUN_indexes.back())
3788                   ->SetByteSize(nlist.n_value);
3789               N_FUN_indexes.pop_back();
3790               // We don't really need the end function STAB as it contains
3791               // the size which we already placed with the original symbol,
3792               // so don't add it if we want a minimal symbol table
3793               add_nlist = false;
3794             }
3795           }
3796           break;
3797 
3798         case N_STSYM:
3799           // static symbol: name,,n_sect,type,address
3800           N_STSYM_addr_to_sym_idx.insert(
3801               std::make_pair(nlist.n_value, sym_idx));
3802           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3803           if (symbol_name && symbol_name[0]) {
3804             type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
3805                                                      eSymbolTypeData);
3806           }
3807           break;
3808 
3809         case N_LCSYM:
3810           // .lcomm symbol: name,,n_sect,type,address
3811           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3812           type = eSymbolTypeCommonBlock;
3813           break;
3814 
3815         case N_BNSYM:
3816           // We use the current number of symbols in the symbol table in lieu
3817           // of using nlist_idx in case we ever start trimming entries out
3818           // Skip these if we want minimal symbol tables
3819           add_nlist = false;
3820           break;
3821 
3822         case N_ENSYM:
3823           // Set the size of the N_BNSYM to the terminating index of this
3824           // N_ENSYM so that we can always skip the entire symbol if we need
3825           // to navigate more quickly at the source level when parsing STABS
3826           // Skip these if we want minimal symbol tables
3827           add_nlist = false;
3828           break;
3829 
3830         case N_OPT:
3831           // emitted with gcc2_compiled and in gcc source
3832           type = eSymbolTypeCompiler;
3833           break;
3834 
3835         case N_RSYM:
3836           // register sym: name,,NO_SECT,type,register
3837           type = eSymbolTypeVariable;
3838           break;
3839 
3840         case N_SLINE:
3841           // src line: 0,,n_sect,linenumber,address
3842           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3843           type = eSymbolTypeLineEntry;
3844           break;
3845 
3846         case N_SSYM:
3847           // structure elt: name,,NO_SECT,type,struct_offset
3848           type = eSymbolTypeVariableType;
3849           break;
3850 
3851         case N_SO:
3852           // source file name
3853           type = eSymbolTypeSourceFile;
3854           if (symbol_name == nullptr) {
3855             add_nlist = false;
3856             if (N_SO_index != UINT32_MAX) {
3857               // Set the size of the N_SO to the terminating index of this
3858               // N_SO so that we can always skip the entire N_SO if we need
3859               // to navigate more quickly at the source level when parsing
3860               // STABS
3861               symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3862               symbol_ptr->SetByteSize(sym_idx);
3863               symbol_ptr->SetSizeIsSibling(true);
3864             }
3865             N_NSYM_indexes.clear();
3866             N_INCL_indexes.clear();
3867             N_BRAC_indexes.clear();
3868             N_COMM_indexes.clear();
3869             N_FUN_indexes.clear();
3870             N_SO_index = UINT32_MAX;
3871           } else {
3872             // We use the current number of symbols in the symbol table in
3873             // lieu of using nlist_idx in case we ever start trimming entries
3874             // out
3875             const bool N_SO_has_full_path = symbol_name[0] == '/';
3876             if (N_SO_has_full_path) {
3877               if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3878                 // We have two consecutive N_SO entries where the first
3879                 // contains a directory and the second contains a full path.
3880                 sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name),
3881                                                        false);
3882                 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3883                 add_nlist = false;
3884               } else {
3885                 // This is the first entry in a N_SO that contains a
3886                 // directory or a full path to the source file
3887                 N_SO_index = sym_idx;
3888               }
3889             } else if ((N_SO_index == sym_idx - 1) &&
3890                        ((sym_idx - 1) < num_syms)) {
3891               // This is usually the second N_SO entry that contains just the
3892               // filename, so here we combine it with the first one if we are
3893               // minimizing the symbol table
3894               const char *so_path =
3895                   sym[sym_idx - 1]
3896                       .GetMangled()
3897                       .GetDemangledName(lldb::eLanguageTypeUnknown)
3898                       .AsCString();
3899               if (so_path && so_path[0]) {
3900                 std::string full_so_path(so_path);
3901                 const size_t double_slash_pos = full_so_path.find("//");
3902                 if (double_slash_pos != std::string::npos) {
3903                   // The linker has been generating bad N_SO entries with
3904                   // doubled up paths in the format "%s%s" where the first
3905                   // string in the DW_AT_comp_dir, and the second is the
3906                   // directory for the source file so you end up with a path
3907                   // that looks like "/tmp/src//tmp/src/"
3908                   FileSpec so_dir(so_path);
3909                   if (!FileSystem::Instance().Exists(so_dir)) {
3910                     so_dir.SetFile(&full_so_path[double_slash_pos + 1],
3911                                    FileSpec::Style::native);
3912                     if (FileSystem::Instance().Exists(so_dir)) {
3913                       // Trim off the incorrect path
3914                       full_so_path.erase(0, double_slash_pos + 1);
3915                     }
3916                   }
3917                 }
3918                 if (*full_so_path.rbegin() != '/')
3919                   full_so_path += '/';
3920                 full_so_path += symbol_name;
3921                 sym[sym_idx - 1].GetMangled().SetValue(
3922                     ConstString(full_so_path.c_str()), false);
3923                 add_nlist = false;
3924                 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3925               }
3926             } else {
3927               // This could be a relative path to a N_SO
3928               N_SO_index = sym_idx;
3929             }
3930           }
3931           break;
3932 
3933         case N_OSO:
3934           // object file name: name,,0,0,st_mtime
3935           type = eSymbolTypeObjectFile;
3936           break;
3937 
3938         case N_LSYM:
3939           // local sym: name,,NO_SECT,type,offset
3940           type = eSymbolTypeLocal;
3941           break;
3942 
3943         // INCL scopes
3944         case N_BINCL:
3945           // include file beginning: name,,NO_SECT,0,sum We use the current
3946           // number of symbols in the symbol table in lieu of using nlist_idx
3947           // in case we ever start trimming entries out
3948           N_INCL_indexes.push_back(sym_idx);
3949           type = eSymbolTypeScopeBegin;
3950           break;
3951 
3952         case N_EINCL:
3953           // include file end: name,,NO_SECT,0,0
3954           // Set the size of the N_BINCL to the terminating index of this
3955           // N_EINCL so that we can always skip the entire symbol if we need
3956           // to navigate more quickly at the source level when parsing STABS
3957           if (!N_INCL_indexes.empty()) {
3958             symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
3959             symbol_ptr->SetByteSize(sym_idx + 1);
3960             symbol_ptr->SetSizeIsSibling(true);
3961             N_INCL_indexes.pop_back();
3962           }
3963           type = eSymbolTypeScopeEnd;
3964           break;
3965 
3966         case N_SOL:
3967           // #included file name: name,,n_sect,0,address
3968           type = eSymbolTypeHeaderFile;
3969 
3970           // We currently don't use the header files on darwin
3971           add_nlist = false;
3972           break;
3973 
3974         case N_PARAMS:
3975           // compiler parameters: name,,NO_SECT,0,0
3976           type = eSymbolTypeCompiler;
3977           break;
3978 
3979         case N_VERSION:
3980           // compiler version: name,,NO_SECT,0,0
3981           type = eSymbolTypeCompiler;
3982           break;
3983 
3984         case N_OLEVEL:
3985           // compiler -O level: name,,NO_SECT,0,0
3986           type = eSymbolTypeCompiler;
3987           break;
3988 
3989         case N_PSYM:
3990           // parameter: name,,NO_SECT,type,offset
3991           type = eSymbolTypeVariable;
3992           break;
3993 
3994         case N_ENTRY:
3995           // alternate entry: name,,n_sect,linenumber,address
3996           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3997           type = eSymbolTypeLineEntry;
3998           break;
3999 
4000         // Left and Right Braces
4001         case N_LBRAC:
4002           // left bracket: 0,,NO_SECT,nesting level,address We use the
4003           // current number of symbols in the symbol table in lieu of using
4004           // nlist_idx in case we ever start trimming entries out
4005           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4006           N_BRAC_indexes.push_back(sym_idx);
4007           type = eSymbolTypeScopeBegin;
4008           break;
4009 
4010         case N_RBRAC:
4011           // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4012           // the N_LBRAC to the terminating index of this N_RBRAC so that we
4013           // can always skip the entire symbol if we need to navigate more
4014           // quickly at the source level when parsing STABS
4015           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4016           if (!N_BRAC_indexes.empty()) {
4017             symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
4018             symbol_ptr->SetByteSize(sym_idx + 1);
4019             symbol_ptr->SetSizeIsSibling(true);
4020             N_BRAC_indexes.pop_back();
4021           }
4022           type = eSymbolTypeScopeEnd;
4023           break;
4024 
4025         case N_EXCL:
4026           // deleted include file: name,,NO_SECT,0,sum
4027           type = eSymbolTypeHeaderFile;
4028           break;
4029 
4030         // COMM scopes
4031         case N_BCOMM:
4032           // begin common: name,,NO_SECT,0,0
4033           // We use the current number of symbols in the symbol table in lieu
4034           // of using nlist_idx in case we ever start trimming entries out
4035           type = eSymbolTypeScopeBegin;
4036           N_COMM_indexes.push_back(sym_idx);
4037           break;
4038 
4039         case N_ECOML:
4040           // end common (local name): 0,,n_sect,0,address
4041           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4042           LLVM_FALLTHROUGH;
4043 
4044         case N_ECOMM:
4045           // end common: name,,n_sect,0,0
4046           // Set the size of the N_BCOMM to the terminating index of this
4047           // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4048           // we need to navigate more quickly at the source level when
4049           // parsing STABS
4050           if (!N_COMM_indexes.empty()) {
4051             symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
4052             symbol_ptr->SetByteSize(sym_idx + 1);
4053             symbol_ptr->SetSizeIsSibling(true);
4054             N_COMM_indexes.pop_back();
4055           }
4056           type = eSymbolTypeScopeEnd;
4057           break;
4058 
4059         case N_LENG:
4060           // second stab entry with length information
4061           type = eSymbolTypeAdditional;
4062           break;
4063 
4064         default:
4065           break;
4066         }
4067       } else {
4068         uint8_t n_type = N_TYPE & nlist.n_type;
4069         sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4070 
4071         switch (n_type) {
4072         case N_INDR: {
4073           const char *reexport_name_cstr = strtab_data.PeekCStr(nlist.n_value);
4074           if (reexport_name_cstr && reexport_name_cstr[0]) {
4075             type = eSymbolTypeReExported;
4076             ConstString reexport_name(reexport_name_cstr +
4077                                       ((reexport_name_cstr[0] == '_') ? 1 : 0));
4078             sym[sym_idx].SetReExportedSymbolName(reexport_name);
4079             set_value = false;
4080             reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4081             indirect_symbol_names.insert(
4082                 ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4083           } else
4084             type = eSymbolTypeUndefined;
4085         } break;
4086 
4087         case N_UNDF:
4088           if (symbol_name && symbol_name[0]) {
4089             ConstString undefined_name(symbol_name +
4090                                        ((symbol_name[0] == '_') ? 1 : 0));
4091             undefined_name_to_desc[undefined_name] = nlist.n_desc;
4092           }
4093           LLVM_FALLTHROUGH;
4094 
4095         case N_PBUD:
4096           type = eSymbolTypeUndefined;
4097           break;
4098 
4099         case N_ABS:
4100           type = eSymbolTypeAbsolute;
4101           break;
4102 
4103         case N_SECT: {
4104           symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4105 
4106           if (!symbol_section) {
4107             // TODO: warn about this?
4108             add_nlist = false;
4109             break;
4110           }
4111 
4112           if (TEXT_eh_frame_sectID == nlist.n_sect) {
4113             type = eSymbolTypeException;
4114           } else {
4115             uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4116 
4117             switch (section_type) {
4118             case S_CSTRING_LITERALS:
4119               type = eSymbolTypeData;
4120               break; // section with only literal C strings
4121             case S_4BYTE_LITERALS:
4122               type = eSymbolTypeData;
4123               break; // section with only 4 byte literals
4124             case S_8BYTE_LITERALS:
4125               type = eSymbolTypeData;
4126               break; // section with only 8 byte literals
4127             case S_LITERAL_POINTERS:
4128               type = eSymbolTypeTrampoline;
4129               break; // section with only pointers to literals
4130             case S_NON_LAZY_SYMBOL_POINTERS:
4131               type = eSymbolTypeTrampoline;
4132               break; // section with only non-lazy symbol pointers
4133             case S_LAZY_SYMBOL_POINTERS:
4134               type = eSymbolTypeTrampoline;
4135               break; // section with only lazy symbol pointers
4136             case S_SYMBOL_STUBS:
4137               type = eSymbolTypeTrampoline;
4138               break; // section with only symbol stubs, byte size of stub in
4139                      // the reserved2 field
4140             case S_MOD_INIT_FUNC_POINTERS:
4141               type = eSymbolTypeCode;
4142               break; // section with only function pointers for initialization
4143             case S_MOD_TERM_FUNC_POINTERS:
4144               type = eSymbolTypeCode;
4145               break; // section with only function pointers for termination
4146             case S_INTERPOSING:
4147               type = eSymbolTypeTrampoline;
4148               break; // section with only pairs of function pointers for
4149                      // interposing
4150             case S_16BYTE_LITERALS:
4151               type = eSymbolTypeData;
4152               break; // section with only 16 byte literals
4153             case S_DTRACE_DOF:
4154               type = eSymbolTypeInstrumentation;
4155               break;
4156             case S_LAZY_DYLIB_SYMBOL_POINTERS:
4157               type = eSymbolTypeTrampoline;
4158               break;
4159             default:
4160               switch (symbol_section->GetType()) {
4161               case lldb::eSectionTypeCode:
4162                 type = eSymbolTypeCode;
4163                 break;
4164               case eSectionTypeData:
4165               case eSectionTypeDataCString:         // Inlined C string data
4166               case eSectionTypeDataCStringPointers: // Pointers to C string
4167                                                     // data
4168               case eSectionTypeDataSymbolAddress:   // Address of a symbol in
4169                                                     // the symbol table
4170               case eSectionTypeData4:
4171               case eSectionTypeData8:
4172               case eSectionTypeData16:
4173                 type = eSymbolTypeData;
4174                 break;
4175               default:
4176                 break;
4177               }
4178               break;
4179             }
4180 
4181             if (type == eSymbolTypeInvalid) {
4182               const char *symbol_sect_name =
4183                   symbol_section->GetName().AsCString();
4184               if (symbol_section->IsDescendant(text_section_sp.get())) {
4185                 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4186                                             S_ATTR_SELF_MODIFYING_CODE |
4187                                             S_ATTR_SOME_INSTRUCTIONS))
4188                   type = eSymbolTypeData;
4189                 else
4190                   type = eSymbolTypeCode;
4191               } else if (symbol_section->IsDescendant(data_section_sp.get()) ||
4192                          symbol_section->IsDescendant(
4193                              data_dirty_section_sp.get()) ||
4194                          symbol_section->IsDescendant(
4195                              data_const_section_sp.get())) {
4196                 if (symbol_sect_name &&
4197                     ::strstr(symbol_sect_name, "__objc") == symbol_sect_name) {
4198                   type = eSymbolTypeRuntime;
4199 
4200                   if (symbol_name) {
4201                     llvm::StringRef symbol_name_ref(symbol_name);
4202                     if (symbol_name_ref.startswith("_OBJC_")) {
4203                       llvm::StringRef g_objc_v2_prefix_class(
4204                           "_OBJC_CLASS_$_");
4205                       llvm::StringRef g_objc_v2_prefix_metaclass(
4206                           "_OBJC_METACLASS_$_");
4207                       llvm::StringRef g_objc_v2_prefix_ivar(
4208                           "_OBJC_IVAR_$_");
4209                       if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) {
4210                         symbol_name_non_abi_mangled = symbol_name + 1;
4211                         symbol_name =
4212                             symbol_name + g_objc_v2_prefix_class.size();
4213                         type = eSymbolTypeObjCClass;
4214                         demangled_is_synthesized = true;
4215                       } else if (symbol_name_ref.startswith(
4216                                      g_objc_v2_prefix_metaclass)) {
4217                         symbol_name_non_abi_mangled = symbol_name + 1;
4218                         symbol_name =
4219                             symbol_name + g_objc_v2_prefix_metaclass.size();
4220                         type = eSymbolTypeObjCMetaClass;
4221                         demangled_is_synthesized = true;
4222                       } else if (symbol_name_ref.startswith(
4223                                      g_objc_v2_prefix_ivar)) {
4224                         symbol_name_non_abi_mangled = symbol_name + 1;
4225                         symbol_name =
4226                             symbol_name + g_objc_v2_prefix_ivar.size();
4227                         type = eSymbolTypeObjCIVar;
4228                         demangled_is_synthesized = true;
4229                       }
4230                     }
4231                   }
4232                 } else if (symbol_sect_name &&
4233                            ::strstr(symbol_sect_name, "__gcc_except_tab") ==
4234                                symbol_sect_name) {
4235                   type = eSymbolTypeException;
4236                 } else {
4237                   type = eSymbolTypeData;
4238                 }
4239               } else if (symbol_sect_name &&
4240                          ::strstr(symbol_sect_name, "__IMPORT") ==
4241                              symbol_sect_name) {
4242                 type = eSymbolTypeTrampoline;
4243               } else if (symbol_section->IsDescendant(objc_section_sp.get())) {
4244                 type = eSymbolTypeRuntime;
4245                 if (symbol_name && symbol_name[0] == '.') {
4246                   llvm::StringRef symbol_name_ref(symbol_name);
4247                   llvm::StringRef g_objc_v1_prefix_class(
4248                       ".objc_class_name_");
4249                   if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) {
4250                     symbol_name_non_abi_mangled = symbol_name;
4251                     symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4252                     type = eSymbolTypeObjCClass;
4253                     demangled_is_synthesized = true;
4254                   }
4255                 }
4256               }
4257             }
4258           }
4259         } break;
4260         }
4261       }
4262 
4263       if (!add_nlist) {
4264         sym[sym_idx].Clear();
4265         return true;
4266       }
4267 
4268       uint64_t symbol_value = nlist.n_value;
4269 
4270       if (symbol_name_non_abi_mangled) {
4271         sym[sym_idx].GetMangled().SetMangledName(
4272             ConstString(symbol_name_non_abi_mangled));
4273         sym[sym_idx].GetMangled().SetDemangledName(ConstString(symbol_name));
4274       } else {
4275         bool symbol_name_is_mangled = false;
4276 
4277         if (symbol_name && symbol_name[0] == '_') {
4278           symbol_name_is_mangled = symbol_name[1] == '_';
4279           symbol_name++; // Skip the leading underscore
4280         }
4281 
4282         if (symbol_name) {
4283           ConstString const_symbol_name(symbol_name);
4284           sym[sym_idx].GetMangled().SetValue(const_symbol_name,
4285                                              symbol_name_is_mangled);
4286         }
4287       }
4288 
4289       if (is_gsym) {
4290         const char *gsym_name =
4291             sym[sym_idx]
4292                 .GetMangled()
4293                 .GetName(lldb::eLanguageTypeUnknown, Mangled::ePreferMangled)
4294                 .GetCString();
4295         if (gsym_name)
4296           N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4297       }
4298 
4299       if (symbol_section) {
4300         const addr_t section_file_addr = symbol_section->GetFileAddress();
4301         if (symbol_byte_size == 0 && function_starts_count > 0) {
4302           addr_t symbol_lookup_file_addr = nlist.n_value;
4303           // Do an exact address match for non-ARM addresses, else get the
4304           // closest since the symbol might be a thumb symbol which has an
4305           // address with bit zero set.
4306           FunctionStarts::Entry *func_start_entry =
4307               function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
4308           if (is_arm && func_start_entry) {
4309             // Verify that the function start address is the symbol address
4310             // (ARM) or the symbol address + 1 (thumb).
4311             if (func_start_entry->addr != symbol_lookup_file_addr &&
4312                 func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4313               // Not the right entry, NULL it out...
4314               func_start_entry = nullptr;
4315             }
4316           }
4317           if (func_start_entry) {
4318             func_start_entry->data = true;
4319 
4320             addr_t symbol_file_addr = func_start_entry->addr;
4321             if (is_arm)
4322               symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4323 
4324             const FunctionStarts::Entry *next_func_start_entry =
4325                 function_starts.FindNextEntry(func_start_entry);
4326             const addr_t section_end_file_addr =
4327                 section_file_addr + symbol_section->GetByteSize();
4328             if (next_func_start_entry) {
4329               addr_t next_symbol_file_addr = next_func_start_entry->addr;
4330               // Be sure the clear the Thumb address bit when we calculate the
4331               // size from the current and next address
4332               if (is_arm)
4333                 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4334               symbol_byte_size = std::min<lldb::addr_t>(
4335                   next_symbol_file_addr - symbol_file_addr,
4336                   section_end_file_addr - symbol_file_addr);
4337             } else {
4338               symbol_byte_size = section_end_file_addr - symbol_file_addr;
4339             }
4340           }
4341         }
4342         symbol_value -= section_file_addr;
4343       }
4344 
4345       if (!is_debug) {
4346         if (type == eSymbolTypeCode) {
4347           // See if we can find a N_FUN entry for any code symbols. If we do
4348           // find a match, and the name matches, then we can merge the two into
4349           // just the function symbol to avoid duplicate entries in the symbol
4350           // table.
4351           std::pair<ValueToSymbolIndexMap::const_iterator,
4352                     ValueToSymbolIndexMap::const_iterator>
4353               range;
4354           range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4355           if (range.first != range.second) {
4356             for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4357                  pos != range.second; ++pos) {
4358               if (sym[sym_idx].GetMangled().GetName(lldb::eLanguageTypeUnknown,
4359                                                     Mangled::ePreferMangled) ==
4360                   sym[pos->second].GetMangled().GetName(
4361                       lldb::eLanguageTypeUnknown, Mangled::ePreferMangled)) {
4362                 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4363                 // We just need the flags from the linker symbol, so put these
4364                 // flags into the N_FUN flags to avoid duplicate symbols in the
4365                 // symbol table.
4366                 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4367                 sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4368                 if (resolver_addresses.find(nlist.n_value) !=
4369                     resolver_addresses.end())
4370                   sym[pos->second].SetType(eSymbolTypeResolver);
4371                 sym[sym_idx].Clear();
4372                 return true;
4373               }
4374             }
4375           } else {
4376             if (resolver_addresses.find(nlist.n_value) !=
4377                 resolver_addresses.end())
4378               type = eSymbolTypeResolver;
4379           }
4380         } else if (type == eSymbolTypeData || type == eSymbolTypeObjCClass ||
4381                    type == eSymbolTypeObjCMetaClass ||
4382                    type == eSymbolTypeObjCIVar) {
4383           // See if we can find a N_STSYM entry for any data symbols. If we do
4384           // find a match, and the name matches, then we can merge the two into
4385           // just the Static symbol to avoid duplicate entries in the symbol
4386           // table.
4387           std::pair<ValueToSymbolIndexMap::const_iterator,
4388                     ValueToSymbolIndexMap::const_iterator>
4389               range;
4390           range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4391           if (range.first != range.second) {
4392             for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4393                  pos != range.second; ++pos) {
4394               if (sym[sym_idx].GetMangled().GetName(lldb::eLanguageTypeUnknown,
4395                                                     Mangled::ePreferMangled) ==
4396                   sym[pos->second].GetMangled().GetName(
4397                       lldb::eLanguageTypeUnknown, Mangled::ePreferMangled)) {
4398                 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4399                 // We just need the flags from the linker symbol, so put these
4400                 // flags into the N_STSYM flags to avoid duplicate symbols in
4401                 // the symbol table.
4402                 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4403                 sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4404                 sym[sym_idx].Clear();
4405                 return true;
4406               }
4407             }
4408           } else {
4409             // Combine N_GSYM stab entries with the non stab symbol.
4410             const char *gsym_name = sym[sym_idx]
4411                                         .GetMangled()
4412                                         .GetName(lldb::eLanguageTypeUnknown,
4413                                                  Mangled::ePreferMangled)
4414                                         .GetCString();
4415             if (gsym_name) {
4416               ConstNameToSymbolIndexMap::const_iterator pos =
4417                   N_GSYM_name_to_sym_idx.find(gsym_name);
4418               if (pos != N_GSYM_name_to_sym_idx.end()) {
4419                 const uint32_t GSYM_sym_idx = pos->second;
4420                 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
4421                 // Copy the address, because often the N_GSYM address has an
4422                 // invalid address of zero when the global is a common symbol.
4423                 sym[GSYM_sym_idx].GetAddressRef().SetSection(symbol_section);
4424                 sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4425                 // We just need the flags from the linker symbol, so put these
4426                 // flags into the N_GSYM flags to avoid duplicate symbols in
4427                 // the symbol table.
4428                 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4429                 sym[sym_idx].Clear();
4430                 return true;
4431               }
4432             }
4433           }
4434         }
4435       }
4436 
4437       sym[sym_idx].SetID(nlist_idx);
4438       sym[sym_idx].SetType(type);
4439       if (set_value) {
4440         sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4441         sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4442       }
4443       sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4444       if (nlist.n_desc & N_WEAK_REF)
4445         sym[sym_idx].SetIsWeak(true);
4446 
4447       if (symbol_byte_size > 0)
4448         sym[sym_idx].SetByteSize(symbol_byte_size);
4449 
4450       if (demangled_is_synthesized)
4451         sym[sym_idx].SetDemangledNameIsSynthesized(true);
4452 
4453       ++sym_idx;
4454       return true;
4455     };
4456 
4457     // First parse all the nlists but don't process them yet. See the next
4458     // comment for an explanation why.
4459     std::vector<struct nlist_64> nlists;
4460     nlists.reserve(symtab_load_command.nsyms);
4461     for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
4462       if (auto nlist =
4463               ParseNList(nlist_data, nlist_data_offset, nlist_byte_size))
4464         nlists.push_back(*nlist);
4465       else
4466         break;
4467     }
4468 
4469     // Now parse all the debug symbols. This is needed to merge non-debug
4470     // symbols in the next step. Non-debug symbols are always coalesced into
4471     // the debug symbol. Doing this in one step would mean that some symbols
4472     // won't be merged.
4473     nlist_idx = 0;
4474     for (auto &nlist : nlists) {
4475       if (!ParseSymbolLambda(nlist, nlist_idx++, DebugSymbols))
4476         break;
4477     }
4478 
4479     // Finally parse all the non debug symbols.
4480     nlist_idx = 0;
4481     for (auto &nlist : nlists) {
4482       if (!ParseSymbolLambda(nlist, nlist_idx++, NonDebugSymbols))
4483         break;
4484     }
4485 
4486     for (const auto &pos : reexport_shlib_needs_fixup) {
4487       const auto undef_pos = undefined_name_to_desc.find(pos.second);
4488       if (undef_pos != undefined_name_to_desc.end()) {
4489         const uint8_t dylib_ordinal =
4490             llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4491         if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4492           sym[pos.first].SetReExportedSymbolSharedLibrary(
4493               dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
4494       }
4495     }
4496   }
4497 
4498   uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4499 
4500   if (function_starts_count > 0) {
4501     uint32_t num_synthetic_function_symbols = 0;
4502     for (i = 0; i < function_starts_count; ++i) {
4503       if (!function_starts.GetEntryRef(i).data)
4504         ++num_synthetic_function_symbols;
4505     }
4506 
4507     if (num_synthetic_function_symbols > 0) {
4508       if (num_syms < sym_idx + num_synthetic_function_symbols) {
4509         num_syms = sym_idx + num_synthetic_function_symbols;
4510         sym = symtab->Resize(num_syms);
4511       }
4512       for (i = 0; i < function_starts_count; ++i) {
4513         const FunctionStarts::Entry *func_start_entry =
4514             function_starts.GetEntryAtIndex(i);
4515         if (!func_start_entry->data) {
4516           addr_t symbol_file_addr = func_start_entry->addr;
4517           uint32_t symbol_flags = 0;
4518           if (is_arm) {
4519             if (symbol_file_addr & 1)
4520               symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4521             symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4522           }
4523           Address symbol_addr;
4524           if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
4525             SectionSP symbol_section(symbol_addr.GetSection());
4526             uint32_t symbol_byte_size = 0;
4527             if (symbol_section) {
4528               const addr_t section_file_addr = symbol_section->GetFileAddress();
4529               const FunctionStarts::Entry *next_func_start_entry =
4530                   function_starts.FindNextEntry(func_start_entry);
4531               const addr_t section_end_file_addr =
4532                   section_file_addr + symbol_section->GetByteSize();
4533               if (next_func_start_entry) {
4534                 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4535                 if (is_arm)
4536                   next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4537                 symbol_byte_size = std::min<lldb::addr_t>(
4538                     next_symbol_file_addr - symbol_file_addr,
4539                     section_end_file_addr - symbol_file_addr);
4540               } else {
4541                 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4542               }
4543               sym[sym_idx].SetID(synthetic_sym_id++);
4544               sym[sym_idx].GetMangled().SetDemangledName(
4545                   GetNextSyntheticSymbolName());
4546               sym[sym_idx].SetType(eSymbolTypeCode);
4547               sym[sym_idx].SetIsSynthetic(true);
4548               sym[sym_idx].GetAddressRef() = symbol_addr;
4549               if (symbol_flags)
4550                 sym[sym_idx].SetFlags(symbol_flags);
4551               if (symbol_byte_size)
4552                 sym[sym_idx].SetByteSize(symbol_byte_size);
4553               ++sym_idx;
4554             }
4555           }
4556         }
4557       }
4558     }
4559   }
4560 
4561   // Trim our symbols down to just what we ended up with after removing any
4562   // symbols.
4563   if (sym_idx < num_syms) {
4564     num_syms = sym_idx;
4565     sym = symtab->Resize(num_syms);
4566   }
4567 
4568   // Now synthesize indirect symbols
4569   if (m_dysymtab.nindirectsyms != 0) {
4570     if (indirect_symbol_index_data.GetByteSize()) {
4571       NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4572           m_nlist_idx_to_sym_idx.end();
4573 
4574       for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4575            ++sect_idx) {
4576         if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4577             S_SYMBOL_STUBS) {
4578           uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2;
4579           if (symbol_stub_byte_size == 0)
4580             continue;
4581 
4582           const uint32_t num_symbol_stubs =
4583               m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4584 
4585           if (num_symbol_stubs == 0)
4586             continue;
4587 
4588           const uint32_t symbol_stub_index_offset =
4589               m_mach_sections[sect_idx].reserved1;
4590           for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx) {
4591             const uint32_t symbol_stub_index =
4592                 symbol_stub_index_offset + stub_idx;
4593             const lldb::addr_t symbol_stub_addr =
4594                 m_mach_sections[sect_idx].addr +
4595                 (stub_idx * symbol_stub_byte_size);
4596             lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4597             if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4598                     symbol_stub_offset, 4)) {
4599               const uint32_t stub_sym_id =
4600                   indirect_symbol_index_data.GetU32(&symbol_stub_offset);
4601               if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4602                 continue;
4603 
4604               NListIndexToSymbolIndexMap::const_iterator index_pos =
4605                   m_nlist_idx_to_sym_idx.find(stub_sym_id);
4606               Symbol *stub_symbol = nullptr;
4607               if (index_pos != end_index_pos) {
4608                 // We have a remapping from the original nlist index to a
4609                 // current symbol index, so just look this up by index
4610                 stub_symbol = symtab->SymbolAtIndex(index_pos->second);
4611               } else {
4612                 // We need to lookup a symbol using the original nlist symbol
4613                 // index since this index is coming from the S_SYMBOL_STUBS
4614                 stub_symbol = symtab->FindSymbolByID(stub_sym_id);
4615               }
4616 
4617               if (stub_symbol) {
4618                 Address so_addr(symbol_stub_addr, section_list);
4619 
4620                 if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4621                   // Change the external symbol into a trampoline that makes
4622                   // sense These symbols were N_UNDF N_EXT, and are useless
4623                   // to us, so we can re-use them so we don't have to make up
4624                   // a synthetic symbol for no good reason.
4625                   if (resolver_addresses.find(symbol_stub_addr) ==
4626                       resolver_addresses.end())
4627                     stub_symbol->SetType(eSymbolTypeTrampoline);
4628                   else
4629                     stub_symbol->SetType(eSymbolTypeResolver);
4630                   stub_symbol->SetExternal(false);
4631                   stub_symbol->GetAddressRef() = so_addr;
4632                   stub_symbol->SetByteSize(symbol_stub_byte_size);
4633                 } else {
4634                   // Make a synthetic symbol to describe the trampoline stub
4635                   Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4636                   if (sym_idx >= num_syms) {
4637                     sym = symtab->Resize(++num_syms);
4638                     stub_symbol = nullptr; // this pointer no longer valid
4639                   }
4640                   sym[sym_idx].SetID(synthetic_sym_id++);
4641                   sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4642                   if (resolver_addresses.find(symbol_stub_addr) ==
4643                       resolver_addresses.end())
4644                     sym[sym_idx].SetType(eSymbolTypeTrampoline);
4645                   else
4646                     sym[sym_idx].SetType(eSymbolTypeResolver);
4647                   sym[sym_idx].SetIsSynthetic(true);
4648                   sym[sym_idx].GetAddressRef() = so_addr;
4649                   sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4650                   ++sym_idx;
4651                 }
4652               } else {
4653                 if (log)
4654                   log->Warning("symbol stub referencing symbol table symbol "
4655                                "%u that isn't in our minimal symbol table, "
4656                                "fix this!!!",
4657                                stub_sym_id);
4658               }
4659             }
4660           }
4661         }
4662       }
4663     }
4664   }
4665 
4666   if (!trie_entries.empty()) {
4667     for (const auto &e : trie_entries) {
4668       if (e.entry.import_name) {
4669         // Only add indirect symbols from the Trie entries if we didn't have
4670         // a N_INDR nlist entry for this already
4671         if (indirect_symbol_names.find(e.entry.name) ==
4672             indirect_symbol_names.end()) {
4673           // Make a synthetic symbol to describe re-exported symbol.
4674           if (sym_idx >= num_syms)
4675             sym = symtab->Resize(++num_syms);
4676           sym[sym_idx].SetID(synthetic_sym_id++);
4677           sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4678           sym[sym_idx].SetType(eSymbolTypeReExported);
4679           sym[sym_idx].SetIsSynthetic(true);
4680           sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4681           if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4682             sym[sym_idx].SetReExportedSymbolSharedLibrary(
4683                 dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
4684           }
4685           ++sym_idx;
4686         }
4687       }
4688     }
4689   }
4690 
4691   //        StreamFile s(stdout, false);
4692   //        s.Printf ("Symbol table before CalculateSymbolSizes():\n");
4693   //        symtab->Dump(&s, NULL, eSortOrderNone);
4694   // Set symbol byte sizes correctly since mach-o nlist entries don't have
4695   // sizes
4696   symtab->CalculateSymbolSizes();
4697 
4698   //        s.Printf ("Symbol table after CalculateSymbolSizes():\n");
4699   //        symtab->Dump(&s, NULL, eSortOrderNone);
4700 
4701   return symtab->GetNumSymbols();
4702 }
4703 
4704 void ObjectFileMachO::Dump(Stream *s) {
4705   ModuleSP module_sp(GetModule());
4706   if (module_sp) {
4707     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4708     s->Printf("%p: ", static_cast<void *>(this));
4709     s->Indent();
4710     if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4711       s->PutCString("ObjectFileMachO64");
4712     else
4713       s->PutCString("ObjectFileMachO32");
4714 
4715     *s << ", file = '" << m_file;
4716     ModuleSpecList all_specs;
4717     ModuleSpec base_spec;
4718     GetAllArchSpecs(m_header, m_data, MachHeaderSizeFromMagic(m_header.magic),
4719                     base_spec, all_specs);
4720     for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
4721       *s << "', triple";
4722       if (e)
4723         s->Printf("[%d]", i);
4724       *s << " = ";
4725       *s << all_specs.GetModuleSpecRefAtIndex(i)
4726                 .GetArchitecture()
4727                 .GetTriple()
4728                 .getTriple();
4729     }
4730     *s << "\n";
4731     SectionList *sections = GetSectionList();
4732     if (sections)
4733       sections->Dump(s, nullptr, true, UINT32_MAX);
4734 
4735     if (m_symtab_up)
4736       m_symtab_up->Dump(s, nullptr, eSortOrderNone);
4737   }
4738 }
4739 
4740 UUID ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4741                               const lldb_private::DataExtractor &data,
4742                               lldb::offset_t lc_offset) {
4743   uint32_t i;
4744   struct uuid_command load_cmd;
4745 
4746   lldb::offset_t offset = lc_offset;
4747   for (i = 0; i < header.ncmds; ++i) {
4748     const lldb::offset_t cmd_offset = offset;
4749     if (data.GetU32(&offset, &load_cmd, 2) == nullptr)
4750       break;
4751 
4752     if (load_cmd.cmd == LC_UUID) {
4753       const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4754 
4755       if (uuid_bytes) {
4756         // OpenCL on Mac OS X uses the same UUID for each of its object files.
4757         // We pretend these object files have no UUID to prevent crashing.
4758 
4759         const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4760                                        0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4761                                        0xbb, 0x14, 0xf0, 0x0d};
4762 
4763         if (!memcmp(uuid_bytes, opencl_uuid, 16))
4764           return UUID();
4765 
4766         return UUID::fromOptionalData(uuid_bytes, 16);
4767       }
4768       return UUID();
4769     }
4770     offset = cmd_offset + load_cmd.cmdsize;
4771   }
4772   return UUID();
4773 }
4774 
4775 static llvm::StringRef GetOSName(uint32_t cmd) {
4776   switch (cmd) {
4777   case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
4778     return llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4779   case llvm::MachO::LC_VERSION_MIN_MACOSX:
4780     return llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4781   case llvm::MachO::LC_VERSION_MIN_TVOS:
4782     return llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4783   case llvm::MachO::LC_VERSION_MIN_WATCHOS:
4784     return llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4785   default:
4786     llvm_unreachable("unexpected LC_VERSION load command");
4787   }
4788 }
4789 
4790 namespace {
4791 struct OSEnv {
4792   llvm::StringRef os_type;
4793   llvm::StringRef environment;
4794   OSEnv(uint32_t cmd) {
4795     switch (cmd) {
4796     case llvm::MachO::PLATFORM_MACOS:
4797       os_type = llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4798       return;
4799     case llvm::MachO::PLATFORM_IOS:
4800       os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4801       return;
4802     case llvm::MachO::PLATFORM_TVOS:
4803       os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4804       return;
4805     case llvm::MachO::PLATFORM_WATCHOS:
4806       os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4807       return;
4808       // NEED_BRIDGEOS_TRIPLE      case llvm::MachO::PLATFORM_BRIDGEOS:
4809       // NEED_BRIDGEOS_TRIPLE        os_type =
4810       // llvm::Triple::getOSTypeName(llvm::Triple::BridgeOS);
4811       // NEED_BRIDGEOS_TRIPLE        return;
4812     case llvm::MachO::PLATFORM_MACCATALYST:
4813       os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4814       environment = llvm::Triple::getEnvironmentTypeName(llvm::Triple::MacABI);
4815       return;
4816     case llvm::MachO::PLATFORM_IOSSIMULATOR:
4817       os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4818       environment =
4819           llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4820       return;
4821     case llvm::MachO::PLATFORM_TVOSSIMULATOR:
4822       os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4823       environment =
4824           llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4825       return;
4826     case llvm::MachO::PLATFORM_WATCHOSSIMULATOR:
4827       os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4828       environment =
4829           llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4830       return;
4831     default: {
4832       Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
4833                                                       LIBLLDB_LOG_PROCESS));
4834       LLDB_LOGF(log, "unsupported platform in LC_BUILD_VERSION");
4835     }
4836     }
4837   }
4838 };
4839 
4840 struct MinOS {
4841   uint32_t major_version, minor_version, patch_version;
4842   MinOS(uint32_t version)
4843       : major_version(version >> 16), minor_version((version >> 8) & 0xffu),
4844         patch_version(version & 0xffu) {}
4845 };
4846 } // namespace
4847 
4848 void ObjectFileMachO::GetAllArchSpecs(const llvm::MachO::mach_header &header,
4849                                       const lldb_private::DataExtractor &data,
4850                                       lldb::offset_t lc_offset,
4851                                       ModuleSpec &base_spec,
4852                                       lldb_private::ModuleSpecList &all_specs) {
4853   auto &base_arch = base_spec.GetArchitecture();
4854   base_arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
4855   if (!base_arch.IsValid())
4856     return;
4857 
4858   bool found_any = false;
4859   auto add_triple = [&](const llvm::Triple &triple) {
4860     auto spec = base_spec;
4861     spec.GetArchitecture().GetTriple() = triple;
4862     if (spec.GetArchitecture().IsValid()) {
4863       spec.GetUUID() = ObjectFileMachO::GetUUID(header, data, lc_offset);
4864       all_specs.Append(spec);
4865       found_any = true;
4866     }
4867   };
4868 
4869   // Set OS to an unspecified unknown or a "*" so it can match any OS
4870   llvm::Triple base_triple = base_arch.GetTriple();
4871   base_triple.setOS(llvm::Triple::UnknownOS);
4872   base_triple.setOSName(llvm::StringRef());
4873 
4874   if (header.filetype == MH_PRELOAD) {
4875     if (header.cputype == CPU_TYPE_ARM) {
4876       // If this is a 32-bit arm binary, and it's a standalone binary, force
4877       // the Vendor to Apple so we don't accidentally pick up the generic
4878       // armv7 ABI at runtime.  Apple's armv7 ABI always uses r7 for the
4879       // frame pointer register; most other armv7 ABIs use a combination of
4880       // r7 and r11.
4881       base_triple.setVendor(llvm::Triple::Apple);
4882     } else {
4883       // Set vendor to an unspecified unknown or a "*" so it can match any
4884       // vendor This is required for correct behavior of EFI debugging on
4885       // x86_64
4886       base_triple.setVendor(llvm::Triple::UnknownVendor);
4887       base_triple.setVendorName(llvm::StringRef());
4888     }
4889     return add_triple(base_triple);
4890   }
4891 
4892   struct load_command load_cmd;
4893 
4894   // See if there is an LC_VERSION_MIN_* load command that can give
4895   // us the OS type.
4896   lldb::offset_t offset = lc_offset;
4897   for (uint32_t i = 0; i < header.ncmds; ++i) {
4898     const lldb::offset_t cmd_offset = offset;
4899     if (data.GetU32(&offset, &load_cmd, 2) == NULL)
4900       break;
4901 
4902     struct version_min_command version_min;
4903     switch (load_cmd.cmd) {
4904     case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
4905     case llvm::MachO::LC_VERSION_MIN_MACOSX:
4906     case llvm::MachO::LC_VERSION_MIN_TVOS:
4907     case llvm::MachO::LC_VERSION_MIN_WATCHOS: {
4908       if (load_cmd.cmdsize != sizeof(version_min))
4909         break;
4910       if (data.ExtractBytes(cmd_offset, sizeof(version_min),
4911                             data.GetByteOrder(), &version_min) == 0)
4912         break;
4913       MinOS min_os(version_min.version);
4914       llvm::SmallString<32> os_name;
4915       llvm::raw_svector_ostream os(os_name);
4916       os << GetOSName(load_cmd.cmd) << min_os.major_version << '.'
4917          << min_os.minor_version << '.' << min_os.patch_version;
4918 
4919       auto triple = base_triple;
4920       triple.setOSName(os.str());
4921       os_name.clear();
4922       add_triple(triple);
4923       break;
4924     }
4925     default:
4926       break;
4927     }
4928 
4929     offset = cmd_offset + load_cmd.cmdsize;
4930   }
4931 
4932   // See if there are LC_BUILD_VERSION load commands that can give
4933   // us the OS type.
4934   offset = lc_offset;
4935   for (uint32_t i = 0; i < header.ncmds; ++i) {
4936     const lldb::offset_t cmd_offset = offset;
4937     if (data.GetU32(&offset, &load_cmd, 2) == NULL)
4938       break;
4939 
4940     do {
4941       if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) {
4942         struct build_version_command build_version;
4943         if (load_cmd.cmdsize < sizeof(build_version)) {
4944           // Malformed load command.
4945           break;
4946         }
4947         if (data.ExtractBytes(cmd_offset, sizeof(build_version),
4948                               data.GetByteOrder(), &build_version) == 0)
4949           break;
4950         MinOS min_os(build_version.minos);
4951         OSEnv os_env(build_version.platform);
4952         llvm::SmallString<16> os_name;
4953         llvm::raw_svector_ostream os(os_name);
4954         os << os_env.os_type << min_os.major_version << '.'
4955            << min_os.minor_version << '.' << min_os.patch_version;
4956         auto triple = base_triple;
4957         triple.setOSName(os.str());
4958         os_name.clear();
4959         if (!os_env.environment.empty())
4960           triple.setEnvironmentName(os_env.environment);
4961         add_triple(triple);
4962       }
4963     } while (0);
4964     offset = cmd_offset + load_cmd.cmdsize;
4965   }
4966 
4967   if (!found_any) {
4968     if (header.filetype == MH_KEXT_BUNDLE) {
4969       base_triple.setVendor(llvm::Triple::Apple);
4970       add_triple(base_triple);
4971     } else {
4972       // We didn't find a LC_VERSION_MIN load command and this isn't a KEXT
4973       // so lets not say our Vendor is Apple, leave it as an unspecified
4974       // unknown.
4975       base_triple.setVendor(llvm::Triple::UnknownVendor);
4976       base_triple.setVendorName(llvm::StringRef());
4977       add_triple(base_triple);
4978     }
4979   }
4980 }
4981 
4982 ArchSpec ObjectFileMachO::GetArchitecture(
4983     ModuleSP module_sp, const llvm::MachO::mach_header &header,
4984     const lldb_private::DataExtractor &data, lldb::offset_t lc_offset) {
4985   ModuleSpecList all_specs;
4986   ModuleSpec base_spec;
4987   GetAllArchSpecs(header, data, MachHeaderSizeFromMagic(header.magic),
4988                   base_spec, all_specs);
4989 
4990   // If the object file offers multiple alternative load commands,
4991   // pick the one that matches the module.
4992   if (module_sp) {
4993     const ArchSpec &module_arch = module_sp->GetArchitecture();
4994     for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
4995       ArchSpec mach_arch =
4996           all_specs.GetModuleSpecRefAtIndex(i).GetArchitecture();
4997       if (module_arch.IsCompatibleMatch(mach_arch))
4998         return mach_arch;
4999     }
5000   }
5001 
5002   // Return the first arch we found.
5003   if (all_specs.GetSize() == 0)
5004     return {};
5005   return all_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
5006 }
5007 
5008 UUID ObjectFileMachO::GetUUID() {
5009   ModuleSP module_sp(GetModule());
5010   if (module_sp) {
5011     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5012     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5013     return GetUUID(m_header, m_data, offset);
5014   }
5015   return UUID();
5016 }
5017 
5018 uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) {
5019   uint32_t count = 0;
5020   ModuleSP module_sp(GetModule());
5021   if (module_sp) {
5022     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5023     struct load_command load_cmd;
5024     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5025     std::vector<std::string> rpath_paths;
5026     std::vector<std::string> rpath_relative_paths;
5027     std::vector<std::string> at_exec_relative_paths;
5028     uint32_t i;
5029     for (i = 0; i < m_header.ncmds; ++i) {
5030       const uint32_t cmd_offset = offset;
5031       if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
5032         break;
5033 
5034       switch (load_cmd.cmd) {
5035       case LC_RPATH:
5036       case LC_LOAD_DYLIB:
5037       case LC_LOAD_WEAK_DYLIB:
5038       case LC_REEXPORT_DYLIB:
5039       case LC_LOAD_DYLINKER:
5040       case LC_LOADFVMLIB:
5041       case LC_LOAD_UPWARD_DYLIB: {
5042         uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
5043         const char *path = m_data.PeekCStr(name_offset);
5044         if (path) {
5045           if (load_cmd.cmd == LC_RPATH)
5046             rpath_paths.push_back(path);
5047           else {
5048             if (path[0] == '@') {
5049               if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
5050                 rpath_relative_paths.push_back(path + strlen("@rpath"));
5051               else if (strncmp(path, "@executable_path",
5052                                strlen("@executable_path")) == 0)
5053                 at_exec_relative_paths.push_back(path +
5054                                                  strlen("@executable_path"));
5055             } else {
5056               FileSpec file_spec(path);
5057               if (files.AppendIfUnique(file_spec))
5058                 count++;
5059             }
5060           }
5061         }
5062       } break;
5063 
5064       default:
5065         break;
5066       }
5067       offset = cmd_offset + load_cmd.cmdsize;
5068     }
5069 
5070     FileSpec this_file_spec(m_file);
5071     FileSystem::Instance().Resolve(this_file_spec);
5072 
5073     if (!rpath_paths.empty()) {
5074       // Fixup all LC_RPATH values to be absolute paths
5075       std::string loader_path("@loader_path");
5076       std::string executable_path("@executable_path");
5077       for (auto &rpath : rpath_paths) {
5078         if (rpath.find(loader_path) == 0) {
5079           rpath.erase(0, loader_path.size());
5080           rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5081         } else if (rpath.find(executable_path) == 0) {
5082           rpath.erase(0, executable_path.size());
5083           rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5084         }
5085       }
5086 
5087       for (const auto &rpath_relative_path : rpath_relative_paths) {
5088         for (const auto &rpath : rpath_paths) {
5089           std::string path = rpath;
5090           path += rpath_relative_path;
5091           // It is OK to resolve this path because we must find a file on disk
5092           // for us to accept it anyway if it is rpath relative.
5093           FileSpec file_spec(path);
5094           FileSystem::Instance().Resolve(file_spec);
5095           if (FileSystem::Instance().Exists(file_spec) &&
5096               files.AppendIfUnique(file_spec)) {
5097             count++;
5098             break;
5099           }
5100         }
5101       }
5102     }
5103 
5104     // We may have @executable_paths but no RPATHS.  Figure those out here.
5105     // Only do this if this object file is the executable.  We have no way to
5106     // get back to the actual executable otherwise, so we won't get the right
5107     // path.
5108     if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
5109       FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
5110       for (const auto &at_exec_relative_path : at_exec_relative_paths) {
5111         FileSpec file_spec =
5112             exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
5113         if (FileSystem::Instance().Exists(file_spec) &&
5114             files.AppendIfUnique(file_spec))
5115           count++;
5116       }
5117     }
5118   }
5119   return count;
5120 }
5121 
5122 lldb_private::Address ObjectFileMachO::GetEntryPointAddress() {
5123   // If the object file is not an executable it can't hold the entry point.
5124   // m_entry_point_address is initialized to an invalid address, so we can just
5125   // return that. If m_entry_point_address is valid it means we've found it
5126   // already, so return the cached value.
5127 
5128   if ((!IsExecutable() && !IsDynamicLoader()) ||
5129       m_entry_point_address.IsValid()) {
5130     return m_entry_point_address;
5131   }
5132 
5133   // Otherwise, look for the UnixThread or Thread command.  The data for the
5134   // Thread command is given in /usr/include/mach-o.h, but it is basically:
5135   //
5136   //  uint32_t flavor  - this is the flavor argument you would pass to
5137   //  thread_get_state
5138   //  uint32_t count   - this is the count of longs in the thread state data
5139   //  struct XXX_thread_state state - this is the structure from
5140   //  <machine/thread_status.h> corresponding to the flavor.
5141   //  <repeat this trio>
5142   //
5143   // So we just keep reading the various register flavors till we find the GPR
5144   // one, then read the PC out of there.
5145   // FIXME: We will need to have a "RegisterContext data provider" class at some
5146   // point that can get all the registers
5147   // out of data in this form & attach them to a given thread.  That should
5148   // underlie the MacOS X User process plugin, and we'll also need it for the
5149   // MacOS X Core File process plugin.  When we have that we can also use it
5150   // here.
5151   //
5152   // For now we hard-code the offsets and flavors we need:
5153   //
5154   //
5155 
5156   ModuleSP module_sp(GetModule());
5157   if (module_sp) {
5158     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5159     struct load_command load_cmd;
5160     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5161     uint32_t i;
5162     lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
5163     bool done = false;
5164 
5165     for (i = 0; i < m_header.ncmds; ++i) {
5166       const lldb::offset_t cmd_offset = offset;
5167       if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
5168         break;
5169 
5170       switch (load_cmd.cmd) {
5171       case LC_UNIXTHREAD:
5172       case LC_THREAD: {
5173         while (offset < cmd_offset + load_cmd.cmdsize) {
5174           uint32_t flavor = m_data.GetU32(&offset);
5175           uint32_t count = m_data.GetU32(&offset);
5176           if (count == 0) {
5177             // We've gotten off somehow, log and exit;
5178             return m_entry_point_address;
5179           }
5180 
5181           switch (m_header.cputype) {
5182           case llvm::MachO::CPU_TYPE_ARM:
5183             if (flavor == 1 ||
5184                 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32
5185                              // from mach/arm/thread_status.h
5186             {
5187               offset += 60; // This is the offset of pc in the GPR thread state
5188                             // data structure.
5189               start_address = m_data.GetU32(&offset);
5190               done = true;
5191             }
5192             break;
5193           case llvm::MachO::CPU_TYPE_ARM64:
5194           case llvm::MachO::CPU_TYPE_ARM64_32:
5195             if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
5196             {
5197               offset += 256; // This is the offset of pc in the GPR thread state
5198                              // data structure.
5199               start_address = m_data.GetU64(&offset);
5200               done = true;
5201             }
5202             break;
5203           case llvm::MachO::CPU_TYPE_I386:
5204             if (flavor ==
5205                 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
5206             {
5207               offset += 40; // This is the offset of eip in the GPR thread state
5208                             // data structure.
5209               start_address = m_data.GetU32(&offset);
5210               done = true;
5211             }
5212             break;
5213           case llvm::MachO::CPU_TYPE_X86_64:
5214             if (flavor ==
5215                 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
5216             {
5217               offset += 16 * 8; // This is the offset of rip in the GPR thread
5218                                 // state data structure.
5219               start_address = m_data.GetU64(&offset);
5220               done = true;
5221             }
5222             break;
5223           default:
5224             return m_entry_point_address;
5225           }
5226           // Haven't found the GPR flavor yet, skip over the data for this
5227           // flavor:
5228           if (done)
5229             break;
5230           offset += count * 4;
5231         }
5232       } break;
5233       case LC_MAIN: {
5234         ConstString text_segment_name("__TEXT");
5235         uint64_t entryoffset = m_data.GetU64(&offset);
5236         SectionSP text_segment_sp =
5237             GetSectionList()->FindSectionByName(text_segment_name);
5238         if (text_segment_sp) {
5239           done = true;
5240           start_address = text_segment_sp->GetFileAddress() + entryoffset;
5241         }
5242       } break;
5243 
5244       default:
5245         break;
5246       }
5247       if (done)
5248         break;
5249 
5250       // Go to the next load command:
5251       offset = cmd_offset + load_cmd.cmdsize;
5252     }
5253 
5254     if (start_address == LLDB_INVALID_ADDRESS && IsDynamicLoader()) {
5255       if (GetSymtab()) {
5256         Symbol *dyld_start_sym = GetSymtab()->FindFirstSymbolWithNameAndType(
5257             ConstString("_dyld_start"), SymbolType::eSymbolTypeCode,
5258             Symtab::eDebugAny, Symtab::eVisibilityAny);
5259         if (dyld_start_sym && dyld_start_sym->GetAddress().IsValid()) {
5260           start_address = dyld_start_sym->GetAddress().GetFileAddress();
5261         }
5262       }
5263     }
5264 
5265     if (start_address != LLDB_INVALID_ADDRESS) {
5266       // We got the start address from the load commands, so now resolve that
5267       // address in the sections of this ObjectFile:
5268       if (!m_entry_point_address.ResolveAddressUsingFileSections(
5269               start_address, GetSectionList())) {
5270         m_entry_point_address.Clear();
5271       }
5272     } else {
5273       // We couldn't read the UnixThread load command - maybe it wasn't there.
5274       // As a fallback look for the "start" symbol in the main executable.
5275 
5276       ModuleSP module_sp(GetModule());
5277 
5278       if (module_sp) {
5279         SymbolContextList contexts;
5280         SymbolContext context;
5281         module_sp->FindSymbolsWithNameAndType(ConstString("start"),
5282                                               eSymbolTypeCode, contexts);
5283         if (contexts.GetSize()) {
5284           if (contexts.GetContextAtIndex(0, context))
5285             m_entry_point_address = context.symbol->GetAddress();
5286         }
5287       }
5288     }
5289   }
5290 
5291   return m_entry_point_address;
5292 }
5293 
5294 lldb_private::Address ObjectFileMachO::GetBaseAddress() {
5295   lldb_private::Address header_addr;
5296   SectionList *section_list = GetSectionList();
5297   if (section_list) {
5298     SectionSP text_segment_sp(
5299         section_list->FindSectionByName(GetSegmentNameTEXT()));
5300     if (text_segment_sp) {
5301       header_addr.SetSection(text_segment_sp);
5302       header_addr.SetOffset(0);
5303     }
5304   }
5305   return header_addr;
5306 }
5307 
5308 uint32_t ObjectFileMachO::GetNumThreadContexts() {
5309   ModuleSP module_sp(GetModule());
5310   if (module_sp) {
5311     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5312     if (!m_thread_context_offsets_valid) {
5313       m_thread_context_offsets_valid = true;
5314       lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5315       FileRangeArray::Entry file_range;
5316       thread_command thread_cmd;
5317       for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5318         const uint32_t cmd_offset = offset;
5319         if (m_data.GetU32(&offset, &thread_cmd, 2) == nullptr)
5320           break;
5321 
5322         if (thread_cmd.cmd == LC_THREAD) {
5323           file_range.SetRangeBase(offset);
5324           file_range.SetByteSize(thread_cmd.cmdsize - 8);
5325           m_thread_context_offsets.Append(file_range);
5326         }
5327         offset = cmd_offset + thread_cmd.cmdsize;
5328       }
5329     }
5330   }
5331   return m_thread_context_offsets.GetSize();
5332 }
5333 
5334 std::string ObjectFileMachO::GetIdentifierString() {
5335   std::string result;
5336   ModuleSP module_sp(GetModule());
5337   if (module_sp) {
5338     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5339 
5340     // First, look over the load commands for an LC_NOTE load command with
5341     // data_owner string "kern ver str" & use that if found.
5342     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5343     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5344       const uint32_t cmd_offset = offset;
5345       load_command lc;
5346       if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5347         break;
5348       if (lc.cmd == LC_NOTE) {
5349         char data_owner[17];
5350         m_data.CopyData(offset, 16, data_owner);
5351         data_owner[16] = '\0';
5352         offset += 16;
5353         uint64_t fileoff = m_data.GetU64_unchecked(&offset);
5354         uint64_t size = m_data.GetU64_unchecked(&offset);
5355 
5356         // "kern ver str" has a uint32_t version and then a nul terminated
5357         // c-string.
5358         if (strcmp("kern ver str", data_owner) == 0) {
5359           offset = fileoff;
5360           uint32_t version;
5361           if (m_data.GetU32(&offset, &version, 1) != nullptr) {
5362             if (version == 1) {
5363               uint32_t strsize = size - sizeof(uint32_t);
5364               char *buf = (char *)malloc(strsize);
5365               if (buf) {
5366                 m_data.CopyData(offset, strsize, buf);
5367                 buf[strsize - 1] = '\0';
5368                 result = buf;
5369                 if (buf)
5370                   free(buf);
5371                 return result;
5372               }
5373             }
5374           }
5375         }
5376       }
5377       offset = cmd_offset + lc.cmdsize;
5378     }
5379 
5380     // Second, make a pass over the load commands looking for an obsolete
5381     // LC_IDENT load command.
5382     offset = MachHeaderSizeFromMagic(m_header.magic);
5383     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5384       const uint32_t cmd_offset = offset;
5385       struct ident_command ident_command;
5386       if (m_data.GetU32(&offset, &ident_command, 2) == nullptr)
5387         break;
5388       if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
5389         char *buf = (char *)malloc(ident_command.cmdsize);
5390         if (buf != nullptr && m_data.CopyData(offset, ident_command.cmdsize,
5391                                               buf) == ident_command.cmdsize) {
5392           buf[ident_command.cmdsize - 1] = '\0';
5393           result = buf;
5394         }
5395         if (buf)
5396           free(buf);
5397       }
5398       offset = cmd_offset + ident_command.cmdsize;
5399     }
5400   }
5401   return result;
5402 }
5403 
5404 bool ObjectFileMachO::GetCorefileMainBinaryInfo(addr_t &address, UUID &uuid) {
5405   address = LLDB_INVALID_ADDRESS;
5406   uuid.Clear();
5407   ModuleSP module_sp(GetModule());
5408   if (module_sp) {
5409     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5410     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5411     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5412       const uint32_t cmd_offset = offset;
5413       load_command lc;
5414       if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5415         break;
5416       if (lc.cmd == LC_NOTE) {
5417         char data_owner[17];
5418         memset(data_owner, 0, sizeof(data_owner));
5419         m_data.CopyData(offset, 16, data_owner);
5420         offset += 16;
5421         uint64_t fileoff = m_data.GetU64_unchecked(&offset);
5422         uint64_t size = m_data.GetU64_unchecked(&offset);
5423 
5424         // "main bin spec" (main binary specification) data payload is
5425         // formatted:
5426         //    uint32_t version       [currently 1]
5427         //    uint32_t type          [0 == unspecified, 1 == kernel, 2 == user
5428         //    process] uint64_t address       [ UINT64_MAX if address not
5429         //    specified ] uuid_t   uuid          [ all zero's if uuid not
5430         //    specified ] uint32_t log2_pagesize [ process page size in log base
5431         //    2, e.g. 4k pages are 12.  0 for unspecified ]
5432 
5433         if (strcmp("main bin spec", data_owner) == 0 && size >= 32) {
5434           offset = fileoff;
5435           uint32_t version;
5436           if (m_data.GetU32(&offset, &version, 1) != nullptr && version == 1) {
5437             uint32_t type = 0;
5438             uuid_t raw_uuid;
5439             memset(raw_uuid, 0, sizeof(uuid_t));
5440 
5441             if (m_data.GetU32(&offset, &type, 1) &&
5442                 m_data.GetU64(&offset, &address, 1) &&
5443                 m_data.CopyData(offset, sizeof(uuid_t), raw_uuid) != 0) {
5444               uuid = UUID::fromOptionalData(raw_uuid, sizeof(uuid_t));
5445               return true;
5446             }
5447           }
5448         }
5449       }
5450       offset = cmd_offset + lc.cmdsize;
5451     }
5452   }
5453   return false;
5454 }
5455 
5456 lldb::RegisterContextSP
5457 ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx,
5458                                          lldb_private::Thread &thread) {
5459   lldb::RegisterContextSP reg_ctx_sp;
5460 
5461   ModuleSP module_sp(GetModule());
5462   if (module_sp) {
5463     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5464     if (!m_thread_context_offsets_valid)
5465       GetNumThreadContexts();
5466 
5467     const FileRangeArray::Entry *thread_context_file_range =
5468         m_thread_context_offsets.GetEntryAtIndex(idx);
5469     if (thread_context_file_range) {
5470 
5471       DataExtractor data(m_data, thread_context_file_range->GetRangeBase(),
5472                          thread_context_file_range->GetByteSize());
5473 
5474       switch (m_header.cputype) {
5475       case llvm::MachO::CPU_TYPE_ARM64:
5476       case llvm::MachO::CPU_TYPE_ARM64_32:
5477         reg_ctx_sp =
5478             std::make_shared<RegisterContextDarwin_arm64_Mach>(thread, data);
5479         break;
5480 
5481       case llvm::MachO::CPU_TYPE_ARM:
5482         reg_ctx_sp =
5483             std::make_shared<RegisterContextDarwin_arm_Mach>(thread, data);
5484         break;
5485 
5486       case llvm::MachO::CPU_TYPE_I386:
5487         reg_ctx_sp =
5488             std::make_shared<RegisterContextDarwin_i386_Mach>(thread, data);
5489         break;
5490 
5491       case llvm::MachO::CPU_TYPE_X86_64:
5492         reg_ctx_sp =
5493             std::make_shared<RegisterContextDarwin_x86_64_Mach>(thread, data);
5494         break;
5495       }
5496     }
5497   }
5498   return reg_ctx_sp;
5499 }
5500 
5501 ObjectFile::Type ObjectFileMachO::CalculateType() {
5502   switch (m_header.filetype) {
5503   case MH_OBJECT: // 0x1u
5504     if (GetAddressByteSize() == 4) {
5505       // 32 bit kexts are just object files, but they do have a valid
5506       // UUID load command.
5507       if (GetUUID()) {
5508         // this checking for the UUID load command is not enough we could
5509         // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5510         // this is required of kexts
5511         if (m_strata == eStrataInvalid)
5512           m_strata = eStrataKernel;
5513         return eTypeSharedLibrary;
5514       }
5515     }
5516     return eTypeObjectFile;
5517 
5518   case MH_EXECUTE:
5519     return eTypeExecutable; // 0x2u
5520   case MH_FVMLIB:
5521     return eTypeSharedLibrary; // 0x3u
5522   case MH_CORE:
5523     return eTypeCoreFile; // 0x4u
5524   case MH_PRELOAD:
5525     return eTypeSharedLibrary; // 0x5u
5526   case MH_DYLIB:
5527     return eTypeSharedLibrary; // 0x6u
5528   case MH_DYLINKER:
5529     return eTypeDynamicLinker; // 0x7u
5530   case MH_BUNDLE:
5531     return eTypeSharedLibrary; // 0x8u
5532   case MH_DYLIB_STUB:
5533     return eTypeStubLibrary; // 0x9u
5534   case MH_DSYM:
5535     return eTypeDebugInfo; // 0xAu
5536   case MH_KEXT_BUNDLE:
5537     return eTypeSharedLibrary; // 0xBu
5538   default:
5539     break;
5540   }
5541   return eTypeUnknown;
5542 }
5543 
5544 ObjectFile::Strata ObjectFileMachO::CalculateStrata() {
5545   switch (m_header.filetype) {
5546   case MH_OBJECT: // 0x1u
5547   {
5548     // 32 bit kexts are just object files, but they do have a valid
5549     // UUID load command.
5550     if (GetUUID()) {
5551       // this checking for the UUID load command is not enough we could
5552       // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
5553       // this is required of kexts
5554       if (m_type == eTypeInvalid)
5555         m_type = eTypeSharedLibrary;
5556 
5557       return eStrataKernel;
5558     }
5559   }
5560     return eStrataUnknown;
5561 
5562   case MH_EXECUTE: // 0x2u
5563     // Check for the MH_DYLDLINK bit in the flags
5564     if (m_header.flags & MH_DYLDLINK) {
5565       return eStrataUser;
5566     } else {
5567       SectionList *section_list = GetSectionList();
5568       if (section_list) {
5569         static ConstString g_kld_section_name("__KLD");
5570         if (section_list->FindSectionByName(g_kld_section_name))
5571           return eStrataKernel;
5572       }
5573     }
5574     return eStrataRawImage;
5575 
5576   case MH_FVMLIB:
5577     return eStrataUser; // 0x3u
5578   case MH_CORE:
5579     return eStrataUnknown; // 0x4u
5580   case MH_PRELOAD:
5581     return eStrataRawImage; // 0x5u
5582   case MH_DYLIB:
5583     return eStrataUser; // 0x6u
5584   case MH_DYLINKER:
5585     return eStrataUser; // 0x7u
5586   case MH_BUNDLE:
5587     return eStrataUser; // 0x8u
5588   case MH_DYLIB_STUB:
5589     return eStrataUser; // 0x9u
5590   case MH_DSYM:
5591     return eStrataUnknown; // 0xAu
5592   case MH_KEXT_BUNDLE:
5593     return eStrataKernel; // 0xBu
5594   default:
5595     break;
5596   }
5597   return eStrataUnknown;
5598 }
5599 
5600 llvm::VersionTuple ObjectFileMachO::GetVersion() {
5601   ModuleSP module_sp(GetModule());
5602   if (module_sp) {
5603     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5604     struct dylib_command load_cmd;
5605     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5606     uint32_t version_cmd = 0;
5607     uint64_t version = 0;
5608     uint32_t i;
5609     for (i = 0; i < m_header.ncmds; ++i) {
5610       const lldb::offset_t cmd_offset = offset;
5611       if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
5612         break;
5613 
5614       if (load_cmd.cmd == LC_ID_DYLIB) {
5615         if (version_cmd == 0) {
5616           version_cmd = load_cmd.cmd;
5617           if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == nullptr)
5618             break;
5619           version = load_cmd.dylib.current_version;
5620         }
5621         break; // Break for now unless there is another more complete version
5622                // number load command in the future.
5623       }
5624       offset = cmd_offset + load_cmd.cmdsize;
5625     }
5626 
5627     if (version_cmd == LC_ID_DYLIB) {
5628       unsigned major = (version & 0xFFFF0000ull) >> 16;
5629       unsigned minor = (version & 0x0000FF00ull) >> 8;
5630       unsigned subminor = (version & 0x000000FFull);
5631       return llvm::VersionTuple(major, minor, subminor);
5632     }
5633   }
5634   return llvm::VersionTuple();
5635 }
5636 
5637 ArchSpec ObjectFileMachO::GetArchitecture() {
5638   ModuleSP module_sp(GetModule());
5639   ArchSpec arch;
5640   if (module_sp) {
5641     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5642 
5643     return GetArchitecture(module_sp, m_header, m_data,
5644                            MachHeaderSizeFromMagic(m_header.magic));
5645   }
5646   return arch;
5647 }
5648 
5649 void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process,
5650                                                 addr_t &base_addr, UUID &uuid) {
5651   uuid.Clear();
5652   base_addr = LLDB_INVALID_ADDRESS;
5653   if (process && process->GetDynamicLoader()) {
5654     DynamicLoader *dl = process->GetDynamicLoader();
5655     LazyBool using_shared_cache;
5656     LazyBool private_shared_cache;
5657     dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache,
5658                                   private_shared_cache);
5659   }
5660   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
5661                                                   LIBLLDB_LOG_PROCESS));
5662   LLDB_LOGF(
5663       log,
5664       "inferior process shared cache has a UUID of %s, base address 0x%" PRIx64,
5665       uuid.GetAsString().c_str(), base_addr);
5666 }
5667 
5668 // From dyld SPI header dyld_process_info.h
5669 typedef void *dyld_process_info;
5670 struct lldb_copy__dyld_process_cache_info {
5671   uuid_t cacheUUID;          // UUID of cache used by process
5672   uint64_t cacheBaseAddress; // load address of dyld shared cache
5673   bool noCache;              // process is running without a dyld cache
5674   bool privateCache; // process is using a private copy of its dyld cache
5675 };
5676 
5677 // #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with
5678 // llvm enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile
5679 // errors. So we need to use the actual underlying types of task_t and
5680 // kern_return_t below.
5681 extern "C" unsigned int /*task_t*/ mach_task_self();
5682 
5683 void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) {
5684   uuid.Clear();
5685   base_addr = LLDB_INVALID_ADDRESS;
5686 
5687 #if defined(__APPLE__) &&                                                      \
5688     (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
5689   uint8_t *(*dyld_get_all_image_infos)(void);
5690   dyld_get_all_image_infos =
5691       (uint8_t * (*)()) dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
5692   if (dyld_get_all_image_infos) {
5693     uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5694     if (dyld_all_image_infos_address) {
5695       uint32_t *version = (uint32_t *)
5696           dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
5697       if (*version >= 13) {
5698         uuid_t *sharedCacheUUID_address = 0;
5699         int wordsize = sizeof(uint8_t *);
5700         if (wordsize == 8) {
5701           sharedCacheUUID_address =
5702               (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5703                          160); // sharedCacheUUID <mach-o/dyld_images.h>
5704           if (*version >= 15)
5705             base_addr =
5706                 *(uint64_t
5707                       *)((uint8_t *)dyld_all_image_infos_address +
5708                          176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5709         } else {
5710           sharedCacheUUID_address =
5711               (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5712                          84); // sharedCacheUUID <mach-o/dyld_images.h>
5713           if (*version >= 15) {
5714             base_addr = 0;
5715             base_addr =
5716                 *(uint32_t
5717                       *)((uint8_t *)dyld_all_image_infos_address +
5718                          100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5719           }
5720         }
5721         uuid = UUID::fromOptionalData(sharedCacheUUID_address, sizeof(uuid_t));
5722       }
5723     }
5724   } else {
5725     // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
5726     dyld_process_info (*dyld_process_info_create)(
5727         unsigned int /* task_t */ task, uint64_t timestamp,
5728         unsigned int /*kern_return_t*/ *kernelError);
5729     void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
5730     void (*dyld_process_info_release)(dyld_process_info info);
5731 
5732     dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t,
5733                                           unsigned int /*kern_return_t*/ *))
5734         dlsym(RTLD_DEFAULT, "_dyld_process_info_create");
5735     dyld_process_info_get_cache = (void (*)(void *, void *))dlsym(
5736         RTLD_DEFAULT, "_dyld_process_info_get_cache");
5737     dyld_process_info_release =
5738         (void (*)(void *))dlsym(RTLD_DEFAULT, "_dyld_process_info_release");
5739 
5740     if (dyld_process_info_create && dyld_process_info_get_cache) {
5741       unsigned int /*kern_return_t */ kern_ret;
5742       dyld_process_info process_info =
5743           dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
5744       if (process_info) {
5745         struct lldb_copy__dyld_process_cache_info sc_info;
5746         memset(&sc_info, 0, sizeof(struct lldb_copy__dyld_process_cache_info));
5747         dyld_process_info_get_cache(process_info, &sc_info);
5748         if (sc_info.cacheBaseAddress != 0) {
5749           base_addr = sc_info.cacheBaseAddress;
5750           uuid = UUID::fromOptionalData(sc_info.cacheUUID, sizeof(uuid_t));
5751         }
5752         dyld_process_info_release(process_info);
5753       }
5754     }
5755   }
5756   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS |
5757                                                   LIBLLDB_LOG_PROCESS));
5758   if (log && uuid.IsValid())
5759     LLDB_LOGF(log,
5760               "lldb's in-memory shared cache has a UUID of %s base address of "
5761               "0x%" PRIx64,
5762               uuid.GetAsString().c_str(), base_addr);
5763 #endif
5764 }
5765 
5766 llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() {
5767   if (!m_min_os_version) {
5768     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5769     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5770       const lldb::offset_t load_cmd_offset = offset;
5771 
5772       version_min_command lc;
5773       if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5774         break;
5775       if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5776           lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5777           lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5778           lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5779         if (m_data.GetU32(&offset, &lc.version,
5780                           (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5781           const uint32_t xxxx = lc.version >> 16;
5782           const uint32_t yy = (lc.version >> 8) & 0xffu;
5783           const uint32_t zz = lc.version & 0xffu;
5784           if (xxxx) {
5785             m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5786             break;
5787           }
5788         }
5789       } else if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5790         // struct build_version_command {
5791         //     uint32_t    cmd;            /* LC_BUILD_VERSION */
5792         //     uint32_t    cmdsize;        /* sizeof(struct
5793         //     build_version_command) plus */
5794         //                                 /* ntools * sizeof(struct
5795         //                                 build_tool_version) */
5796         //     uint32_t    platform;       /* platform */
5797         //     uint32_t    minos;          /* X.Y.Z is encoded in nibbles
5798         //     xxxx.yy.zz */ uint32_t    sdk;            /* X.Y.Z is encoded in
5799         //     nibbles xxxx.yy.zz */ uint32_t    ntools;         /* number of
5800         //     tool entries following this */
5801         // };
5802 
5803         offset += 4; // skip platform
5804         uint32_t minos = m_data.GetU32(&offset);
5805 
5806         const uint32_t xxxx = minos >> 16;
5807         const uint32_t yy = (minos >> 8) & 0xffu;
5808         const uint32_t zz = minos & 0xffu;
5809         if (xxxx) {
5810           m_min_os_version = llvm::VersionTuple(xxxx, yy, zz);
5811           break;
5812         }
5813       }
5814 
5815       offset = load_cmd_offset + lc.cmdsize;
5816     }
5817 
5818     if (!m_min_os_version) {
5819       // Set version to an empty value so we don't keep trying to
5820       m_min_os_version = llvm::VersionTuple();
5821     }
5822   }
5823 
5824   return *m_min_os_version;
5825 }
5826 
5827 llvm::VersionTuple ObjectFileMachO::GetSDKVersion() {
5828   if (!m_sdk_versions.hasValue()) {
5829     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5830     for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5831       const lldb::offset_t load_cmd_offset = offset;
5832 
5833       version_min_command lc;
5834       if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5835         break;
5836       if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5837           lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5838           lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5839           lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5840         if (m_data.GetU32(&offset, &lc.version,
5841                           (sizeof(lc) / sizeof(uint32_t)) - 2)) {
5842           const uint32_t xxxx = lc.sdk >> 16;
5843           const uint32_t yy = (lc.sdk >> 8) & 0xffu;
5844           const uint32_t zz = lc.sdk & 0xffu;
5845           if (xxxx) {
5846             m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz);
5847             break;
5848           } else {
5849             GetModule()->ReportWarning("minimum OS version load command with "
5850                                        "invalid (0) version found.");
5851           }
5852         }
5853       }
5854       offset = load_cmd_offset + lc.cmdsize;
5855     }
5856 
5857     if (!m_sdk_versions.hasValue()) {
5858       offset = MachHeaderSizeFromMagic(m_header.magic);
5859       for (uint32_t i = 0; i < m_header.ncmds; ++i) {
5860         const lldb::offset_t load_cmd_offset = offset;
5861 
5862         version_min_command lc;
5863         if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr)
5864           break;
5865         if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5866           // struct build_version_command {
5867           //     uint32_t    cmd;            /* LC_BUILD_VERSION */
5868           //     uint32_t    cmdsize;        /* sizeof(struct
5869           //     build_version_command) plus */
5870           //                                 /* ntools * sizeof(struct
5871           //                                 build_tool_version) */
5872           //     uint32_t    platform;       /* platform */
5873           //     uint32_t    minos;          /* X.Y.Z is encoded in nibbles
5874           //     xxxx.yy.zz */ uint32_t    sdk;            /* X.Y.Z is encoded
5875           //     in nibbles xxxx.yy.zz */ uint32_t    ntools;         /* number
5876           //     of tool entries following this */
5877           // };
5878 
5879           offset += 4; // skip platform
5880           uint32_t minos = m_data.GetU32(&offset);
5881 
5882           const uint32_t xxxx = minos >> 16;
5883           const uint32_t yy = (minos >> 8) & 0xffu;
5884           const uint32_t zz = minos & 0xffu;
5885           if (xxxx) {
5886             m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz);
5887             break;
5888           }
5889         }
5890         offset = load_cmd_offset + lc.cmdsize;
5891       }
5892     }
5893 
5894     if (!m_sdk_versions.hasValue())
5895       m_sdk_versions = llvm::VersionTuple();
5896   }
5897 
5898   return m_sdk_versions.getValue();
5899 }
5900 
5901 bool ObjectFileMachO::GetIsDynamicLinkEditor() {
5902   return m_header.filetype == llvm::MachO::MH_DYLINKER;
5903 }
5904 
5905 bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() {
5906   return m_allow_assembly_emulation_unwind_plans;
5907 }
5908 
5909 // PluginInterface protocol
5910 lldb_private::ConstString ObjectFileMachO::GetPluginName() {
5911   return GetPluginNameStatic();
5912 }
5913 
5914 uint32_t ObjectFileMachO::GetPluginVersion() { return 1; }
5915 
5916 Section *ObjectFileMachO::GetMachHeaderSection() {
5917   // Find the first address of the mach header which is the first non-zero file
5918   // sized section whose file offset is zero. This is the base file address of
5919   // the mach-o file which can be subtracted from the vmaddr of the other
5920   // segments found in memory and added to the load address
5921   ModuleSP module_sp = GetModule();
5922   if (!module_sp)
5923     return nullptr;
5924   SectionList *section_list = GetSectionList();
5925   if (!section_list)
5926     return nullptr;
5927   const size_t num_sections = section_list->GetSize();
5928   for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5929     Section *section = section_list->GetSectionAtIndex(sect_idx).get();
5930     if (section->GetFileOffset() == 0 && SectionIsLoadable(section))
5931       return section;
5932   }
5933   return nullptr;
5934 }
5935 
5936 bool ObjectFileMachO::SectionIsLoadable(const Section *section) {
5937   if (!section)
5938     return false;
5939   const bool is_dsym = (m_header.filetype == MH_DSYM);
5940   if (section->GetFileSize() == 0 && !is_dsym)
5941     return false;
5942   if (section->IsThreadSpecific())
5943     return false;
5944   if (GetModule().get() != section->GetModule().get())
5945     return false;
5946   // Be careful with __LINKEDIT and __DWARF segments
5947   if (section->GetName() == GetSegmentNameLINKEDIT() ||
5948       section->GetName() == GetSegmentNameDWARF()) {
5949     // Only map __LINKEDIT and __DWARF if we have an in memory image and
5950     // this isn't a kernel binary like a kext or mach_kernel.
5951     const bool is_memory_image = (bool)m_process_wp.lock();
5952     const Strata strata = GetStrata();
5953     if (is_memory_image == false || strata == eStrataKernel)
5954       return false;
5955   }
5956   return true;
5957 }
5958 
5959 lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(
5960     lldb::addr_t header_load_address, const Section *header_section,
5961     const Section *section) {
5962   ModuleSP module_sp = GetModule();
5963   if (module_sp && header_section && section &&
5964       header_load_address != LLDB_INVALID_ADDRESS) {
5965     lldb::addr_t file_addr = header_section->GetFileAddress();
5966     if (file_addr != LLDB_INVALID_ADDRESS && SectionIsLoadable(section))
5967       return section->GetFileAddress() - file_addr + header_load_address;
5968   }
5969   return LLDB_INVALID_ADDRESS;
5970 }
5971 
5972 bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value,
5973                                      bool value_is_offset) {
5974   ModuleSP module_sp = GetModule();
5975   if (!module_sp)
5976     return false;
5977 
5978   SectionList *section_list = GetSectionList();
5979   if (!section_list)
5980     return false;
5981 
5982   size_t num_loaded_sections = 0;
5983   const size_t num_sections = section_list->GetSize();
5984 
5985   if (value_is_offset) {
5986     // "value" is an offset to apply to each top level segment
5987     for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5988       // Iterate through the object file sections to find all of the
5989       // sections that size on disk (to avoid __PAGEZERO) and load them
5990       SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
5991       if (SectionIsLoadable(section_sp.get()))
5992         if (target.GetSectionLoadList().SetSectionLoadAddress(
5993                 section_sp, section_sp->GetFileAddress() + value))
5994           ++num_loaded_sections;
5995     }
5996   } else {
5997     // "value" is the new base address of the mach_header, adjust each
5998     // section accordingly
5999 
6000     Section *mach_header_section = GetMachHeaderSection();
6001     if (mach_header_section) {
6002       for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
6003         SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
6004 
6005         lldb::addr_t section_load_addr =
6006             CalculateSectionLoadAddressForMemoryImage(
6007                 value, mach_header_section, section_sp.get());
6008         if (section_load_addr != LLDB_INVALID_ADDRESS) {
6009           if (target.GetSectionLoadList().SetSectionLoadAddress(
6010                   section_sp, section_load_addr))
6011             ++num_loaded_sections;
6012         }
6013       }
6014     }
6015   }
6016   return num_loaded_sections > 0;
6017 }
6018 
6019 bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp,
6020                                const FileSpec &outfile, Status &error) {
6021   if (!process_sp)
6022     return false;
6023 
6024   Target &target = process_sp->GetTarget();
6025   const ArchSpec target_arch = target.GetArchitecture();
6026   const llvm::Triple &target_triple = target_arch.GetTriple();
6027   if (target_triple.getVendor() == llvm::Triple::Apple &&
6028       (target_triple.getOS() == llvm::Triple::MacOSX ||
6029        target_triple.getOS() == llvm::Triple::IOS ||
6030        target_triple.getOS() == llvm::Triple::WatchOS ||
6031        target_triple.getOS() == llvm::Triple::TvOS)) {
6032     // NEED_BRIDGEOS_TRIPLE target_triple.getOS() == llvm::Triple::BridgeOS))
6033     // {
6034     bool make_core = false;
6035     switch (target_arch.GetMachine()) {
6036     case llvm::Triple::aarch64:
6037     case llvm::Triple::aarch64_32:
6038     case llvm::Triple::arm:
6039     case llvm::Triple::thumb:
6040     case llvm::Triple::x86:
6041     case llvm::Triple::x86_64:
6042       make_core = true;
6043       break;
6044     default:
6045       error.SetErrorStringWithFormat("unsupported core architecture: %s",
6046                                      target_triple.str().c_str());
6047       break;
6048     }
6049 
6050     if (make_core) {
6051       std::vector<segment_command_64> segment_load_commands;
6052       //                uint32_t range_info_idx = 0;
6053       MemoryRegionInfo range_info;
6054       Status range_error = process_sp->GetMemoryRegionInfo(0, range_info);
6055       const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
6056       const ByteOrder byte_order = target_arch.GetByteOrder();
6057       if (range_error.Success()) {
6058         while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) {
6059           const addr_t addr = range_info.GetRange().GetRangeBase();
6060           const addr_t size = range_info.GetRange().GetByteSize();
6061 
6062           if (size == 0)
6063             break;
6064 
6065           // Calculate correct protections
6066           uint32_t prot = 0;
6067           if (range_info.GetReadable() == MemoryRegionInfo::eYes)
6068             prot |= VM_PROT_READ;
6069           if (range_info.GetWritable() == MemoryRegionInfo::eYes)
6070             prot |= VM_PROT_WRITE;
6071           if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
6072             prot |= VM_PROT_EXECUTE;
6073 
6074           if (prot != 0) {
6075             uint32_t cmd_type = LC_SEGMENT_64;
6076             uint32_t segment_size = sizeof(segment_command_64);
6077             if (addr_byte_size == 4) {
6078               cmd_type = LC_SEGMENT;
6079               segment_size = sizeof(segment_command);
6080             }
6081             segment_command_64 segment = {
6082                 cmd_type,     // uint32_t cmd;
6083                 segment_size, // uint32_t cmdsize;
6084                 {0},          // char segname[16];
6085                 addr, // uint64_t vmaddr;    // uint32_t for 32-bit Mach-O
6086                 size, // uint64_t vmsize;    // uint32_t for 32-bit Mach-O
6087                 0,    // uint64_t fileoff;   // uint32_t for 32-bit Mach-O
6088                 size, // uint64_t filesize;  // uint32_t for 32-bit Mach-O
6089                 prot, // uint32_t maxprot;
6090                 prot, // uint32_t initprot;
6091                 0,    // uint32_t nsects;
6092                 0};   // uint32_t flags;
6093             segment_load_commands.push_back(segment);
6094           } else {
6095             // No protections and a size of 1 used to be returned from old
6096             // debugservers when we asked about a region that was past the
6097             // last memory region and it indicates the end...
6098             if (size == 1)
6099               break;
6100           }
6101 
6102           range_error = process_sp->GetMemoryRegionInfo(
6103               range_info.GetRange().GetRangeEnd(), range_info);
6104           if (range_error.Fail())
6105             break;
6106         }
6107 
6108         StreamString buffer(Stream::eBinary, addr_byte_size, byte_order);
6109 
6110         mach_header_64 mach_header;
6111         if (addr_byte_size == 8) {
6112           mach_header.magic = MH_MAGIC_64;
6113         } else {
6114           mach_header.magic = MH_MAGIC;
6115         }
6116         mach_header.cputype = target_arch.GetMachOCPUType();
6117         mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
6118         mach_header.filetype = MH_CORE;
6119         mach_header.ncmds = segment_load_commands.size();
6120         mach_header.flags = 0;
6121         mach_header.reserved = 0;
6122         ThreadList &thread_list = process_sp->GetThreadList();
6123         const uint32_t num_threads = thread_list.GetSize();
6124 
6125         // Make an array of LC_THREAD data items. Each one contains the
6126         // contents of the LC_THREAD load command. The data doesn't contain
6127         // the load command + load command size, we will add the load command
6128         // and load command size as we emit the data.
6129         std::vector<StreamString> LC_THREAD_datas(num_threads);
6130         for (auto &LC_THREAD_data : LC_THREAD_datas) {
6131           LC_THREAD_data.GetFlags().Set(Stream::eBinary);
6132           LC_THREAD_data.SetAddressByteSize(addr_byte_size);
6133           LC_THREAD_data.SetByteOrder(byte_order);
6134         }
6135         for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
6136           ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
6137           if (thread_sp) {
6138             switch (mach_header.cputype) {
6139             case llvm::MachO::CPU_TYPE_ARM64:
6140             case llvm::MachO::CPU_TYPE_ARM64_32:
6141               RegisterContextDarwin_arm64_Mach::Create_LC_THREAD(
6142                   thread_sp.get(), LC_THREAD_datas[thread_idx]);
6143               break;
6144 
6145             case llvm::MachO::CPU_TYPE_ARM:
6146               RegisterContextDarwin_arm_Mach::Create_LC_THREAD(
6147                   thread_sp.get(), LC_THREAD_datas[thread_idx]);
6148               break;
6149 
6150             case llvm::MachO::CPU_TYPE_I386:
6151               RegisterContextDarwin_i386_Mach::Create_LC_THREAD(
6152                   thread_sp.get(), LC_THREAD_datas[thread_idx]);
6153               break;
6154 
6155             case llvm::MachO::CPU_TYPE_X86_64:
6156               RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD(
6157                   thread_sp.get(), LC_THREAD_datas[thread_idx]);
6158               break;
6159             }
6160           }
6161         }
6162 
6163         // The size of the load command is the size of the segments...
6164         if (addr_byte_size == 8) {
6165           mach_header.sizeofcmds =
6166               segment_load_commands.size() * sizeof(struct segment_command_64);
6167         } else {
6168           mach_header.sizeofcmds =
6169               segment_load_commands.size() * sizeof(struct segment_command);
6170         }
6171 
6172         // and the size of all LC_THREAD load command
6173         for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6174           ++mach_header.ncmds;
6175           mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
6176         }
6177 
6178         // Write the mach header
6179         buffer.PutHex32(mach_header.magic);
6180         buffer.PutHex32(mach_header.cputype);
6181         buffer.PutHex32(mach_header.cpusubtype);
6182         buffer.PutHex32(mach_header.filetype);
6183         buffer.PutHex32(mach_header.ncmds);
6184         buffer.PutHex32(mach_header.sizeofcmds);
6185         buffer.PutHex32(mach_header.flags);
6186         if (addr_byte_size == 8) {
6187           buffer.PutHex32(mach_header.reserved);
6188         }
6189 
6190         // Skip the mach header and all load commands and align to the next
6191         // 0x1000 byte boundary
6192         addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
6193         if (file_offset & 0x00000fff) {
6194           file_offset += 0x00001000ull;
6195           file_offset &= (~0x00001000ull + 1);
6196         }
6197 
6198         for (auto &segment : segment_load_commands) {
6199           segment.fileoff = file_offset;
6200           file_offset += segment.filesize;
6201         }
6202 
6203         // Write out all of the LC_THREAD load commands
6204         for (const auto &LC_THREAD_data : LC_THREAD_datas) {
6205           const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
6206           buffer.PutHex32(LC_THREAD);
6207           buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
6208           buffer.Write(LC_THREAD_data.GetString().data(), LC_THREAD_data_size);
6209         }
6210 
6211         // Write out all of the segment load commands
6212         for (const auto &segment : segment_load_commands) {
6213           printf("0x%8.8x 0x%8.8x [0x%16.16" PRIx64 " - 0x%16.16" PRIx64
6214                  ") [0x%16.16" PRIx64 " 0x%16.16" PRIx64
6215                  ") 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x]\n",
6216                  segment.cmd, segment.cmdsize, segment.vmaddr,
6217                  segment.vmaddr + segment.vmsize, segment.fileoff,
6218                  segment.filesize, segment.maxprot, segment.initprot,
6219                  segment.nsects, segment.flags);
6220 
6221           buffer.PutHex32(segment.cmd);
6222           buffer.PutHex32(segment.cmdsize);
6223           buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
6224           if (addr_byte_size == 8) {
6225             buffer.PutHex64(segment.vmaddr);
6226             buffer.PutHex64(segment.vmsize);
6227             buffer.PutHex64(segment.fileoff);
6228             buffer.PutHex64(segment.filesize);
6229           } else {
6230             buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
6231             buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
6232             buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
6233             buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
6234           }
6235           buffer.PutHex32(segment.maxprot);
6236           buffer.PutHex32(segment.initprot);
6237           buffer.PutHex32(segment.nsects);
6238           buffer.PutHex32(segment.flags);
6239         }
6240 
6241         std::string core_file_path(outfile.GetPath());
6242         auto core_file = FileSystem::Instance().Open(
6243             outfile, File::eOpenOptionWrite | File::eOpenOptionTruncate |
6244                          File::eOpenOptionCanCreate);
6245         if (!core_file) {
6246           error = core_file.takeError();
6247         } else {
6248           // Read 1 page at a time
6249           uint8_t bytes[0x1000];
6250           // Write the mach header and load commands out to the core file
6251           size_t bytes_written = buffer.GetString().size();
6252           error =
6253               core_file.get()->Write(buffer.GetString().data(), bytes_written);
6254           if (error.Success()) {
6255             // Now write the file data for all memory segments in the process
6256             for (const auto &segment : segment_load_commands) {
6257               if (core_file.get()->SeekFromStart(segment.fileoff) == -1) {
6258                 error.SetErrorStringWithFormat(
6259                     "unable to seek to offset 0x%" PRIx64 " in '%s'",
6260                     segment.fileoff, core_file_path.c_str());
6261                 break;
6262               }
6263 
6264               printf("Saving %" PRId64
6265                      " bytes of data for memory region at 0x%" PRIx64 "\n",
6266                      segment.vmsize, segment.vmaddr);
6267               addr_t bytes_left = segment.vmsize;
6268               addr_t addr = segment.vmaddr;
6269               Status memory_read_error;
6270               while (bytes_left > 0 && error.Success()) {
6271                 const size_t bytes_to_read =
6272                     bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
6273 
6274                 // In a savecore setting, we don't really care about caching,
6275                 // as the data is dumped and very likely never read again,
6276                 // so we call ReadMemoryFromInferior to bypass it.
6277                 const size_t bytes_read = process_sp->ReadMemoryFromInferior(
6278                     addr, bytes, bytes_to_read, memory_read_error);
6279 
6280                 if (bytes_read == bytes_to_read) {
6281                   size_t bytes_written = bytes_read;
6282                   error = core_file.get()->Write(bytes, bytes_written);
6283                   bytes_left -= bytes_read;
6284                   addr += bytes_read;
6285                 } else {
6286                   // Some pages within regions are not readable, those should
6287                   // be zero filled
6288                   memset(bytes, 0, bytes_to_read);
6289                   size_t bytes_written = bytes_to_read;
6290                   error = core_file.get()->Write(bytes, bytes_written);
6291                   bytes_left -= bytes_to_read;
6292                   addr += bytes_to_read;
6293                 }
6294               }
6295             }
6296           }
6297         }
6298       } else {
6299         error.SetErrorString(
6300             "process doesn't support getting memory region info");
6301       }
6302     }
6303     return true; // This is the right plug to handle saving core files for
6304                  // this process
6305   }
6306   return false;
6307 }
6308