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