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