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