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