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