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