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