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->GetAddressRef().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                 addr_t linkedit_load_addr = linkedit_section_sp->GetLoadBaseAddress(&target);
2287                 if (linkedit_load_addr == LLDB_INVALID_ADDRESS)
2288                 {
2289                     // We might be trying to access the symbol table before the __LINKEDIT's load
2290                     // address has been set in the target. We can't fail to read the symbol table,
2291                     // so calculate the right address manually
2292                     linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2293                 }
2294 
2295                 const addr_t linkedit_file_offset = linkedit_section_sp->GetFileOffset();
2296                 const addr_t symoff_addr = linkedit_load_addr + symtab_load_command.symoff - linkedit_file_offset;
2297                 strtab_addr = linkedit_load_addr + symtab_load_command.stroff - linkedit_file_offset;
2298 
2299                 bool data_was_read = false;
2300 
2301 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
2302                 if (m_header.flags & 0x80000000u && process->GetAddressByteSize() == sizeof (void*))
2303                 {
2304                     // This mach-o memory file is in the dyld shared cache. If this
2305                     // program is not remote and this is iOS, then this process will
2306                     // share the same shared cache as the process we are debugging and
2307                     // we can read the entire __LINKEDIT from the address space in this
2308                     // process. This is a needed optimization that is used for local iOS
2309                     // debugging only since all shared libraries in the shared cache do
2310                     // not have corresponding files that exist in the file system of the
2311                     // device. They have been combined into a single file. This means we
2312                     // always have to load these files from memory. All of the symbol and
2313                     // string tables from all of the __LINKEDIT sections from the shared
2314                     // libraries in the shared cache have been merged into a single large
2315                     // symbol and string table. Reading all of this symbol and string table
2316                     // data across can slow down debug launch times, so we optimize this by
2317                     // reading the memory for the __LINKEDIT section from this process.
2318 
2319                     UUID lldb_shared_cache(GetLLDBSharedCacheUUID());
2320                     UUID process_shared_cache(GetProcessSharedCacheUUID(process));
2321                     bool use_lldb_cache = true;
2322                     if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() && lldb_shared_cache != process_shared_cache)
2323                     {
2324                             use_lldb_cache = false;
2325                             ModuleSP module_sp (GetModule());
2326                             if (module_sp)
2327                                 module_sp->ReportWarning ("shared cache in process does not match lldb's own shared cache, startup will be slow.");
2328 
2329                     }
2330 
2331                     PlatformSP platform_sp (target.GetPlatform());
2332                     if (platform_sp && platform_sp->IsHost() && use_lldb_cache)
2333                     {
2334                         data_was_read = true;
2335                         nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size, eByteOrderLittle);
2336                         strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size, eByteOrderLittle);
2337                         if (function_starts_load_command.cmd)
2338                         {
2339                             const addr_t func_start_addr = linkedit_load_addr + function_starts_load_command.dataoff - linkedit_file_offset;
2340                             function_starts_data.SetData ((void *)func_start_addr, function_starts_load_command.datasize, eByteOrderLittle);
2341                         }
2342                     }
2343                 }
2344 #endif
2345 
2346                 if (!data_was_read)
2347                 {
2348                     if (memory_module_load_level == eMemoryModuleLoadLevelComplete)
2349                     {
2350                         DataBufferSP nlist_data_sp (ReadMemory (process_sp, symoff_addr, nlist_data_byte_size));
2351                         if (nlist_data_sp)
2352                             nlist_data.SetData (nlist_data_sp, 0, nlist_data_sp->GetByteSize());
2353                         // Load strings individually from memory when loading from memory since shared cache
2354                         // string tables contain strings for all symbols from all shared cached libraries
2355                         //DataBufferSP strtab_data_sp (ReadMemory (process_sp, strtab_addr, strtab_data_byte_size));
2356                         //if (strtab_data_sp)
2357                         //    strtab_data.SetData (strtab_data_sp, 0, strtab_data_sp->GetByteSize());
2358                         if (m_dysymtab.nindirectsyms != 0)
2359                         {
2360                             const addr_t indirect_syms_addr = linkedit_load_addr + m_dysymtab.indirectsymoff - linkedit_file_offset;
2361                             DataBufferSP indirect_syms_data_sp (ReadMemory (process_sp, indirect_syms_addr, m_dysymtab.nindirectsyms * 4));
2362                             if (indirect_syms_data_sp)
2363                                 indirect_symbol_index_data.SetData (indirect_syms_data_sp, 0, indirect_syms_data_sp->GetByteSize());
2364                         }
2365                     }
2366 
2367                     if (memory_module_load_level >= eMemoryModuleLoadLevelPartial)
2368                     {
2369                         if (function_starts_load_command.cmd)
2370                         {
2371                             const addr_t func_start_addr = linkedit_load_addr + function_starts_load_command.dataoff - linkedit_file_offset;
2372                             DataBufferSP func_start_data_sp (ReadMemory (process_sp, func_start_addr, function_starts_load_command.datasize));
2373                             if (func_start_data_sp)
2374                                 function_starts_data.SetData (func_start_data_sp, 0, func_start_data_sp->GetByteSize());
2375                         }
2376                     }
2377                 }
2378             }
2379         }
2380         else
2381         {
2382             nlist_data.SetData (m_data,
2383                                 symtab_load_command.symoff,
2384                                 nlist_data_byte_size);
2385             strtab_data.SetData (m_data,
2386                                  symtab_load_command.stroff,
2387                                  strtab_data_byte_size);
2388 
2389             if (dyld_info.export_size > 0)
2390             {
2391                 dyld_trie_data.SetData (m_data,
2392                                         dyld_info.export_off,
2393                                         dyld_info.export_size);
2394             }
2395 
2396             if (m_dysymtab.nindirectsyms != 0)
2397             {
2398                 indirect_symbol_index_data.SetData (m_data,
2399                                                     m_dysymtab.indirectsymoff,
2400                                                     m_dysymtab.nindirectsyms * 4);
2401             }
2402             if (function_starts_load_command.cmd)
2403             {
2404                 function_starts_data.SetData (m_data,
2405                                               function_starts_load_command.dataoff,
2406                                               function_starts_load_command.datasize);
2407             }
2408         }
2409 
2410         if (nlist_data.GetByteSize() == 0 && memory_module_load_level == eMemoryModuleLoadLevelComplete)
2411         {
2412             if (log)
2413                 module_sp->LogMessage(log, "failed to read nlist data");
2414             return 0;
2415         }
2416 
2417 
2418         const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2419         if (!have_strtab_data)
2420         {
2421             if (process)
2422             {
2423                 if (strtab_addr == LLDB_INVALID_ADDRESS)
2424                 {
2425                     if (log)
2426                         module_sp->LogMessage(log, "failed to locate the strtab in memory");
2427                     return 0;
2428                 }
2429             }
2430             else
2431             {
2432                 if (log)
2433                     module_sp->LogMessage(log, "failed to read strtab data");
2434                 return 0;
2435             }
2436         }
2437 
2438         const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT();
2439         const ConstString &g_segment_name_DATA = GetSegmentNameDATA();
2440         const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC();
2441         const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame();
2442         SectionSP text_section_sp(section_list->FindSectionByName(g_segment_name_TEXT));
2443         SectionSP data_section_sp(section_list->FindSectionByName(g_segment_name_DATA));
2444         SectionSP objc_section_sp(section_list->FindSectionByName(g_segment_name_OBJC));
2445         SectionSP eh_frame_section_sp;
2446         if (text_section_sp.get())
2447             eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName (g_section_name_eh_frame);
2448         else
2449             eh_frame_section_sp = section_list->FindSectionByName (g_section_name_eh_frame);
2450 
2451         const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
2452 
2453         // lldb works best if it knows the start address of all functions in a module.
2454         // Linker symbols or debug info are normally the best source of information for start addr / size but
2455         // they may be stripped in a released binary.
2456         // Two additional sources of information exist in Mach-O binaries:
2457         //    LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each function's start address in the
2458         //                         binary, relative to the text section.
2459         //    eh_frame           - the eh_frame FDEs have the start addr & size of each function
2460         //  LC_FUNCTION_STARTS is the fastest source to read in, and is present on all modern binaries.
2461         //  Binaries built to run on older releases may need to use eh_frame information.
2462 
2463         if (text_section_sp && function_starts_data.GetByteSize())
2464         {
2465             FunctionStarts::Entry function_start_entry;
2466             function_start_entry.data = false;
2467             lldb::offset_t function_start_offset = 0;
2468             function_start_entry.addr = text_section_sp->GetFileAddress();
2469             uint64_t delta;
2470             while ((delta = function_starts_data.GetULEB128(&function_start_offset)) > 0)
2471             {
2472                 // Now append the current entry
2473                 function_start_entry.addr += delta;
2474                 function_starts.Append(function_start_entry);
2475             }
2476         }
2477         else
2478         {
2479             // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the load command claiming an eh_frame
2480             // but it doesn't actually have the eh_frame content.  And if we have a dSYM, we don't need to do any
2481             // of this fill-in-the-missing-symbols works anyway - the debug info should give us all the functions in
2482             // the module.
2483             if (text_section_sp.get() && eh_frame_section_sp.get() && m_type != eTypeDebugInfo)
2484             {
2485                 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp, eRegisterKindGCC, true);
2486                 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2487                 eh_frame.GetFunctionAddressAndSizeVector (functions);
2488                 addr_t text_base_addr = text_section_sp->GetFileAddress();
2489                 size_t count = functions.GetSize();
2490                 for (size_t i = 0; i < count; ++i)
2491                 {
2492                     const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func = functions.GetEntryAtIndex (i);
2493                     if (func)
2494                     {
2495                         FunctionStarts::Entry function_start_entry;
2496                         function_start_entry.addr = func->base - text_base_addr;
2497                         function_starts.Append(function_start_entry);
2498                     }
2499                 }
2500             }
2501         }
2502 
2503         const size_t function_starts_count = function_starts.GetSize();
2504 
2505         const user_id_t TEXT_eh_frame_sectID =
2506             eh_frame_section_sp.get() ? eh_frame_section_sp->GetID()
2507                                       : static_cast<user_id_t>(NO_SECT);
2508 
2509         lldb::offset_t nlist_data_offset = 0;
2510 
2511         uint32_t N_SO_index = UINT32_MAX;
2512 
2513         MachSymtabSectionInfo section_info (section_list);
2514         std::vector<uint32_t> N_FUN_indexes;
2515         std::vector<uint32_t> N_NSYM_indexes;
2516         std::vector<uint32_t> N_INCL_indexes;
2517         std::vector<uint32_t> N_BRAC_indexes;
2518         std::vector<uint32_t> N_COMM_indexes;
2519         typedef std::multimap <uint64_t, uint32_t> ValueToSymbolIndexMap;
2520         typedef std::map <uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2521         typedef std::map <const char *, uint32_t> ConstNameToSymbolIndexMap;
2522         ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2523         ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2524         ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
2525         // Any symbols that get merged into another will get an entry
2526         // in this map so we know
2527         NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2528         uint32_t nlist_idx = 0;
2529         Symbol *symbol_ptr = NULL;
2530 
2531         uint32_t sym_idx = 0;
2532         Symbol *sym = NULL;
2533         size_t num_syms = 0;
2534         std::string memory_symbol_name;
2535         uint32_t unmapped_local_symbols_found = 0;
2536 
2537         std::vector<TrieEntryWithOffset> trie_entries;
2538         std::set<lldb::addr_t> resolver_addresses;
2539 
2540         if (dyld_trie_data.GetByteSize() > 0)
2541         {
2542             std::vector<llvm::StringRef> nameSlices;
2543             ParseTrieEntries (dyld_trie_data,
2544                               0,
2545                               nameSlices,
2546                               resolver_addresses,
2547                               trie_entries);
2548 
2549             ConstString text_segment_name ("__TEXT");
2550             SectionSP text_segment_sp = GetSectionList()->FindSectionByName(text_segment_name);
2551             if (text_segment_sp)
2552             {
2553                 const lldb::addr_t text_segment_file_addr = text_segment_sp->GetFileAddress();
2554                 if (text_segment_file_addr != LLDB_INVALID_ADDRESS)
2555                 {
2556                     for (auto &e : trie_entries)
2557                         e.entry.address += text_segment_file_addr;
2558                 }
2559             }
2560         }
2561 
2562         typedef std::set<ConstString> IndirectSymbols;
2563         IndirectSymbols indirect_symbol_names;
2564 
2565 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
2566 
2567         // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been optimized by moving LOCAL
2568         // symbols out of the memory mapped portion of the DSC. The symbol information has all been retained,
2569         // but it isn't available in the normal nlist data. However, there *are* duplicate entries of *some*
2570         // LOCAL symbols in the normal nlist data. To handle this situation correctly, we must first attempt
2571         // to parse any DSC unmapped symbol information. If we find any, we set a flag that tells the normal
2572         // nlist parser to ignore all LOCAL symbols.
2573 
2574         if (m_header.flags & 0x80000000u)
2575         {
2576             // Before we can start mapping the DSC, we need to make certain the target process is actually
2577             // using the cache we can find.
2578 
2579             // Next we need to determine the correct path for the dyld shared cache.
2580 
2581             ArchSpec header_arch;
2582             GetArchitecture(header_arch);
2583             char dsc_path[PATH_MAX];
2584 
2585             snprintf(dsc_path, sizeof(dsc_path), "%s%s%s",
2586                      "/System/Library/Caches/com.apple.dyld/",  /* IPHONE_DYLD_SHARED_CACHE_DIR */
2587                      "dyld_shared_cache_",          /* DYLD_SHARED_CACHE_BASE_NAME */
2588                      header_arch.GetArchitectureName());
2589 
2590             FileSpec dsc_filespec(dsc_path, false);
2591 
2592             // We need definitions of two structures in the on-disk DSC, copy them here manually
2593             struct lldb_copy_dyld_cache_header_v0
2594             {
2595                 char        magic[16];            // e.g. "dyld_v0    i386", "dyld_v1   armv7", etc.
2596                 uint32_t    mappingOffset;        // file offset to first dyld_cache_mapping_info
2597                 uint32_t    mappingCount;         // number of dyld_cache_mapping_info entries
2598                 uint32_t    imagesOffset;
2599                 uint32_t    imagesCount;
2600                 uint64_t    dyldBaseAddress;
2601                 uint64_t    codeSignatureOffset;
2602                 uint64_t    codeSignatureSize;
2603                 uint64_t    slideInfoOffset;
2604                 uint64_t    slideInfoSize;
2605                 uint64_t    localSymbolsOffset;   // file offset of where local symbols are stored
2606                 uint64_t    localSymbolsSize;     // size of local symbols information
2607             };
2608             struct lldb_copy_dyld_cache_header_v1
2609             {
2610                 char        magic[16];            // e.g. "dyld_v0    i386", "dyld_v1   armv7", etc.
2611                 uint32_t    mappingOffset;        // file offset to first dyld_cache_mapping_info
2612                 uint32_t    mappingCount;         // number of dyld_cache_mapping_info entries
2613                 uint32_t    imagesOffset;
2614                 uint32_t    imagesCount;
2615                 uint64_t    dyldBaseAddress;
2616                 uint64_t    codeSignatureOffset;
2617                 uint64_t    codeSignatureSize;
2618                 uint64_t    slideInfoOffset;
2619                 uint64_t    slideInfoSize;
2620                 uint64_t    localSymbolsOffset;
2621                 uint64_t    localSymbolsSize;
2622                 uint8_t     uuid[16];             // v1 and above, also recorded in dyld_all_image_infos v13 and later
2623             };
2624 
2625             struct lldb_copy_dyld_cache_mapping_info
2626             {
2627                 uint64_t        address;
2628                 uint64_t        size;
2629                 uint64_t        fileOffset;
2630                 uint32_t        maxProt;
2631                 uint32_t        initProt;
2632             };
2633 
2634             struct lldb_copy_dyld_cache_local_symbols_info
2635             {
2636                 uint32_t        nlistOffset;
2637                 uint32_t        nlistCount;
2638                 uint32_t        stringsOffset;
2639                 uint32_t        stringsSize;
2640                 uint32_t        entriesOffset;
2641                 uint32_t        entriesCount;
2642             };
2643             struct lldb_copy_dyld_cache_local_symbols_entry
2644             {
2645                 uint32_t        dylibOffset;
2646                 uint32_t        nlistStartIndex;
2647                 uint32_t        nlistCount;
2648             };
2649 
2650             /* The dyld_cache_header has a pointer to the dyld_cache_local_symbols_info structure (localSymbolsOffset).
2651                The dyld_cache_local_symbols_info structure gives us three things:
2652                  1. The start and count of the nlist records in the dyld_shared_cache file
2653                  2. The start and size of the strings for these nlist records
2654                  3. The start and count of dyld_cache_local_symbols_entry entries
2655 
2656                There is one dyld_cache_local_symbols_entry per dylib/framework in the dyld shared cache.
2657                The "dylibOffset" field is the Mach-O header of this dylib/framework in the dyld shared cache.
2658                The dyld_cache_local_symbols_entry also lists the start of this dylib/framework's nlist records
2659                and the count of how many nlist records there are for this dylib/framework.
2660             */
2661 
2662             // Process the dsc header to find the unmapped symbols
2663             //
2664             // Save some VM space, do not map the entire cache in one shot.
2665 
2666             DataBufferSP dsc_data_sp;
2667             dsc_data_sp = dsc_filespec.MemoryMapFileContentsIfLocal(0, sizeof(struct lldb_copy_dyld_cache_header_v1));
2668 
2669             if (dsc_data_sp)
2670             {
2671                 DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2672 
2673                 char version_str[17];
2674                 int version = -1;
2675                 lldb::offset_t offset = 0;
2676                 memcpy (version_str, dsc_header_data.GetData (&offset, 16), 16);
2677                 version_str[16] = '\0';
2678                 if (strncmp (version_str, "dyld_v", 6) == 0 && isdigit (version_str[6]))
2679                 {
2680                     int v;
2681                     if (::sscanf (version_str + 6, "%d", &v) == 1)
2682                     {
2683                         version = v;
2684                     }
2685                 }
2686 
2687                 UUID dsc_uuid;
2688                 if (version >= 1)
2689                 {
2690                     offset = offsetof (struct lldb_copy_dyld_cache_header_v1, uuid);
2691                     uint8_t uuid_bytes[sizeof (uuid_t)];
2692                     memcpy (uuid_bytes, dsc_header_data.GetData (&offset, sizeof (uuid_t)), sizeof (uuid_t));
2693                     dsc_uuid.SetBytes (uuid_bytes);
2694                 }
2695 
2696                 bool uuid_match = true;
2697                 if (dsc_uuid.IsValid() && process)
2698                 {
2699                     UUID shared_cache_uuid(GetProcessSharedCacheUUID(process));
2700 
2701                     if (shared_cache_uuid.IsValid() && dsc_uuid != shared_cache_uuid)
2702                     {
2703                         // The on-disk dyld_shared_cache file is not the same as the one in this
2704                         // process' memory, don't use it.
2705                         uuid_match = false;
2706                         ModuleSP module_sp (GetModule());
2707                         if (module_sp)
2708                             module_sp->ReportWarning ("process shared cache does not match on-disk dyld_shared_cache file, some symbol names will be missing.");
2709                     }
2710                 }
2711 
2712                 offset = offsetof (struct lldb_copy_dyld_cache_header_v1, mappingOffset);
2713 
2714                 uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
2715 
2716                 // If the mappingOffset points to a location inside the header, we've
2717                 // opened an old dyld shared cache, and should not proceed further.
2718                 if (uuid_match && mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v0))
2719                 {
2720 
2721                     DataBufferSP dsc_mapping_info_data_sp = dsc_filespec.MemoryMapFileContentsIfLocal(mappingOffset, sizeof (struct lldb_copy_dyld_cache_mapping_info));
2722                     DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp, byte_order, addr_byte_size);
2723                     offset = 0;
2724 
2725                     // The File addresses (from the in-memory Mach-O load commands) for the shared libraries
2726                     // in the shared library cache need to be adjusted by an offset to match up with the
2727                     // dylibOffset identifying field in the dyld_cache_local_symbol_entry's.  This offset is
2728                     // recorded in mapping_offset_value.
2729                     const uint64_t mapping_offset_value = dsc_mapping_info_data.GetU64(&offset);
2730 
2731                     offset = offsetof (struct lldb_copy_dyld_cache_header_v1, localSymbolsOffset);
2732                     uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2733                     uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
2734 
2735                     if (localSymbolsOffset && localSymbolsSize)
2736                     {
2737                         // Map the local symbols
2738                         if (DataBufferSP dsc_local_symbols_data_sp = dsc_filespec.MemoryMapFileContentsIfLocal(localSymbolsOffset, localSymbolsSize))
2739                         {
2740                             DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp, byte_order, addr_byte_size);
2741 
2742                             offset = 0;
2743 
2744                             typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
2745                             typedef std::map<uint32_t, ConstString> SymbolIndexToName;
2746                             UndefinedNameToDescMap undefined_name_to_desc;
2747                             SymbolIndexToName reexport_shlib_needs_fixup;
2748 
2749 
2750                             // Read the local_symbols_infos struct in one shot
2751                             struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
2752                             dsc_local_symbols_data.GetU32(&offset, &local_symbols_info.nlistOffset, 6);
2753 
2754                             SectionSP text_section_sp(section_list->FindSectionByName(GetSegmentNameTEXT()));
2755 
2756                             uint32_t header_file_offset = (text_section_sp->GetFileAddress() - mapping_offset_value);
2757 
2758                             offset = local_symbols_info.entriesOffset;
2759                             for (uint32_t entry_index = 0; entry_index < local_symbols_info.entriesCount; entry_index++)
2760                             {
2761                                 struct lldb_copy_dyld_cache_local_symbols_entry local_symbols_entry;
2762                                 local_symbols_entry.dylibOffset = dsc_local_symbols_data.GetU32(&offset);
2763                                 local_symbols_entry.nlistStartIndex = dsc_local_symbols_data.GetU32(&offset);
2764                                 local_symbols_entry.nlistCount = dsc_local_symbols_data.GetU32(&offset);
2765 
2766                                 if (header_file_offset == local_symbols_entry.dylibOffset)
2767                                 {
2768                                     unmapped_local_symbols_found = local_symbols_entry.nlistCount;
2769 
2770                                     // The normal nlist code cannot correctly size the Symbols array, we need to allocate it here.
2771                                     sym = symtab->Resize (symtab_load_command.nsyms + m_dysymtab.nindirectsyms + unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2772                                     num_syms = symtab->GetNumSymbols();
2773 
2774                                     nlist_data_offset = local_symbols_info.nlistOffset + (nlist_byte_size * local_symbols_entry.nlistStartIndex);
2775                                     uint32_t string_table_offset = local_symbols_info.stringsOffset;
2776 
2777                                     for (uint32_t nlist_index = 0; nlist_index < local_symbols_entry.nlistCount; nlist_index++)
2778                                     {
2779                                         /////////////////////////////
2780                                         {
2781                                             struct nlist_64 nlist;
2782                                             if (!dsc_local_symbols_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size))
2783                                                 break;
2784 
2785                                             nlist.n_strx  = dsc_local_symbols_data.GetU32_unchecked(&nlist_data_offset);
2786                                             nlist.n_type  = dsc_local_symbols_data.GetU8_unchecked (&nlist_data_offset);
2787                                             nlist.n_sect  = dsc_local_symbols_data.GetU8_unchecked (&nlist_data_offset);
2788                                             nlist.n_desc  = dsc_local_symbols_data.GetU16_unchecked (&nlist_data_offset);
2789                                             nlist.n_value = dsc_local_symbols_data.GetAddress_unchecked (&nlist_data_offset);
2790 
2791                                             SymbolType type = eSymbolTypeInvalid;
2792                                             const char *symbol_name = dsc_local_symbols_data.PeekCStr(string_table_offset + nlist.n_strx);
2793 
2794                                             if (symbol_name == NULL)
2795                                             {
2796                                                 // No symbol should be NULL, even the symbols with no
2797                                                 // string values should have an offset zero which points
2798                                                 // to an empty C-string
2799                                                 Host::SystemLog (Host::eSystemLogError,
2800                                                                  "error: DSC unmapped local symbol[%u] has invalid string table offset 0x%x in %s, ignoring symbol\n",
2801                                                                  entry_index,
2802                                                                  nlist.n_strx,
2803                                                                  module_sp->GetFileSpec().GetPath().c_str());
2804                                                 continue;
2805                                             }
2806                                             if (symbol_name[0] == '\0')
2807                                                 symbol_name = NULL;
2808 
2809                                             const char *symbol_name_non_abi_mangled = NULL;
2810 
2811                                             SectionSP symbol_section;
2812                                             uint32_t symbol_byte_size = 0;
2813                                             bool add_nlist = true;
2814                                             bool is_debug = ((nlist.n_type & N_STAB) != 0);
2815                                             bool demangled_is_synthesized = false;
2816                                             bool is_gsym = false;
2817                                             bool set_value = true;
2818 
2819                                             assert (sym_idx < num_syms);
2820 
2821                                             sym[sym_idx].SetDebug (is_debug);
2822 
2823                                             if (is_debug)
2824                                             {
2825                                                 switch (nlist.n_type)
2826                                                 {
2827                                                     case N_GSYM:
2828                                                         // global symbol: name,,NO_SECT,type,0
2829                                                         // Sometimes the N_GSYM value contains the address.
2830 
2831                                                         // FIXME: In the .o files, we have a GSYM and a debug symbol for all the ObjC data.  They
2832                                                         // have the same address, but we want to ensure that we always find only the real symbol,
2833                                                         // 'cause we don't currently correctly attribute the GSYM one to the ObjCClass/Ivar/MetaClass
2834                                                         // symbol type.  This is a temporary hack to make sure the ObjectiveC symbols get treated
2835                                                         // correctly.  To do this right, we should coalesce all the GSYM & global symbols that have the
2836                                                         // same address.
2837 
2838                                                         is_gsym = true;
2839                                                         sym[sym_idx].SetExternal(true);
2840 
2841                                                         if (symbol_name && symbol_name[0] == '_' && symbol_name[1] ==  'O')
2842                                                         {
2843                                                             llvm::StringRef symbol_name_ref(symbol_name);
2844                                                             if (symbol_name_ref.startswith(g_objc_v2_prefix_class))
2845                                                             {
2846                                                                 symbol_name_non_abi_mangled = symbol_name + 1;
2847                                                                 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
2848                                                                 type = eSymbolTypeObjCClass;
2849                                                                 demangled_is_synthesized = true;
2850 
2851                                                             }
2852                                                             else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass))
2853                                                             {
2854                                                                 symbol_name_non_abi_mangled = symbol_name + 1;
2855                                                                 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
2856                                                                 type = eSymbolTypeObjCMetaClass;
2857                                                                 demangled_is_synthesized = true;
2858                                                             }
2859                                                             else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar))
2860                                                             {
2861                                                                 symbol_name_non_abi_mangled = symbol_name + 1;
2862                                                                 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
2863                                                                 type = eSymbolTypeObjCIVar;
2864                                                                 demangled_is_synthesized = true;
2865                                                             }
2866                                                         }
2867                                                         else
2868                                                         {
2869                                                             if (nlist.n_value != 0)
2870                                                                 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2871                                                             type = eSymbolTypeData;
2872                                                         }
2873                                                         break;
2874 
2875                                                     case N_FNAME:
2876                                                         // procedure name (f77 kludge): name,,NO_SECT,0,0
2877                                                         type = eSymbolTypeCompiler;
2878                                                         break;
2879 
2880                                                     case N_FUN:
2881                                                         // procedure: name,,n_sect,linenumber,address
2882                                                         if (symbol_name)
2883                                                         {
2884                                                             type = eSymbolTypeCode;
2885                                                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2886 
2887                                                             N_FUN_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx));
2888                                                             // We use the current number of symbols in the symbol table in lieu of
2889                                                             // using nlist_idx in case we ever start trimming entries out
2890                                                             N_FUN_indexes.push_back(sym_idx);
2891                                                         }
2892                                                         else
2893                                                         {
2894                                                             type = eSymbolTypeCompiler;
2895 
2896                                                             if ( !N_FUN_indexes.empty() )
2897                                                             {
2898                                                                 // Copy the size of the function into the original STAB entry so we don't have
2899                                                                 // to hunt for it later
2900                                                                 symtab->SymbolAtIndex(N_FUN_indexes.back())->SetByteSize(nlist.n_value);
2901                                                                 N_FUN_indexes.pop_back();
2902                                                                 // We don't really need the end function STAB as it contains the size which
2903                                                                 // we already placed with the original symbol, so don't add it if we want a
2904                                                                 // minimal symbol table
2905                                                                 add_nlist = false;
2906                                                             }
2907                                                         }
2908                                                         break;
2909 
2910                                                     case N_STSYM:
2911                                                         // static symbol: name,,n_sect,type,address
2912                                                         N_STSYM_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx));
2913                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2914                                                         type = eSymbolTypeData;
2915                                                         break;
2916 
2917                                                     case N_LCSYM:
2918                                                         // .lcomm symbol: name,,n_sect,type,address
2919                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2920                                                         type = eSymbolTypeCommonBlock;
2921                                                         break;
2922 
2923                                                     case N_BNSYM:
2924                                                         // We use the current number of symbols in the symbol table in lieu of
2925                                                         // using nlist_idx in case we ever start trimming entries out
2926                                                         // Skip these if we want minimal symbol tables
2927                                                         add_nlist = false;
2928                                                         break;
2929 
2930                                                     case N_ENSYM:
2931                                                         // Set the size of the N_BNSYM to the terminating index of this N_ENSYM
2932                                                         // so that we can always skip the entire symbol if we need to navigate
2933                                                         // more quickly at the source level when parsing STABS
2934                                                         // Skip these if we want minimal symbol tables
2935                                                         add_nlist = false;
2936                                                         break;
2937 
2938 
2939                                                     case N_OPT:
2940                                                         // emitted with gcc2_compiled and in gcc source
2941                                                         type = eSymbolTypeCompiler;
2942                                                         break;
2943 
2944                                                     case N_RSYM:
2945                                                         // register sym: name,,NO_SECT,type,register
2946                                                         type = eSymbolTypeVariable;
2947                                                         break;
2948 
2949                                                     case N_SLINE:
2950                                                         // src line: 0,,n_sect,linenumber,address
2951                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2952                                                         type = eSymbolTypeLineEntry;
2953                                                         break;
2954 
2955                                                     case N_SSYM:
2956                                                         // structure elt: name,,NO_SECT,type,struct_offset
2957                                                         type = eSymbolTypeVariableType;
2958                                                         break;
2959 
2960                                                     case N_SO:
2961                                                         // source file name
2962                                                         type = eSymbolTypeSourceFile;
2963                                                         if (symbol_name == NULL)
2964                                                         {
2965                                                             add_nlist = false;
2966                                                             if (N_SO_index != UINT32_MAX)
2967                                                             {
2968                                                                 // Set the size of the N_SO to the terminating index of this N_SO
2969                                                                 // so that we can always skip the entire N_SO if we need to navigate
2970                                                                 // more quickly at the source level when parsing STABS
2971                                                                 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
2972                                                                 symbol_ptr->SetByteSize(sym_idx);
2973                                                                 symbol_ptr->SetSizeIsSibling(true);
2974                                                             }
2975                                                             N_NSYM_indexes.clear();
2976                                                             N_INCL_indexes.clear();
2977                                                             N_BRAC_indexes.clear();
2978                                                             N_COMM_indexes.clear();
2979                                                             N_FUN_indexes.clear();
2980                                                             N_SO_index = UINT32_MAX;
2981                                                         }
2982                                                         else
2983                                                         {
2984                                                             // We use the current number of symbols in the symbol table in lieu of
2985                                                             // using nlist_idx in case we ever start trimming entries out
2986                                                             const bool N_SO_has_full_path = symbol_name[0] == '/';
2987                                                             if (N_SO_has_full_path)
2988                                                             {
2989                                                                 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
2990                                                                 {
2991                                                                     // We have two consecutive N_SO entries where the first contains a directory
2992                                                                     // and the second contains a full path.
2993                                                                     sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name), false);
2994                                                                     m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
2995                                                                     add_nlist = false;
2996                                                                 }
2997                                                                 else
2998                                                                 {
2999                                                                     // This is the first entry in a N_SO that contains a directory or
3000                                                                     // a full path to the source file
3001                                                                     N_SO_index = sym_idx;
3002                                                                 }
3003                                                             }
3004                                                             else if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
3005                                                             {
3006                                                                 // This is usually the second N_SO entry that contains just the filename,
3007                                                                 // so here we combine it with the first one if we are minimizing the symbol table
3008                                                                 const char *so_path = sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString();
3009                                                                 if (so_path && so_path[0])
3010                                                                 {
3011                                                                     std::string full_so_path (so_path);
3012                                                                     const size_t double_slash_pos = full_so_path.find("//");
3013                                                                     if (double_slash_pos != std::string::npos)
3014                                                                     {
3015                                                                         // The linker has been generating bad N_SO entries with doubled up paths
3016                                                                         // in the format "%s%s" where the first string in the DW_AT_comp_dir,
3017                                                                         // and the second is the directory for the source file so you end up with
3018                                                                         // a path that looks like "/tmp/src//tmp/src/"
3019                                                                         FileSpec so_dir(so_path, false);
3020                                                                         if (!so_dir.Exists())
3021                                                                         {
3022                                                                             so_dir.SetFile(&full_so_path[double_slash_pos + 1], false);
3023                                                                             if (so_dir.Exists())
3024                                                                             {
3025                                                                                 // Trim off the incorrect path
3026                                                                                 full_so_path.erase(0, double_slash_pos + 1);
3027                                                                             }
3028                                                                         }
3029                                                                     }
3030                                                                     if (*full_so_path.rbegin() != '/')
3031                                                                         full_so_path += '/';
3032                                                                     full_so_path += symbol_name;
3033                                                                     sym[sym_idx - 1].GetMangled().SetValue(ConstString(full_so_path.c_str()), false);
3034                                                                     add_nlist = false;
3035                                                                     m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3036                                                                 }
3037                                                             }
3038                                                             else
3039                                                             {
3040                                                                 // This could be a relative path to a N_SO
3041                                                                 N_SO_index = sym_idx;
3042                                                             }
3043                                                         }
3044                                                         break;
3045 
3046                                                     case N_OSO:
3047                                                         // object file name: name,,0,0,st_mtime
3048                                                         type = eSymbolTypeObjectFile;
3049                                                         break;
3050 
3051                                                     case N_LSYM:
3052                                                         // local sym: name,,NO_SECT,type,offset
3053                                                         type = eSymbolTypeLocal;
3054                                                         break;
3055 
3056                                                         //----------------------------------------------------------------------
3057                                                         // INCL scopes
3058                                                         //----------------------------------------------------------------------
3059                                                     case N_BINCL:
3060                                                         // include file beginning: name,,NO_SECT,0,sum
3061                                                         // We use the current number of symbols in the symbol table in lieu of
3062                                                         // using nlist_idx in case we ever start trimming entries out
3063                                                         N_INCL_indexes.push_back(sym_idx);
3064                                                         type = eSymbolTypeScopeBegin;
3065                                                         break;
3066 
3067                                                     case N_EINCL:
3068                                                         // include file end: name,,NO_SECT,0,0
3069                                                         // Set the size of the N_BINCL to the terminating index of this N_EINCL
3070                                                         // so that we can always skip the entire symbol if we need to navigate
3071                                                         // more quickly at the source level when parsing STABS
3072                                                         if ( !N_INCL_indexes.empty() )
3073                                                         {
3074                                                             symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
3075                                                             symbol_ptr->SetByteSize(sym_idx + 1);
3076                                                             symbol_ptr->SetSizeIsSibling(true);
3077                                                             N_INCL_indexes.pop_back();
3078                                                         }
3079                                                         type = eSymbolTypeScopeEnd;
3080                                                         break;
3081 
3082                                                     case N_SOL:
3083                                                         // #included file name: name,,n_sect,0,address
3084                                                         type = eSymbolTypeHeaderFile;
3085 
3086                                                         // We currently don't use the header files on darwin
3087                                                         add_nlist = false;
3088                                                         break;
3089 
3090                                                     case N_PARAMS:
3091                                                         // compiler parameters: name,,NO_SECT,0,0
3092                                                         type = eSymbolTypeCompiler;
3093                                                         break;
3094 
3095                                                     case N_VERSION:
3096                                                         // compiler version: name,,NO_SECT,0,0
3097                                                         type = eSymbolTypeCompiler;
3098                                                         break;
3099 
3100                                                     case N_OLEVEL:
3101                                                         // compiler -O level: name,,NO_SECT,0,0
3102                                                         type = eSymbolTypeCompiler;
3103                                                         break;
3104 
3105                                                     case N_PSYM:
3106                                                         // parameter: name,,NO_SECT,type,offset
3107                                                         type = eSymbolTypeVariable;
3108                                                         break;
3109 
3110                                                     case N_ENTRY:
3111                                                         // alternate entry: name,,n_sect,linenumber,address
3112                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3113                                                         type = eSymbolTypeLineEntry;
3114                                                         break;
3115 
3116                                                         //----------------------------------------------------------------------
3117                                                         // Left and Right Braces
3118                                                         //----------------------------------------------------------------------
3119                                                     case N_LBRAC:
3120                                                         // left bracket: 0,,NO_SECT,nesting level,address
3121                                                         // We use the current number of symbols in the symbol table in lieu of
3122                                                         // using nlist_idx in case we ever start trimming entries out
3123                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3124                                                         N_BRAC_indexes.push_back(sym_idx);
3125                                                         type = eSymbolTypeScopeBegin;
3126                                                         break;
3127 
3128                                                     case N_RBRAC:
3129                                                         // right bracket: 0,,NO_SECT,nesting level,address
3130                                                         // Set the size of the N_LBRAC to the terminating index of this N_RBRAC
3131                                                         // so that we can always skip the entire symbol if we need to navigate
3132                                                         // more quickly at the source level when parsing STABS
3133                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3134                                                         if ( !N_BRAC_indexes.empty() )
3135                                                         {
3136                                                             symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
3137                                                             symbol_ptr->SetByteSize(sym_idx + 1);
3138                                                             symbol_ptr->SetSizeIsSibling(true);
3139                                                             N_BRAC_indexes.pop_back();
3140                                                         }
3141                                                         type = eSymbolTypeScopeEnd;
3142                                                         break;
3143 
3144                                                     case N_EXCL:
3145                                                         // deleted include file: name,,NO_SECT,0,sum
3146                                                         type = eSymbolTypeHeaderFile;
3147                                                         break;
3148 
3149                                                         //----------------------------------------------------------------------
3150                                                         // COMM scopes
3151                                                         //----------------------------------------------------------------------
3152                                                     case N_BCOMM:
3153                                                         // begin common: name,,NO_SECT,0,0
3154                                                         // We use the current number of symbols in the symbol table in lieu of
3155                                                         // using nlist_idx in case we ever start trimming entries out
3156                                                         type = eSymbolTypeScopeBegin;
3157                                                         N_COMM_indexes.push_back(sym_idx);
3158                                                         break;
3159 
3160                                                     case N_ECOML:
3161                                                         // end common (local name): 0,,n_sect,0,address
3162                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3163                                                         // Fall through
3164 
3165                                                     case N_ECOMM:
3166                                                         // end common: name,,n_sect,0,0
3167                                                         // Set the size of the N_BCOMM to the terminating index of this N_ECOMM/N_ECOML
3168                                                         // so that we can always skip the entire symbol if we need to navigate
3169                                                         // more quickly at the source level when parsing STABS
3170                                                         if ( !N_COMM_indexes.empty() )
3171                                                         {
3172                                                             symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
3173                                                             symbol_ptr->SetByteSize(sym_idx + 1);
3174                                                             symbol_ptr->SetSizeIsSibling(true);
3175                                                             N_COMM_indexes.pop_back();
3176                                                         }
3177                                                         type = eSymbolTypeScopeEnd;
3178                                                         break;
3179 
3180                                                     case N_LENG:
3181                                                         // second stab entry with length information
3182                                                         type = eSymbolTypeAdditional;
3183                                                         break;
3184 
3185                                                     default: break;
3186                                                 }
3187                                             }
3188                                             else
3189                                             {
3190                                                 //uint8_t n_pext    = N_PEXT & nlist.n_type;
3191                                                 uint8_t n_type  = N_TYPE & nlist.n_type;
3192                                                 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
3193 
3194                                                 switch (n_type)
3195                                                 {
3196                                                     case N_INDR:
3197                                                         {
3198                                                             const char *reexport_name_cstr = strtab_data.PeekCStr(nlist.n_value);
3199                                                             if (reexport_name_cstr && reexport_name_cstr[0])
3200                                                             {
3201                                                                 type = eSymbolTypeReExported;
3202                                                                 ConstString reexport_name(reexport_name_cstr + ((reexport_name_cstr[0] == '_') ? 1 : 0));
3203                                                                 sym[sym_idx].SetReExportedSymbolName(reexport_name);
3204                                                                 set_value = false;
3205                                                                 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3206                                                                 indirect_symbol_names.insert(ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
3207                                                             }
3208                                                             else
3209                                                                 type = eSymbolTypeUndefined;
3210                                                         }
3211                                                         break;
3212 
3213                                                     case N_UNDF:
3214                                                         if (symbol_name && symbol_name[0])
3215                                                         {
3216                                                             ConstString undefined_name(symbol_name + ((symbol_name[0] == '_') ? 1 : 0));
3217                                                             undefined_name_to_desc[undefined_name] = nlist.n_desc;
3218                                                         }
3219                                                         // Fall through
3220                                                     case N_PBUD:
3221                                                         type = eSymbolTypeUndefined;
3222                                                         break;
3223 
3224                                                     case N_ABS:
3225                                                         type = eSymbolTypeAbsolute;
3226                                                         break;
3227 
3228                                                     case N_SECT:
3229                                                         {
3230                                                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3231 
3232                                                             if (symbol_section == NULL)
3233                                                             {
3234                                                                 // TODO: warn about this?
3235                                                                 add_nlist = false;
3236                                                                 break;
3237                                                             }
3238 
3239                                                             if (TEXT_eh_frame_sectID == nlist.n_sect)
3240                                                             {
3241                                                                 type = eSymbolTypeException;
3242                                                             }
3243                                                             else
3244                                                             {
3245                                                                 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
3246 
3247                                                                 switch (section_type)
3248                                                                 {
3249                                                                     case S_CSTRING_LITERALS:           type = eSymbolTypeData;    break; // section with only literal C strings
3250                                                                     case S_4BYTE_LITERALS:             type = eSymbolTypeData;    break; // section with only 4 byte literals
3251                                                                     case S_8BYTE_LITERALS:             type = eSymbolTypeData;    break; // section with only 8 byte literals
3252                                                                     case S_LITERAL_POINTERS:           type = eSymbolTypeTrampoline; break; // section with only pointers to literals
3253                                                                     case S_NON_LAZY_SYMBOL_POINTERS:   type = eSymbolTypeTrampoline; break; // section with only non-lazy symbol pointers
3254                                                                     case S_LAZY_SYMBOL_POINTERS:       type = eSymbolTypeTrampoline; break; // section with only lazy symbol pointers
3255                                                                     case S_SYMBOL_STUBS:               type = eSymbolTypeTrampoline; break; // section with only symbol stubs, byte size of stub in the reserved2 field
3256                                                                     case S_MOD_INIT_FUNC_POINTERS:     type = eSymbolTypeCode;    break; // section with only function pointers for initialization
3257                                                                     case S_MOD_TERM_FUNC_POINTERS:     type = eSymbolTypeCode;    break; // section with only function pointers for termination
3258                                                                     case S_INTERPOSING:                type = eSymbolTypeTrampoline;  break; // section with only pairs of function pointers for interposing
3259                                                                     case S_16BYTE_LITERALS:            type = eSymbolTypeData;    break; // section with only 16 byte literals
3260                                                                     case S_DTRACE_DOF:                 type = eSymbolTypeInstrumentation; break;
3261                                                                     case S_LAZY_DYLIB_SYMBOL_POINTERS: type = eSymbolTypeTrampoline; break;
3262                                                                     default:
3263                                                                         switch (symbol_section->GetType())
3264                                                                         {
3265                                                                             case lldb::eSectionTypeCode:
3266                                                                                 type = eSymbolTypeCode;
3267                                                                                 break;
3268                                                                             case eSectionTypeData:
3269                                                                             case eSectionTypeDataCString:            // Inlined C string data
3270                                                                             case eSectionTypeDataCStringPointers:    // Pointers to C string data
3271                                                                             case eSectionTypeDataSymbolAddress:      // Address of a symbol in the symbol table
3272                                                                             case eSectionTypeData4:
3273                                                                             case eSectionTypeData8:
3274                                                                             case eSectionTypeData16:
3275                                                                                 type = eSymbolTypeData;
3276                                                                                 break;
3277                                                                             default:
3278                                                                                 break;
3279                                                                         }
3280                                                                         break;
3281                                                                 }
3282 
3283                                                                 if (type == eSymbolTypeInvalid)
3284                                                                 {
3285                                                                     const char *symbol_sect_name = symbol_section->GetName().AsCString();
3286                                                                     if (symbol_section->IsDescendant (text_section_sp.get()))
3287                                                                     {
3288                                                                         if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
3289                                                                                                     S_ATTR_SELF_MODIFYING_CODE |
3290                                                                                                     S_ATTR_SOME_INSTRUCTIONS))
3291                                                                             type = eSymbolTypeData;
3292                                                                         else
3293                                                                             type = eSymbolTypeCode;
3294                                                                     }
3295                                                                     else if (symbol_section->IsDescendant(data_section_sp.get()))
3296                                                                     {
3297                                                                         if (symbol_sect_name && ::strstr (symbol_sect_name, "__objc") == symbol_sect_name)
3298                                                                         {
3299                                                                             type = eSymbolTypeRuntime;
3300 
3301                                                                             if (symbol_name &&
3302                                                                                 symbol_name[0] == '_' &&
3303                                                                                 symbol_name[1] == 'O' &&
3304                                                                                 symbol_name[2] == 'B')
3305                                                                             {
3306                                                                                 llvm::StringRef symbol_name_ref(symbol_name);
3307                                                                                 if (symbol_name_ref.startswith(g_objc_v2_prefix_class))
3308                                                                                 {
3309                                                                                     symbol_name_non_abi_mangled = symbol_name + 1;
3310                                                                                     symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3311                                                                                     type = eSymbolTypeObjCClass;
3312                                                                                     demangled_is_synthesized = true;
3313                                                                                 }
3314                                                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass))
3315                                                                                 {
3316                                                                                     symbol_name_non_abi_mangled = symbol_name + 1;
3317                                                                                     symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3318                                                                                     type = eSymbolTypeObjCMetaClass;
3319                                                                                     demangled_is_synthesized = true;
3320                                                                                 }
3321                                                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar))
3322                                                                                 {
3323                                                                                     symbol_name_non_abi_mangled = symbol_name + 1;
3324                                                                                     symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3325                                                                                     type = eSymbolTypeObjCIVar;
3326                                                                                     demangled_is_synthesized = true;
3327                                                                                 }
3328                                                                             }
3329                                                                         }
3330                                                                         else if (symbol_sect_name && ::strstr (symbol_sect_name, "__gcc_except_tab") == symbol_sect_name)
3331                                                                         {
3332                                                                             type = eSymbolTypeException;
3333                                                                         }
3334                                                                         else
3335                                                                         {
3336                                                                             type = eSymbolTypeData;
3337                                                                         }
3338                                                                     }
3339                                                                     else if (symbol_sect_name && ::strstr (symbol_sect_name, "__IMPORT") == symbol_sect_name)
3340                                                                     {
3341                                                                         type = eSymbolTypeTrampoline;
3342                                                                     }
3343                                                                     else if (symbol_section->IsDescendant(objc_section_sp.get()))
3344                                                                     {
3345                                                                         type = eSymbolTypeRuntime;
3346                                                                         if (symbol_name && symbol_name[0] == '.')
3347                                                                         {
3348                                                                             llvm::StringRef symbol_name_ref(symbol_name);
3349                                                                             static const llvm::StringRef g_objc_v1_prefix_class (".objc_class_name_");
3350                                                                             if (symbol_name_ref.startswith(g_objc_v1_prefix_class))
3351                                                                             {
3352                                                                                 symbol_name_non_abi_mangled = symbol_name;
3353                                                                                 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
3354                                                                                 type = eSymbolTypeObjCClass;
3355                                                                                 demangled_is_synthesized = true;
3356                                                                             }
3357                                                                         }
3358                                                                     }
3359                                                                 }
3360                                                             }
3361                                                         }
3362                                                         break;
3363                                                 }
3364                                             }
3365 
3366                                             if (add_nlist)
3367                                             {
3368                                                 uint64_t symbol_value = nlist.n_value;
3369                                                 if (symbol_name_non_abi_mangled)
3370                                                 {
3371                                                     sym[sym_idx].GetMangled().SetMangledName (ConstString(symbol_name_non_abi_mangled));
3372                                                     sym[sym_idx].GetMangled().SetDemangledName (ConstString(symbol_name));
3373                                                 }
3374                                                 else
3375                                                 {
3376                                                     bool symbol_name_is_mangled = false;
3377 
3378                                                     if (symbol_name && symbol_name[0] == '_')
3379                                                     {
3380                                                         symbol_name_is_mangled = symbol_name[1] == '_';
3381                                                         symbol_name++;  // Skip the leading underscore
3382                                                     }
3383 
3384                                                     if (symbol_name)
3385                                                     {
3386                                                         ConstString const_symbol_name(symbol_name);
3387                                                         sym[sym_idx].GetMangled().SetValue(const_symbol_name, symbol_name_is_mangled);
3388                                                         if (is_gsym && is_debug)
3389                                                         {
3390                                                             const char *gsym_name = sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString();
3391                                                             if (gsym_name)
3392                                                                 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3393                                                         }
3394                                                     }
3395                                                 }
3396                                                 if (symbol_section)
3397                                                 {
3398                                                     const addr_t section_file_addr = symbol_section->GetFileAddress();
3399                                                     if (symbol_byte_size == 0 && function_starts_count > 0)
3400                                                     {
3401                                                         addr_t symbol_lookup_file_addr = nlist.n_value;
3402                                                         // Do an exact address match for non-ARM addresses, else get the closest since
3403                                                         // the symbol might be a thumb symbol which has an address with bit zero set
3404                                                         FunctionStarts::Entry *func_start_entry = function_starts.FindEntry (symbol_lookup_file_addr, !is_arm);
3405                                                         if (is_arm && func_start_entry)
3406                                                         {
3407                                                             // Verify that the function start address is the symbol address (ARM)
3408                                                             // or the symbol address + 1 (thumb)
3409                                                             if (func_start_entry->addr != symbol_lookup_file_addr &&
3410                                                                 func_start_entry->addr != (symbol_lookup_file_addr + 1))
3411                                                             {
3412                                                                 // Not the right entry, NULL it out...
3413                                                                 func_start_entry = NULL;
3414                                                             }
3415                                                         }
3416                                                         if (func_start_entry)
3417                                                         {
3418                                                             func_start_entry->data = true;
3419 
3420                                                             addr_t symbol_file_addr = func_start_entry->addr;
3421                                                             uint32_t symbol_flags = 0;
3422                                                             if (is_arm)
3423                                                             {
3424                                                                 if (symbol_file_addr & 1)
3425                                                                     symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3426                                                                 symbol_file_addr &= 0xfffffffffffffffeull;
3427                                                             }
3428 
3429                                                             const FunctionStarts::Entry *next_func_start_entry = function_starts.FindNextEntry (func_start_entry);
3430                                                             const addr_t section_end_file_addr = section_file_addr + symbol_section->GetByteSize();
3431                                                             if (next_func_start_entry)
3432                                                             {
3433                                                                 addr_t next_symbol_file_addr = next_func_start_entry->addr;
3434                                                                 // Be sure the clear the Thumb address bit when we calculate the size
3435                                                                 // from the current and next address
3436                                                                 if (is_arm)
3437                                                                     next_symbol_file_addr &= 0xfffffffffffffffeull;
3438                                                                 symbol_byte_size = std::min<lldb::addr_t>(next_symbol_file_addr - symbol_file_addr, section_end_file_addr - symbol_file_addr);
3439                                                             }
3440                                                             else
3441                                                             {
3442                                                                 symbol_byte_size = section_end_file_addr - symbol_file_addr;
3443                                                             }
3444                                                         }
3445                                                     }
3446                                                     symbol_value -= section_file_addr;
3447                                                 }
3448 
3449                                                 if (is_debug == false)
3450                                                 {
3451                                                     if (type == eSymbolTypeCode)
3452                                                     {
3453                                                         // See if we can find a N_FUN entry for any code symbols.
3454                                                         // If we do find a match, and the name matches, then we
3455                                                         // can merge the two into just the function symbol to avoid
3456                                                         // duplicate entries in the symbol table
3457                                                         std::pair<ValueToSymbolIndexMap::const_iterator, ValueToSymbolIndexMap::const_iterator> range;
3458                                                         range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
3459                                                         if (range.first != range.second)
3460                                                         {
3461                                                             bool found_it = false;
3462                                                             for (ValueToSymbolIndexMap::const_iterator pos = range.first; pos != range.second; ++pos)
3463                                                             {
3464                                                                 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled))
3465                                                                 {
3466                                                                     m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3467                                                                     // We just need the flags from the linker symbol, so put these flags
3468                                                                     // into the N_FUN flags to avoid duplicate symbols in the symbol table
3469                                                                     sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
3470                                                                     sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3471                                                                     if (resolver_addresses.find(nlist.n_value) != resolver_addresses.end())
3472                                                                         sym[pos->second].SetType (eSymbolTypeResolver);
3473                                                                     sym[sym_idx].Clear();
3474                                                                     found_it = true;
3475                                                                     break;
3476                                                                 }
3477                                                             }
3478                                                             if (found_it)
3479                                                                 continue;
3480                                                         }
3481                                                         else
3482                                                         {
3483                                                             if (resolver_addresses.find(nlist.n_value) != resolver_addresses.end())
3484                                                                 type = eSymbolTypeResolver;
3485                                                         }
3486                                                     }
3487                                                     else if (type == eSymbolTypeData          ||
3488                                                              type == eSymbolTypeObjCClass     ||
3489                                                              type == eSymbolTypeObjCMetaClass ||
3490                                                              type == eSymbolTypeObjCIVar      )
3491                                                     {
3492                                                         // See if we can find a N_STSYM entry for any data symbols.
3493                                                         // If we do find a match, and the name matches, then we
3494                                                         // can merge the two into just the Static symbol to avoid
3495                                                         // duplicate entries in the symbol table
3496                                                         std::pair<ValueToSymbolIndexMap::const_iterator, ValueToSymbolIndexMap::const_iterator> range;
3497                                                         range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
3498                                                         if (range.first != range.second)
3499                                                         {
3500                                                             bool found_it = false;
3501                                                             for (ValueToSymbolIndexMap::const_iterator pos = range.first; pos != range.second; ++pos)
3502                                                             {
3503                                                                 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled))
3504                                                                 {
3505                                                                     m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3506                                                                     // We just need the flags from the linker symbol, so put these flags
3507                                                                     // into the N_STSYM flags to avoid duplicate symbols in the symbol table
3508                                                                     sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
3509                                                                     sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3510                                                                     sym[sym_idx].Clear();
3511                                                                     found_it = true;
3512                                                                     break;
3513                                                                 }
3514                                                             }
3515                                                             if (found_it)
3516                                                                 continue;
3517                                                         }
3518                                                         else
3519                                                         {
3520                                                             const char *gsym_name = sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString();
3521                                                             if (gsym_name)
3522                                                             {
3523                                                                 // Combine N_GSYM stab entries with the non stab symbol
3524                                                                 ConstNameToSymbolIndexMap::const_iterator pos = N_GSYM_name_to_sym_idx.find(gsym_name);
3525                                                                 if (pos != N_GSYM_name_to_sym_idx.end())
3526                                                                 {
3527                                                                     const uint32_t GSYM_sym_idx = pos->second;
3528                                                                     m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
3529                                                                     // Copy the address, because often the N_GSYM address has an invalid address of zero
3530                                                                     // when the global is a common symbol
3531                                                                     sym[GSYM_sym_idx].GetAddressRef().SetSection (symbol_section);
3532                                                                     sym[GSYM_sym_idx].GetAddressRef().SetOffset (symbol_value);
3533                                                                     // We just need the flags from the linker symbol, so put these flags
3534                                                                     // into the N_GSYM flags to avoid duplicate symbols in the symbol table
3535                                                                     sym[GSYM_sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3536                                                                     sym[sym_idx].Clear();
3537                                                                     continue;
3538                                                                 }
3539                                                             }
3540                                                         }
3541                                                     }
3542                                                 }
3543 
3544                                                 sym[sym_idx].SetID (nlist_idx);
3545                                                 sym[sym_idx].SetType (type);
3546                                                 if (set_value)
3547                                                 {
3548                                                     sym[sym_idx].GetAddressRef().SetSection (symbol_section);
3549                                                     sym[sym_idx].GetAddressRef().SetOffset (symbol_value);
3550                                                 }
3551                                                 sym[sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3552 
3553                                                 if (symbol_byte_size > 0)
3554                                                     sym[sym_idx].SetByteSize(symbol_byte_size);
3555 
3556                                                 if (demangled_is_synthesized)
3557                                                     sym[sym_idx].SetDemangledNameIsSynthesized(true);
3558                                                 ++sym_idx;
3559                                             }
3560                                             else
3561                                             {
3562                                                 sym[sym_idx].Clear();
3563                                             }
3564 
3565                                         }
3566                                         /////////////////////////////
3567                                     }
3568                                     break; // No more entries to consider
3569                                 }
3570                             }
3571 
3572                             for (const auto &pos :reexport_shlib_needs_fixup)
3573                             {
3574                                 const auto undef_pos = undefined_name_to_desc.find(pos.second);
3575                                 if (undef_pos != undefined_name_to_desc.end())
3576                                 {
3577                                     const uint8_t dylib_ordinal = llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3578                                     if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
3579                                         sym[pos.first].SetReExportedSymbolSharedLibrary(dylib_files.GetFileSpecAtIndex(dylib_ordinal-1));
3580                                 }
3581                             }
3582                         }
3583                     }
3584                 }
3585             }
3586         }
3587 
3588         // Must reset this in case it was mutated above!
3589         nlist_data_offset = 0;
3590 #endif
3591 
3592         if (nlist_data.GetByteSize() > 0)
3593         {
3594 
3595             // If the sym array was not created while parsing the DSC unmapped
3596             // symbols, create it now.
3597             if (sym == NULL)
3598             {
3599                 sym = symtab->Resize (symtab_load_command.nsyms + m_dysymtab.nindirectsyms);
3600                 num_syms = symtab->GetNumSymbols();
3601             }
3602 
3603             if (unmapped_local_symbols_found)
3604             {
3605                 assert(m_dysymtab.ilocalsym == 0);
3606                 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3607                 nlist_idx = m_dysymtab.nlocalsym;
3608             }
3609             else
3610             {
3611                 nlist_idx = 0;
3612             }
3613 
3614             typedef std::map<ConstString, uint16_t> UndefinedNameToDescMap;
3615             typedef std::map<uint32_t, ConstString> SymbolIndexToName;
3616             UndefinedNameToDescMap undefined_name_to_desc;
3617             SymbolIndexToName reexport_shlib_needs_fixup;
3618             for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx)
3619             {
3620                 struct nlist_64 nlist;
3621                 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size))
3622                     break;
3623 
3624                 nlist.n_strx  = nlist_data.GetU32_unchecked(&nlist_data_offset);
3625                 nlist.n_type  = nlist_data.GetU8_unchecked (&nlist_data_offset);
3626                 nlist.n_sect  = nlist_data.GetU8_unchecked (&nlist_data_offset);
3627                 nlist.n_desc  = nlist_data.GetU16_unchecked (&nlist_data_offset);
3628                 nlist.n_value = nlist_data.GetAddress_unchecked (&nlist_data_offset);
3629 
3630                 SymbolType type = eSymbolTypeInvalid;
3631                 const char *symbol_name = NULL;
3632 
3633                 if (have_strtab_data)
3634                 {
3635                     symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3636 
3637                     if (symbol_name == NULL)
3638                     {
3639                         // No symbol should be NULL, even the symbols with no
3640                         // string values should have an offset zero which points
3641                         // to an empty C-string
3642                         Host::SystemLog (Host::eSystemLogError,
3643                                          "error: symbol[%u] has invalid string table offset 0x%x in %s, ignoring symbol\n",
3644                                          nlist_idx,
3645                                          nlist.n_strx,
3646                                          module_sp->GetFileSpec().GetPath().c_str());
3647                         continue;
3648                     }
3649                     if (symbol_name[0] == '\0')
3650                         symbol_name = NULL;
3651                 }
3652                 else
3653                 {
3654                     const addr_t str_addr = strtab_addr + nlist.n_strx;
3655                     Error str_error;
3656                     if (process->ReadCStringFromMemory(str_addr, memory_symbol_name, str_error))
3657                         symbol_name = memory_symbol_name.c_str();
3658                 }
3659                 const char *symbol_name_non_abi_mangled = NULL;
3660 
3661                 SectionSP symbol_section;
3662                 lldb::addr_t symbol_byte_size = 0;
3663                 bool add_nlist = true;
3664                 bool is_gsym = false;
3665                 bool is_debug = ((nlist.n_type & N_STAB) != 0);
3666                 bool demangled_is_synthesized = false;
3667                 bool set_value = true;
3668                 assert (sym_idx < num_syms);
3669 
3670                 sym[sym_idx].SetDebug (is_debug);
3671 
3672                 if (is_debug)
3673                 {
3674                     switch (nlist.n_type)
3675                     {
3676                     case N_GSYM:
3677                         // global symbol: name,,NO_SECT,type,0
3678                         // Sometimes the N_GSYM value contains the address.
3679 
3680                         // FIXME: In the .o files, we have a GSYM and a debug symbol for all the ObjC data.  They
3681                         // have the same address, but we want to ensure that we always find only the real symbol,
3682                         // 'cause we don't currently correctly attribute the GSYM one to the ObjCClass/Ivar/MetaClass
3683                         // symbol type.  This is a temporary hack to make sure the ObjectiveC symbols get treated
3684                         // correctly.  To do this right, we should coalesce all the GSYM & global symbols that have the
3685                         // same address.
3686                         is_gsym = true;
3687                         sym[sym_idx].SetExternal(true);
3688 
3689                         if (symbol_name && symbol_name[0] == '_' && symbol_name[1] ==  'O')
3690                         {
3691                             llvm::StringRef symbol_name_ref(symbol_name);
3692                             if (symbol_name_ref.startswith(g_objc_v2_prefix_class))
3693                             {
3694                                 symbol_name_non_abi_mangled = symbol_name + 1;
3695                                 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3696                                 type = eSymbolTypeObjCClass;
3697                                 demangled_is_synthesized = true;
3698 
3699                             }
3700                             else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass))
3701                             {
3702                                 symbol_name_non_abi_mangled = symbol_name + 1;
3703                                 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3704                                 type = eSymbolTypeObjCMetaClass;
3705                                 demangled_is_synthesized = true;
3706                             }
3707                             else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar))
3708                             {
3709                                 symbol_name_non_abi_mangled = symbol_name + 1;
3710                                 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3711                                 type = eSymbolTypeObjCIVar;
3712                                 demangled_is_synthesized = true;
3713                             }
3714                         }
3715                         else
3716                         {
3717                             if (nlist.n_value != 0)
3718                                 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3719                             type = eSymbolTypeData;
3720                         }
3721                         break;
3722 
3723                     case N_FNAME:
3724                         // procedure name (f77 kludge): name,,NO_SECT,0,0
3725                         type = eSymbolTypeCompiler;
3726                         break;
3727 
3728                     case N_FUN:
3729                         // procedure: name,,n_sect,linenumber,address
3730                         if (symbol_name)
3731                         {
3732                             type = eSymbolTypeCode;
3733                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3734 
3735                             N_FUN_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx));
3736                             // We use the current number of symbols in the symbol table in lieu of
3737                             // using nlist_idx in case we ever start trimming entries out
3738                             N_FUN_indexes.push_back(sym_idx);
3739                         }
3740                         else
3741                         {
3742                             type = eSymbolTypeCompiler;
3743 
3744                             if ( !N_FUN_indexes.empty() )
3745                             {
3746                                 // Copy the size of the function into the original STAB entry so we don't have
3747                                 // to hunt for it later
3748                                 symtab->SymbolAtIndex(N_FUN_indexes.back())->SetByteSize(nlist.n_value);
3749                                 N_FUN_indexes.pop_back();
3750                                 // We don't really need the end function STAB as it contains the size which
3751                                 // we already placed with the original symbol, so don't add it if we want a
3752                                 // minimal symbol table
3753                                 add_nlist = false;
3754                             }
3755                         }
3756                         break;
3757 
3758                     case N_STSYM:
3759                         // static symbol: name,,n_sect,type,address
3760                         N_STSYM_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx));
3761                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3762                         type = eSymbolTypeData;
3763                         break;
3764 
3765                     case N_LCSYM:
3766                         // .lcomm symbol: name,,n_sect,type,address
3767                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3768                         type = eSymbolTypeCommonBlock;
3769                         break;
3770 
3771                     case N_BNSYM:
3772                         // We use the current number of symbols in the symbol table in lieu of
3773                         // using nlist_idx in case we ever start trimming entries out
3774                         // Skip these if we want minimal symbol tables
3775                         add_nlist = false;
3776                         break;
3777 
3778                     case N_ENSYM:
3779                         // Set the size of the N_BNSYM to the terminating index of this N_ENSYM
3780                         // so that we can always skip the entire symbol if we need to navigate
3781                         // more quickly at the source level when parsing STABS
3782                         // Skip these if we want minimal symbol tables
3783                         add_nlist = false;
3784                         break;
3785 
3786 
3787                     case N_OPT:
3788                         // emitted with gcc2_compiled and in gcc source
3789                         type = eSymbolTypeCompiler;
3790                         break;
3791 
3792                     case N_RSYM:
3793                         // register sym: name,,NO_SECT,type,register
3794                         type = eSymbolTypeVariable;
3795                         break;
3796 
3797                     case N_SLINE:
3798                         // src line: 0,,n_sect,linenumber,address
3799                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3800                         type = eSymbolTypeLineEntry;
3801                         break;
3802 
3803                     case N_SSYM:
3804                         // structure elt: name,,NO_SECT,type,struct_offset
3805                         type = eSymbolTypeVariableType;
3806                         break;
3807 
3808                     case N_SO:
3809                         // source file name
3810                         type = eSymbolTypeSourceFile;
3811                         if (symbol_name == NULL)
3812                         {
3813                             add_nlist = false;
3814                             if (N_SO_index != UINT32_MAX)
3815                             {
3816                                 // Set the size of the N_SO to the terminating index of this N_SO
3817                                 // so that we can always skip the entire N_SO if we need to navigate
3818                                 // more quickly at the source level when parsing STABS
3819                                 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3820                                 symbol_ptr->SetByteSize(sym_idx);
3821                                 symbol_ptr->SetSizeIsSibling(true);
3822                             }
3823                             N_NSYM_indexes.clear();
3824                             N_INCL_indexes.clear();
3825                             N_BRAC_indexes.clear();
3826                             N_COMM_indexes.clear();
3827                             N_FUN_indexes.clear();
3828                             N_SO_index = UINT32_MAX;
3829                         }
3830                         else
3831                         {
3832                             // We use the current number of symbols in the symbol table in lieu of
3833                             // using nlist_idx in case we ever start trimming entries out
3834                             const bool N_SO_has_full_path = symbol_name[0] == '/';
3835                             if (N_SO_has_full_path)
3836                             {
3837                                 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
3838                                 {
3839                                     // We have two consecutive N_SO entries where the first contains a directory
3840                                     // and the second contains a full path.
3841                                     sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name), false);
3842                                     m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3843                                     add_nlist = false;
3844                                 }
3845                                 else
3846                                 {
3847                                     // This is the first entry in a N_SO that contains a directory or
3848                                     // a full path to the source file
3849                                     N_SO_index = sym_idx;
3850                                 }
3851                             }
3852                             else if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
3853                             {
3854                                 // This is usually the second N_SO entry that contains just the filename,
3855                                 // so here we combine it with the first one if we are minimizing the symbol table
3856                                 const char *so_path = sym[sym_idx - 1].GetMangled().GetDemangledName(lldb::eLanguageTypeUnknown).AsCString();
3857                                 if (so_path && so_path[0])
3858                                 {
3859                                     std::string full_so_path (so_path);
3860                                     const size_t double_slash_pos = full_so_path.find("//");
3861                                     if (double_slash_pos != std::string::npos)
3862                                     {
3863                                         // The linker has been generating bad N_SO entries with doubled up paths
3864                                         // in the format "%s%s" where the first string in the DW_AT_comp_dir,
3865                                         // and the second is the directory for the source file so you end up with
3866                                         // a path that looks like "/tmp/src//tmp/src/"
3867                                         FileSpec so_dir(so_path, false);
3868                                         if (!so_dir.Exists())
3869                                         {
3870                                             so_dir.SetFile(&full_so_path[double_slash_pos + 1], false);
3871                                             if (so_dir.Exists())
3872                                             {
3873                                                 // Trim off the incorrect path
3874                                                 full_so_path.erase(0, double_slash_pos + 1);
3875                                             }
3876                                         }
3877                                     }
3878                                     if (*full_so_path.rbegin() != '/')
3879                                         full_so_path += '/';
3880                                     full_so_path += symbol_name;
3881                                     sym[sym_idx - 1].GetMangled().SetValue(ConstString(full_so_path.c_str()), false);
3882                                     add_nlist = false;
3883                                     m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3884                                 }
3885                             }
3886                             else
3887                             {
3888                                 // This could be a relative path to a N_SO
3889                                 N_SO_index = sym_idx;
3890                             }
3891                         }
3892 
3893                         break;
3894 
3895                     case N_OSO:
3896                         // object file name: name,,0,0,st_mtime
3897                         type = eSymbolTypeObjectFile;
3898                         break;
3899 
3900                     case N_LSYM:
3901                         // local sym: name,,NO_SECT,type,offset
3902                         type = eSymbolTypeLocal;
3903                         break;
3904 
3905                     //----------------------------------------------------------------------
3906                     // INCL scopes
3907                     //----------------------------------------------------------------------
3908                     case N_BINCL:
3909                         // include file beginning: name,,NO_SECT,0,sum
3910                         // We use the current number of symbols in the symbol table in lieu of
3911                         // using nlist_idx in case we ever start trimming entries out
3912                         N_INCL_indexes.push_back(sym_idx);
3913                         type = eSymbolTypeScopeBegin;
3914                         break;
3915 
3916                     case N_EINCL:
3917                         // include file end: name,,NO_SECT,0,0
3918                         // Set the size of the N_BINCL to the terminating index of this N_EINCL
3919                         // so that we can always skip the entire symbol if we need to navigate
3920                         // more quickly at the source level when parsing STABS
3921                         if ( !N_INCL_indexes.empty() )
3922                         {
3923                             symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
3924                             symbol_ptr->SetByteSize(sym_idx + 1);
3925                             symbol_ptr->SetSizeIsSibling(true);
3926                             N_INCL_indexes.pop_back();
3927                         }
3928                         type = eSymbolTypeScopeEnd;
3929                         break;
3930 
3931                     case N_SOL:
3932                         // #included file name: name,,n_sect,0,address
3933                         type = eSymbolTypeHeaderFile;
3934 
3935                         // We currently don't use the header files on darwin
3936                         add_nlist = false;
3937                         break;
3938 
3939                     case N_PARAMS:
3940                         // compiler parameters: name,,NO_SECT,0,0
3941                         type = eSymbolTypeCompiler;
3942                         break;
3943 
3944                     case N_VERSION:
3945                         // compiler version: name,,NO_SECT,0,0
3946                         type = eSymbolTypeCompiler;
3947                         break;
3948 
3949                     case N_OLEVEL:
3950                         // compiler -O level: name,,NO_SECT,0,0
3951                         type = eSymbolTypeCompiler;
3952                         break;
3953 
3954                     case N_PSYM:
3955                         // parameter: name,,NO_SECT,type,offset
3956                         type = eSymbolTypeVariable;
3957                         break;
3958 
3959                     case N_ENTRY:
3960                         // alternate entry: name,,n_sect,linenumber,address
3961                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3962                         type = eSymbolTypeLineEntry;
3963                         break;
3964 
3965                     //----------------------------------------------------------------------
3966                     // Left and Right Braces
3967                     //----------------------------------------------------------------------
3968                     case N_LBRAC:
3969                         // left bracket: 0,,NO_SECT,nesting level,address
3970                         // We use the current number of symbols in the symbol table in lieu of
3971                         // using nlist_idx in case we ever start trimming entries out
3972                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3973                         N_BRAC_indexes.push_back(sym_idx);
3974                         type = eSymbolTypeScopeBegin;
3975                         break;
3976 
3977                     case N_RBRAC:
3978                         // right bracket: 0,,NO_SECT,nesting level,address
3979                         // Set the size of the N_LBRAC to the terminating index of this N_RBRAC
3980                         // so that we can always skip the entire symbol if we need to navigate
3981                         // more quickly at the source level when parsing STABS
3982                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3983                         if ( !N_BRAC_indexes.empty() )
3984                         {
3985                             symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
3986                             symbol_ptr->SetByteSize(sym_idx + 1);
3987                             symbol_ptr->SetSizeIsSibling(true);
3988                             N_BRAC_indexes.pop_back();
3989                         }
3990                         type = eSymbolTypeScopeEnd;
3991                         break;
3992 
3993                     case N_EXCL:
3994                         // deleted include file: name,,NO_SECT,0,sum
3995                         type = eSymbolTypeHeaderFile;
3996                         break;
3997 
3998                     //----------------------------------------------------------------------
3999                     // COMM scopes
4000                     //----------------------------------------------------------------------
4001                     case N_BCOMM:
4002                         // begin common: name,,NO_SECT,0,0
4003                         // We use the current number of symbols in the symbol table in lieu of
4004                         // using nlist_idx in case we ever start trimming entries out
4005                         type = eSymbolTypeScopeBegin;
4006                         N_COMM_indexes.push_back(sym_idx);
4007                         break;
4008 
4009                     case N_ECOML:
4010                         // end common (local name): 0,,n_sect,0,address
4011                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
4012                         // Fall through
4013 
4014                     case N_ECOMM:
4015                         // end common: name,,n_sect,0,0
4016                         // Set the size of the N_BCOMM to the terminating index of this N_ECOMM/N_ECOML
4017                         // so that we can always skip the entire symbol if we need to navigate
4018                         // more quickly at the source level when parsing STABS
4019                         if ( !N_COMM_indexes.empty() )
4020                         {
4021                             symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
4022                             symbol_ptr->SetByteSize(sym_idx + 1);
4023                             symbol_ptr->SetSizeIsSibling(true);
4024                             N_COMM_indexes.pop_back();
4025                         }
4026                         type = eSymbolTypeScopeEnd;
4027                         break;
4028 
4029                     case N_LENG:
4030                         // second stab entry with length information
4031                         type = eSymbolTypeAdditional;
4032                         break;
4033 
4034                     default: break;
4035                     }
4036                 }
4037                 else
4038                 {
4039                     //uint8_t n_pext    = N_PEXT & nlist.n_type;
4040                     uint8_t n_type  = N_TYPE & nlist.n_type;
4041                     sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4042 
4043                     switch (n_type)
4044                     {
4045                     case N_INDR:
4046                         {
4047                             const char *reexport_name_cstr = strtab_data.PeekCStr(nlist.n_value);
4048                             if (reexport_name_cstr && reexport_name_cstr[0])
4049                             {
4050                                 type = eSymbolTypeReExported;
4051                                 ConstString reexport_name(reexport_name_cstr + ((reexport_name_cstr[0] == '_') ? 1 : 0));
4052                                 sym[sym_idx].SetReExportedSymbolName(reexport_name);
4053                                 set_value = false;
4054                                 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4055                                 indirect_symbol_names.insert(ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4056                             }
4057                             else
4058                                 type = eSymbolTypeUndefined;
4059                         }
4060                         break;
4061 
4062                     case N_UNDF:
4063                         if (symbol_name && symbol_name[0])
4064                         {
4065                             ConstString undefined_name(symbol_name + ((symbol_name[0] == '_') ? 1 : 0));
4066                             undefined_name_to_desc[undefined_name] = nlist.n_desc;
4067                         }
4068                         // Fall through
4069                     case N_PBUD:
4070                         type = eSymbolTypeUndefined;
4071                         break;
4072 
4073                     case N_ABS:
4074                         type = eSymbolTypeAbsolute;
4075                         break;
4076 
4077                     case N_SECT:
4078                         {
4079                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
4080 
4081                             if (!symbol_section)
4082                             {
4083                                 // TODO: warn about this?
4084                                 add_nlist = false;
4085                                 break;
4086                             }
4087 
4088                             if (TEXT_eh_frame_sectID == nlist.n_sect)
4089                             {
4090                                 type = eSymbolTypeException;
4091                             }
4092                             else
4093                             {
4094                                 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4095 
4096                                 switch (section_type)
4097                                 {
4098                                 case S_CSTRING_LITERALS:           type = eSymbolTypeData;    break; // section with only literal C strings
4099                                 case S_4BYTE_LITERALS:             type = eSymbolTypeData;    break; // section with only 4 byte literals
4100                                 case S_8BYTE_LITERALS:             type = eSymbolTypeData;    break; // section with only 8 byte literals
4101                                 case S_LITERAL_POINTERS:           type = eSymbolTypeTrampoline; break; // section with only pointers to literals
4102                                 case S_NON_LAZY_SYMBOL_POINTERS:   type = eSymbolTypeTrampoline; break; // section with only non-lazy symbol pointers
4103                                 case S_LAZY_SYMBOL_POINTERS:       type = eSymbolTypeTrampoline; break; // section with only lazy symbol pointers
4104                                 case S_SYMBOL_STUBS:               type = eSymbolTypeTrampoline; break; // section with only symbol stubs, byte size of stub in the reserved2 field
4105                                 case S_MOD_INIT_FUNC_POINTERS:     type = eSymbolTypeCode;    break; // section with only function pointers for initialization
4106                                 case S_MOD_TERM_FUNC_POINTERS:     type = eSymbolTypeCode;    break; // section with only function pointers for termination
4107                                 case S_INTERPOSING:                type = eSymbolTypeTrampoline;  break; // section with only pairs of function pointers for interposing
4108                                 case S_16BYTE_LITERALS:            type = eSymbolTypeData;    break; // section with only 16 byte literals
4109                                 case S_DTRACE_DOF:                 type = eSymbolTypeInstrumentation; break;
4110                                 case S_LAZY_DYLIB_SYMBOL_POINTERS: type = eSymbolTypeTrampoline; break;
4111                                 default:
4112                                     switch (symbol_section->GetType())
4113                                     {
4114                                         case lldb::eSectionTypeCode:
4115                                             type = eSymbolTypeCode;
4116                                             break;
4117                                         case eSectionTypeData:
4118                                         case eSectionTypeDataCString:            // Inlined C string data
4119                                         case eSectionTypeDataCStringPointers:    // Pointers to C string data
4120                                         case eSectionTypeDataSymbolAddress:      // Address of a symbol in the symbol table
4121                                         case eSectionTypeData4:
4122                                         case eSectionTypeData8:
4123                                         case eSectionTypeData16:
4124                                             type = eSymbolTypeData;
4125                                             break;
4126                                         default:
4127                                             break;
4128                                     }
4129                                     break;
4130                                 }
4131 
4132                                 if (type == eSymbolTypeInvalid)
4133                                 {
4134                                     const char *symbol_sect_name = symbol_section->GetName().AsCString();
4135                                     if (symbol_section->IsDescendant (text_section_sp.get()))
4136                                     {
4137                                         if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4138                                                                     S_ATTR_SELF_MODIFYING_CODE |
4139                                                                     S_ATTR_SOME_INSTRUCTIONS))
4140                                             type = eSymbolTypeData;
4141                                         else
4142                                             type = eSymbolTypeCode;
4143                                     }
4144                                     else
4145                                     if (symbol_section->IsDescendant(data_section_sp.get()))
4146                                     {
4147                                         if (symbol_sect_name && ::strstr (symbol_sect_name, "__objc") == symbol_sect_name)
4148                                         {
4149                                             type = eSymbolTypeRuntime;
4150 
4151                                             if (symbol_name &&
4152                                                 symbol_name[0] == '_' &&
4153                                                 symbol_name[1] == 'O' &&
4154                                                 symbol_name[2] == 'B')
4155                                             {
4156                                                 llvm::StringRef symbol_name_ref(symbol_name);
4157                                                 if (symbol_name_ref.startswith(g_objc_v2_prefix_class))
4158                                                 {
4159                                                     symbol_name_non_abi_mangled = symbol_name + 1;
4160                                                     symbol_name = symbol_name + g_objc_v2_prefix_class.size();
4161                                                     type = eSymbolTypeObjCClass;
4162                                                     demangled_is_synthesized = true;
4163                                                 }
4164                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass))
4165                                                 {
4166                                                     symbol_name_non_abi_mangled = symbol_name + 1;
4167                                                     symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
4168                                                     type = eSymbolTypeObjCMetaClass;
4169                                                     demangled_is_synthesized = true;
4170                                                 }
4171                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar))
4172                                                 {
4173                                                     symbol_name_non_abi_mangled = symbol_name + 1;
4174                                                     symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
4175                                                     type = eSymbolTypeObjCIVar;
4176                                                     demangled_is_synthesized = true;
4177                                                 }
4178                                             }
4179                                         }
4180                                         else
4181                                         if (symbol_sect_name && ::strstr (symbol_sect_name, "__gcc_except_tab") == symbol_sect_name)
4182                                         {
4183                                             type = eSymbolTypeException;
4184                                         }
4185                                         else
4186                                         {
4187                                             type = eSymbolTypeData;
4188                                         }
4189                                     }
4190                                     else
4191                                     if (symbol_sect_name && ::strstr (symbol_sect_name, "__IMPORT") == symbol_sect_name)
4192                                     {
4193                                         type = eSymbolTypeTrampoline;
4194                                     }
4195                                     else
4196                                     if (symbol_section->IsDescendant(objc_section_sp.get()))
4197                                     {
4198                                         type = eSymbolTypeRuntime;
4199                                         if (symbol_name && symbol_name[0] == '.')
4200                                         {
4201                                             llvm::StringRef symbol_name_ref(symbol_name);
4202                                             static const llvm::StringRef g_objc_v1_prefix_class (".objc_class_name_");
4203                                             if (symbol_name_ref.startswith(g_objc_v1_prefix_class))
4204                                             {
4205                                                 symbol_name_non_abi_mangled = symbol_name;
4206                                                 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4207                                                 type = eSymbolTypeObjCClass;
4208                                                 demangled_is_synthesized = true;
4209                                             }
4210                                         }
4211                                     }
4212                                 }
4213                             }
4214                         }
4215                         break;
4216                     }
4217                 }
4218 
4219                 if (add_nlist)
4220                 {
4221                     uint64_t symbol_value = nlist.n_value;
4222 
4223                     if (symbol_name_non_abi_mangled)
4224                     {
4225                         sym[sym_idx].GetMangled().SetMangledName (ConstString(symbol_name_non_abi_mangled));
4226                         sym[sym_idx].GetMangled().SetDemangledName (ConstString(symbol_name));
4227                     }
4228                     else
4229                     {
4230                         bool symbol_name_is_mangled = false;
4231 
4232                         if (symbol_name && symbol_name[0] == '_')
4233                         {
4234                             symbol_name_is_mangled = symbol_name[1] == '_';
4235                             symbol_name++;  // Skip the leading underscore
4236                         }
4237 
4238                         if (symbol_name)
4239                         {
4240                             ConstString const_symbol_name(symbol_name);
4241                             sym[sym_idx].GetMangled().SetValue(const_symbol_name, symbol_name_is_mangled);
4242                         }
4243                     }
4244 
4245                     if (is_gsym)
4246                     {
4247                         const char *gsym_name = sym[sym_idx].GetMangled().GetName(lldb::eLanguageTypeUnknown, Mangled::ePreferMangled).GetCString();
4248                         if (gsym_name)
4249                             N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4250                     }
4251 
4252                     if (symbol_section)
4253                     {
4254                         const addr_t section_file_addr = symbol_section->GetFileAddress();
4255                         if (symbol_byte_size == 0 && function_starts_count > 0)
4256                         {
4257                             addr_t symbol_lookup_file_addr = nlist.n_value;
4258                             // Do an exact address match for non-ARM addresses, else get the closest since
4259                             // the symbol might be a thumb symbol which has an address with bit zero set
4260                             FunctionStarts::Entry *func_start_entry = function_starts.FindEntry (symbol_lookup_file_addr, !is_arm);
4261                             if (is_arm && func_start_entry)
4262                             {
4263                                 // Verify that the function start address is the symbol address (ARM)
4264                                 // or the symbol address + 1 (thumb)
4265                                 if (func_start_entry->addr != symbol_lookup_file_addr &&
4266                                     func_start_entry->addr != (symbol_lookup_file_addr + 1))
4267                                 {
4268                                     // Not the right entry, NULL it out...
4269                                     func_start_entry = NULL;
4270                                 }
4271                             }
4272                             if (func_start_entry)
4273                             {
4274                                 func_start_entry->data = true;
4275 
4276                                 addr_t symbol_file_addr = func_start_entry->addr;
4277                                 if (is_arm)
4278                                     symbol_file_addr &= 0xfffffffffffffffeull;
4279 
4280                                 const FunctionStarts::Entry *next_func_start_entry = function_starts.FindNextEntry (func_start_entry);
4281                                 const addr_t section_end_file_addr = section_file_addr + symbol_section->GetByteSize();
4282                                 if (next_func_start_entry)
4283                                 {
4284                                     addr_t next_symbol_file_addr = next_func_start_entry->addr;
4285                                     // Be sure the clear the Thumb address bit when we calculate the size
4286                                     // from the current and next address
4287                                     if (is_arm)
4288                                         next_symbol_file_addr &= 0xfffffffffffffffeull;
4289                                     symbol_byte_size = std::min<lldb::addr_t>(next_symbol_file_addr - symbol_file_addr, section_end_file_addr - symbol_file_addr);
4290                                 }
4291                                 else
4292                                 {
4293                                     symbol_byte_size = section_end_file_addr - symbol_file_addr;
4294                                 }
4295                             }
4296                         }
4297                         symbol_value -= section_file_addr;
4298                     }
4299 
4300                     if (is_debug == false)
4301                     {
4302                         if (type == eSymbolTypeCode)
4303                         {
4304                             // See if we can find a N_FUN entry for any code symbols.
4305                             // If we do find a match, and the name matches, then we
4306                             // can merge the two into just the function symbol to avoid
4307                             // duplicate entries in the symbol table
4308                             std::pair<ValueToSymbolIndexMap::const_iterator, ValueToSymbolIndexMap::const_iterator> range;
4309                             range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4310                             if (range.first != range.second)
4311                             {
4312                                 bool found_it = false;
4313                                 for (ValueToSymbolIndexMap::const_iterator pos = range.first; pos != range.second; ++pos)
4314                                 {
4315                                     if (sym[sym_idx].GetMangled().GetName(lldb::eLanguageTypeUnknown, Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(lldb::eLanguageTypeUnknown, Mangled::ePreferMangled))
4316                                     {
4317                                         m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4318                                         // We just need the flags from the linker symbol, so put these flags
4319                                         // into the N_FUN flags to avoid duplicate symbols in the symbol table
4320                                         sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4321                                         sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
4322                                         if (resolver_addresses.find(nlist.n_value) != resolver_addresses.end())
4323                                             sym[pos->second].SetType (eSymbolTypeResolver);
4324                                         sym[sym_idx].Clear();
4325                                         found_it = true;
4326                                         break;
4327                                     }
4328                                 }
4329                                 if (found_it)
4330                                     continue;
4331                             }
4332                             else
4333                             {
4334                                 if (resolver_addresses.find(nlist.n_value) != resolver_addresses.end())
4335                                     type = eSymbolTypeResolver;
4336                             }
4337                         }
4338                         else if (type == eSymbolTypeData          ||
4339                                  type == eSymbolTypeObjCClass     ||
4340                                  type == eSymbolTypeObjCMetaClass ||
4341                                  type == eSymbolTypeObjCIVar      )
4342                         {
4343                             // See if we can find a N_STSYM entry for any data symbols.
4344                             // If we do find a match, and the name matches, then we
4345                             // can merge the two into just the Static symbol to avoid
4346                             // duplicate entries in the symbol table
4347                             std::pair<ValueToSymbolIndexMap::const_iterator, ValueToSymbolIndexMap::const_iterator> range;
4348                             range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4349                             if (range.first != range.second)
4350                             {
4351                                 bool found_it = false;
4352                                 for (ValueToSymbolIndexMap::const_iterator pos = range.first; pos != range.second; ++pos)
4353                                 {
4354                                     if (sym[sym_idx].GetMangled().GetName(lldb::eLanguageTypeUnknown, Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(lldb::eLanguageTypeUnknown, Mangled::ePreferMangled))
4355                                     {
4356                                         m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4357                                         // We just need the flags from the linker symbol, so put these flags
4358                                         // into the N_STSYM flags to avoid duplicate symbols in the symbol table
4359                                         sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4360                                         sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
4361                                         sym[sym_idx].Clear();
4362                                         found_it = true;
4363                                         break;
4364                                     }
4365                                 }
4366                                 if (found_it)
4367                                     continue;
4368                             }
4369                             else
4370                             {
4371                                 // Combine N_GSYM stab entries with the non stab symbol
4372                                 const char *gsym_name = sym[sym_idx].GetMangled().GetName(lldb::eLanguageTypeUnknown, Mangled::ePreferMangled).GetCString();
4373                                 if (gsym_name)
4374                                 {
4375                                     ConstNameToSymbolIndexMap::const_iterator pos = N_GSYM_name_to_sym_idx.find(gsym_name);
4376                                     if (pos != N_GSYM_name_to_sym_idx.end())
4377                                     {
4378                                         const uint32_t GSYM_sym_idx = pos->second;
4379                                         m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
4380                                         // Copy the address, because often the N_GSYM address has an invalid address of zero
4381                                         // when the global is a common symbol
4382                                         sym[GSYM_sym_idx].GetAddressRef().SetSection (symbol_section);
4383                                         sym[GSYM_sym_idx].GetAddressRef().SetOffset (symbol_value);
4384                                         // We just need the flags from the linker symbol, so put these flags
4385                                         // into the N_GSYM flags to avoid duplicate symbols in the symbol table
4386                                         sym[GSYM_sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
4387                                         sym[sym_idx].Clear();
4388                                         continue;
4389                                     }
4390                                 }
4391                             }
4392                         }
4393                     }
4394 
4395                     sym[sym_idx].SetID (nlist_idx);
4396                     sym[sym_idx].SetType (type);
4397                     if (set_value)
4398                     {
4399                         sym[sym_idx].GetAddressRef().SetSection (symbol_section);
4400                         sym[sym_idx].GetAddressRef().SetOffset (symbol_value);
4401                     }
4402                     sym[sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
4403 
4404                     if (symbol_byte_size > 0)
4405                         sym[sym_idx].SetByteSize(symbol_byte_size);
4406 
4407                     if (demangled_is_synthesized)
4408                         sym[sym_idx].SetDemangledNameIsSynthesized(true);
4409 
4410                     ++sym_idx;
4411                 }
4412                 else
4413                 {
4414                     sym[sym_idx].Clear();
4415                 }
4416             }
4417 
4418             for (const auto &pos :reexport_shlib_needs_fixup)
4419             {
4420                 const auto undef_pos = undefined_name_to_desc.find(pos.second);
4421                 if (undef_pos != undefined_name_to_desc.end())
4422                 {
4423                     const uint8_t dylib_ordinal = llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4424                     if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4425                         sym[pos.first].SetReExportedSymbolSharedLibrary(dylib_files.GetFileSpecAtIndex(dylib_ordinal-1));
4426                 }
4427             }
4428 
4429         }
4430 
4431         uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4432 
4433         if (function_starts_count > 0)
4434         {
4435             char synthetic_function_symbol[PATH_MAX];
4436             uint32_t num_synthetic_function_symbols = 0;
4437             for (i=0; i<function_starts_count; ++i)
4438             {
4439                 if (function_starts.GetEntryRef (i).data == false)
4440                     ++num_synthetic_function_symbols;
4441             }
4442 
4443             if (num_synthetic_function_symbols > 0)
4444             {
4445                 if (num_syms < sym_idx + num_synthetic_function_symbols)
4446                 {
4447                     num_syms = sym_idx + num_synthetic_function_symbols;
4448                     sym = symtab->Resize (num_syms);
4449                 }
4450                 uint32_t synthetic_function_symbol_idx = 0;
4451                 for (i=0; i<function_starts_count; ++i)
4452                 {
4453                     const FunctionStarts::Entry *func_start_entry = function_starts.GetEntryAtIndex (i);
4454                     if (func_start_entry->data == false)
4455                     {
4456                         addr_t symbol_file_addr = func_start_entry->addr;
4457                         uint32_t symbol_flags = 0;
4458                         if (is_arm)
4459                         {
4460                             if (symbol_file_addr & 1)
4461                                 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4462                             symbol_file_addr &= 0xfffffffffffffffeull;
4463                         }
4464                         Address symbol_addr;
4465                         if (module_sp->ResolveFileAddress (symbol_file_addr, symbol_addr))
4466                         {
4467                             SectionSP symbol_section (symbol_addr.GetSection());
4468                             uint32_t symbol_byte_size = 0;
4469                             if (symbol_section)
4470                             {
4471                                 const addr_t section_file_addr = symbol_section->GetFileAddress();
4472                                 const FunctionStarts::Entry *next_func_start_entry = function_starts.FindNextEntry (func_start_entry);
4473                                 const addr_t section_end_file_addr = section_file_addr + symbol_section->GetByteSize();
4474                                 if (next_func_start_entry)
4475                                 {
4476                                     addr_t next_symbol_file_addr = next_func_start_entry->addr;
4477                                     if (is_arm)
4478                                         next_symbol_file_addr &= 0xfffffffffffffffeull;
4479                                     symbol_byte_size = std::min<lldb::addr_t>(next_symbol_file_addr - symbol_file_addr, section_end_file_addr - symbol_file_addr);
4480                                 }
4481                                 else
4482                                 {
4483                                     symbol_byte_size = section_end_file_addr - symbol_file_addr;
4484                                 }
4485                                 snprintf (synthetic_function_symbol,
4486                                           sizeof(synthetic_function_symbol),
4487                                           "___lldb_unnamed_function%u$$%s",
4488                                           ++synthetic_function_symbol_idx,
4489                                           module_sp->GetFileSpec().GetFilename().GetCString());
4490                                 sym[sym_idx].SetID (synthetic_sym_id++);
4491                                 sym[sym_idx].GetMangled().SetDemangledName(ConstString(synthetic_function_symbol));
4492                                 sym[sym_idx].SetType (eSymbolTypeCode);
4493                                 sym[sym_idx].SetIsSynthetic (true);
4494                                 sym[sym_idx].GetAddressRef() = symbol_addr;
4495                                 if (symbol_flags)
4496                                     sym[sym_idx].SetFlags (symbol_flags);
4497                                 if (symbol_byte_size)
4498                                     sym[sym_idx].SetByteSize (symbol_byte_size);
4499                                 ++sym_idx;
4500                             }
4501                         }
4502                     }
4503                 }
4504             }
4505         }
4506 
4507         // Trim our symbols down to just what we ended up with after
4508         // removing any symbols.
4509         if (sym_idx < num_syms)
4510         {
4511             num_syms = sym_idx;
4512             sym = symtab->Resize (num_syms);
4513         }
4514 
4515         // Now synthesize indirect symbols
4516         if (m_dysymtab.nindirectsyms != 0)
4517         {
4518             if (indirect_symbol_index_data.GetByteSize())
4519             {
4520                 NListIndexToSymbolIndexMap::const_iterator end_index_pos = m_nlist_idx_to_sym_idx.end();
4521 
4522                 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size(); ++sect_idx)
4523                 {
4524                     if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) == S_SYMBOL_STUBS)
4525                     {
4526                         uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2;
4527                         if (symbol_stub_byte_size == 0)
4528                             continue;
4529 
4530                         const uint32_t num_symbol_stubs = m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4531 
4532                         if (num_symbol_stubs == 0)
4533                             continue;
4534 
4535                         const uint32_t symbol_stub_index_offset = m_mach_sections[sect_idx].reserved1;
4536                         for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx)
4537                         {
4538                             const uint32_t symbol_stub_index = symbol_stub_index_offset + stub_idx;
4539                             const lldb::addr_t symbol_stub_addr = m_mach_sections[sect_idx].addr + (stub_idx * symbol_stub_byte_size);
4540                             lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4541                             if (indirect_symbol_index_data.ValidOffsetForDataOfSize(symbol_stub_offset, 4))
4542                             {
4543                                 const uint32_t stub_sym_id = indirect_symbol_index_data.GetU32 (&symbol_stub_offset);
4544                                 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4545                                     continue;
4546 
4547                                 NListIndexToSymbolIndexMap::const_iterator index_pos = m_nlist_idx_to_sym_idx.find (stub_sym_id);
4548                                 Symbol *stub_symbol = NULL;
4549                                 if (index_pos != end_index_pos)
4550                                 {
4551                                     // We have a remapping from the original nlist index to
4552                                     // a current symbol index, so just look this up by index
4553                                     stub_symbol = symtab->SymbolAtIndex (index_pos->second);
4554                                 }
4555                                 else
4556                                 {
4557                                     // We need to lookup a symbol using the original nlist
4558                                     // symbol index since this index is coming from the
4559                                     // S_SYMBOL_STUBS
4560                                     stub_symbol = symtab->FindSymbolByID (stub_sym_id);
4561                                 }
4562 
4563                                 if (stub_symbol)
4564                                 {
4565                                     Address so_addr(symbol_stub_addr, section_list);
4566 
4567                                     if (stub_symbol->GetType() == eSymbolTypeUndefined)
4568                                     {
4569                                         // Change the external symbol into a trampoline that makes sense
4570                                         // These symbols were N_UNDF N_EXT, and are useless to us, so we
4571                                         // can re-use them so we don't have to make up a synthetic symbol
4572                                         // for no good reason.
4573                                         if (resolver_addresses.find(symbol_stub_addr) == resolver_addresses.end())
4574                                             stub_symbol->SetType (eSymbolTypeTrampoline);
4575                                         else
4576                                             stub_symbol->SetType (eSymbolTypeResolver);
4577                                         stub_symbol->SetExternal (false);
4578                                         stub_symbol->GetAddressRef() = so_addr;
4579                                         stub_symbol->SetByteSize (symbol_stub_byte_size);
4580                                     }
4581                                     else
4582                                     {
4583                                         // Make a synthetic symbol to describe the trampoline stub
4584                                         Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4585                                         if (sym_idx >= num_syms)
4586                                         {
4587                                             sym = symtab->Resize (++num_syms);
4588                                             stub_symbol = NULL;  // this pointer no longer valid
4589                                         }
4590                                         sym[sym_idx].SetID (synthetic_sym_id++);
4591                                         sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4592                                         if (resolver_addresses.find(symbol_stub_addr) == resolver_addresses.end())
4593                                             sym[sym_idx].SetType (eSymbolTypeTrampoline);
4594                                         else
4595                                             sym[sym_idx].SetType (eSymbolTypeResolver);
4596                                         sym[sym_idx].SetIsSynthetic (true);
4597                                         sym[sym_idx].GetAddressRef() = so_addr;
4598                                         sym[sym_idx].SetByteSize (symbol_stub_byte_size);
4599                                         ++sym_idx;
4600                                     }
4601                                 }
4602                                 else
4603                                 {
4604                                     if (log)
4605                                         log->Warning ("symbol stub referencing symbol table symbol %u that isn't in our minimal symbol table, fix this!!!", stub_sym_id);
4606                                 }
4607                             }
4608                         }
4609                     }
4610                 }
4611             }
4612         }
4613 
4614 
4615         if (!trie_entries.empty())
4616         {
4617             for (const auto &e : trie_entries)
4618             {
4619                 if (e.entry.import_name)
4620                 {
4621                     // Only add indirect symbols from the Trie entries if we
4622                     // didn't have a N_INDR nlist entry for this already
4623                     if (indirect_symbol_names.find(e.entry.name) == indirect_symbol_names.end())
4624                     {
4625                         // Make a synthetic symbol to describe re-exported symbol.
4626                         if (sym_idx >= num_syms)
4627                             sym = symtab->Resize (++num_syms);
4628                         sym[sym_idx].SetID (synthetic_sym_id++);
4629                         sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4630                         sym[sym_idx].SetType (eSymbolTypeReExported);
4631                         sym[sym_idx].SetIsSynthetic (true);
4632                         sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4633                         if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize())
4634                         {
4635                             sym[sym_idx].SetReExportedSymbolSharedLibrary(dylib_files.GetFileSpecAtIndex(e.entry.other-1));
4636                         }
4637                         ++sym_idx;
4638                     }
4639                 }
4640             }
4641         }
4642 
4643 
4644 
4645 //        StreamFile s(stdout, false);
4646 //        s.Printf ("Symbol table before CalculateSymbolSizes():\n");
4647 //        symtab->Dump(&s, NULL, eSortOrderNone);
4648         // Set symbol byte sizes correctly since mach-o nlist entries don't have sizes
4649         symtab->CalculateSymbolSizes();
4650 
4651 //        s.Printf ("Symbol table after CalculateSymbolSizes():\n");
4652 //        symtab->Dump(&s, NULL, eSortOrderNone);
4653 
4654         return symtab->GetNumSymbols();
4655     }
4656     return 0;
4657 }
4658 
4659 
4660 void
4661 ObjectFileMachO::Dump (Stream *s)
4662 {
4663     ModuleSP module_sp(GetModule());
4664     if (module_sp)
4665     {
4666         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4667         s->Printf("%p: ", static_cast<void*>(this));
4668         s->Indent();
4669         if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4670             s->PutCString("ObjectFileMachO64");
4671         else
4672             s->PutCString("ObjectFileMachO32");
4673 
4674         ArchSpec header_arch;
4675         GetArchitecture(header_arch);
4676 
4677         *s << ", file = '" << m_file << "', arch = " << header_arch.GetArchitectureName() << "\n";
4678 
4679         SectionList *sections = GetSectionList();
4680         if (sections)
4681             sections->Dump(s, NULL, true, UINT32_MAX);
4682 
4683         if (m_symtab_ap.get())
4684             m_symtab_ap->Dump(s, NULL, eSortOrderNone);
4685     }
4686 }
4687 
4688 bool
4689 ObjectFileMachO::GetUUID (const llvm::MachO::mach_header &header,
4690                           const lldb_private::DataExtractor &data,
4691                           lldb::offset_t lc_offset,
4692                           lldb_private::UUID& uuid)
4693 {
4694     uint32_t i;
4695     struct uuid_command load_cmd;
4696 
4697     lldb::offset_t offset = lc_offset;
4698     for (i=0; i<header.ncmds; ++i)
4699     {
4700         const lldb::offset_t cmd_offset = offset;
4701         if (data.GetU32(&offset, &load_cmd, 2) == NULL)
4702             break;
4703 
4704         if (load_cmd.cmd == LC_UUID)
4705         {
4706             const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4707 
4708             if (uuid_bytes)
4709             {
4710                 // OpenCL on Mac OS X uses the same UUID for each of its object files.
4711                 // We pretend these object files have no UUID to prevent crashing.
4712 
4713                 const uint8_t opencl_uuid[] = { 0x8c, 0x8e, 0xb3, 0x9b,
4714                     0x3b, 0xa8,
4715                     0x4b, 0x16,
4716                     0xb6, 0xa4,
4717                     0x27, 0x63, 0xbb, 0x14, 0xf0, 0x0d };
4718 
4719                 if (!memcmp(uuid_bytes, opencl_uuid, 16))
4720                     return false;
4721 
4722                 uuid.SetBytes (uuid_bytes);
4723                 return true;
4724             }
4725             return false;
4726         }
4727         offset = cmd_offset + load_cmd.cmdsize;
4728     }
4729     return false;
4730 }
4731 
4732 
4733 bool
4734 ObjectFileMachO::GetArchitecture (const llvm::MachO::mach_header &header,
4735                                   const lldb_private::DataExtractor &data,
4736                                   lldb::offset_t lc_offset,
4737                                   ArchSpec &arch)
4738 {
4739     arch.SetArchitecture (eArchTypeMachO, header.cputype, header.cpusubtype);
4740 
4741     if (arch.IsValid())
4742     {
4743         llvm::Triple &triple = arch.GetTriple();
4744         if (header.filetype == MH_PRELOAD)
4745         {
4746             // Set OS to "unknown" - this is a standalone binary with no dyld et al
4747             triple.setOS(llvm::Triple::UnknownOS);
4748             return true;
4749         }
4750         else
4751         {
4752             struct load_command load_cmd;
4753 
4754             lldb::offset_t offset = lc_offset;
4755             for (uint32_t i=0; i<header.ncmds; ++i)
4756             {
4757                 const lldb::offset_t cmd_offset = offset;
4758                 if (data.GetU32(&offset, &load_cmd, 2) == NULL)
4759                     break;
4760 
4761                 switch (load_cmd.cmd)
4762                 {
4763                     case LC_VERSION_MIN_IPHONEOS:
4764                         triple.setOS (llvm::Triple::IOS);
4765                         return true;
4766 
4767                     case LC_VERSION_MIN_MACOSX:
4768                         triple.setOS (llvm::Triple::MacOSX);
4769                         return true;
4770 
4771                     default:
4772                         break;
4773                 }
4774 
4775                 offset = cmd_offset + load_cmd.cmdsize;
4776             }
4777 
4778             // Only set the OS to iOS for ARM, we don't want to set it for x86 and x86_64.
4779             // We do this because we now have MacOSX or iOS as the OS value for x86 and
4780             // x86_64 for normal desktop (MacOSX) and simulator (iOS) binaries. And if
4781             // we compare a "x86_64-apple-ios" to a "x86_64-apple-" triple, it will say
4782             // it is compatible (because the OS is unspecified in the second one and will
4783             // match anything in the first
4784             if (header.cputype == CPU_TYPE_ARM || header.cputype == CPU_TYPE_ARM64)
4785                 triple.setOS (llvm::Triple::IOS);
4786         }
4787     }
4788     return arch.IsValid();
4789 }
4790 
4791 bool
4792 ObjectFileMachO::GetUUID (lldb_private::UUID* uuid)
4793 {
4794     ModuleSP module_sp(GetModule());
4795     if (module_sp)
4796     {
4797         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4798         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4799         return GetUUID (m_header, m_data, offset, *uuid);
4800     }
4801     return false;
4802 }
4803 
4804 
4805 uint32_t
4806 ObjectFileMachO::GetDependentModules (FileSpecList& files)
4807 {
4808     uint32_t count = 0;
4809     ModuleSP module_sp(GetModule());
4810     if (module_sp)
4811     {
4812         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4813         struct load_command load_cmd;
4814         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4815         std::vector<std::string> rpath_paths;
4816         std::vector<std::string> rpath_relative_paths;
4817         const bool resolve_path = false; // Don't resolve the dependent file paths since they may not reside on this system
4818         uint32_t i;
4819         for (i=0; i<m_header.ncmds; ++i)
4820         {
4821             const uint32_t cmd_offset = offset;
4822             if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
4823                 break;
4824 
4825             switch (load_cmd.cmd)
4826             {
4827             case LC_RPATH:
4828             case LC_LOAD_DYLIB:
4829             case LC_LOAD_WEAK_DYLIB:
4830             case LC_REEXPORT_DYLIB:
4831             case LC_LOAD_DYLINKER:
4832             case LC_LOADFVMLIB:
4833             case LC_LOAD_UPWARD_DYLIB:
4834                 {
4835                     uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
4836                     const char *path = m_data.PeekCStr(name_offset);
4837                     if (path)
4838                     {
4839                         if (load_cmd.cmd == LC_RPATH)
4840                             rpath_paths.push_back(path);
4841                         else
4842                         {
4843                             if (path[0] == '@')
4844                             {
4845                                 if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
4846                                     rpath_relative_paths.push_back(path + strlen("@rpath"));
4847                             }
4848                             else
4849                             {
4850                                 FileSpec file_spec(path, resolve_path);
4851                                 if (files.AppendIfUnique(file_spec))
4852                                     count++;
4853                             }
4854                         }
4855                     }
4856                 }
4857                 break;
4858 
4859             default:
4860                 break;
4861             }
4862             offset = cmd_offset + load_cmd.cmdsize;
4863         }
4864 
4865         if (!rpath_paths.empty())
4866         {
4867             // Fixup all LC_RPATH values to be absolute paths
4868             FileSpec this_file_spec(m_file);
4869             this_file_spec.ResolvePath();
4870             std::string loader_path("@loader_path");
4871             std::string executable_path("@executable_path");
4872             for (auto &rpath : rpath_paths)
4873             {
4874                 if (rpath.find(loader_path) == 0)
4875                 {
4876                     rpath.erase(0, loader_path.size());
4877                     rpath.insert(0, this_file_spec.GetDirectory().GetCString());
4878                 }
4879                 else if (rpath.find(executable_path) == 0)
4880                 {
4881                     rpath.erase(0, executable_path.size());
4882                     rpath.insert(0, this_file_spec.GetDirectory().GetCString());
4883                 }
4884             }
4885 
4886             for (const auto &rpath_relative_path : rpath_relative_paths)
4887             {
4888                 for (const auto &rpath : rpath_paths)
4889                 {
4890                     std::string path = rpath;
4891                     path += rpath_relative_path;
4892                     // It is OK to resolve this path because we must find a file on
4893                     // disk for us to accept it anyway if it is rpath relative.
4894                     FileSpec file_spec(path, true);
4895                     // Remove any redundant parts of the path (like "../foo") since
4896                     // LC_RPATH values often contain "..".
4897                     file_spec.NormalizePath ();
4898                     if (file_spec.Exists() && files.AppendIfUnique(file_spec))
4899                     {
4900                         count++;
4901                         break;
4902                     }
4903                 }
4904             }
4905         }
4906     }
4907     return count;
4908 }
4909 
4910 lldb_private::Address
4911 ObjectFileMachO::GetEntryPointAddress ()
4912 {
4913     // If the object file is not an executable it can't hold the entry point.  m_entry_point_address
4914     // is initialized to an invalid address, so we can just return that.
4915     // If m_entry_point_address is valid it means we've found it already, so return the cached value.
4916 
4917     if (!IsExecutable() || m_entry_point_address.IsValid())
4918         return m_entry_point_address;
4919 
4920     // Otherwise, look for the UnixThread or Thread command.  The data for the Thread command is given in
4921     // /usr/include/mach-o.h, but it is basically:
4922     //
4923     //  uint32_t flavor  - this is the flavor argument you would pass to thread_get_state
4924     //  uint32_t count   - this is the count of longs in the thread state data
4925     //  struct XXX_thread_state state - this is the structure from <machine/thread_status.h> corresponding to the flavor.
4926     //  <repeat this trio>
4927     //
4928     // So we just keep reading the various register flavors till we find the GPR one, then read the PC out of there.
4929     // FIXME: We will need to have a "RegisterContext data provider" class at some point that can get all the registers
4930     // out of data in this form & attach them to a given thread.  That should underlie the MacOS X User process plugin,
4931     // and we'll also need it for the MacOS X Core File process plugin.  When we have that we can also use it here.
4932     //
4933     // For now we hard-code the offsets and flavors we need:
4934     //
4935     //
4936 
4937     ModuleSP module_sp(GetModule());
4938     if (module_sp)
4939     {
4940         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4941         struct load_command load_cmd;
4942         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4943         uint32_t i;
4944         lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
4945         bool done = false;
4946 
4947         for (i=0; i<m_header.ncmds; ++i)
4948         {
4949             const lldb::offset_t cmd_offset = offset;
4950             if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
4951                 break;
4952 
4953             switch (load_cmd.cmd)
4954             {
4955             case LC_UNIXTHREAD:
4956             case LC_THREAD:
4957                 {
4958                     while (offset < cmd_offset + load_cmd.cmdsize)
4959                     {
4960                         uint32_t flavor = m_data.GetU32(&offset);
4961                         uint32_t count = m_data.GetU32(&offset);
4962                         if (count == 0)
4963                         {
4964                             // We've gotten off somehow, log and exit;
4965                             return m_entry_point_address;
4966                         }
4967 
4968                         switch (m_header.cputype)
4969                         {
4970                         case llvm::MachO::CPU_TYPE_ARM:
4971                            if (flavor == 1) // ARM_THREAD_STATE from mach/arm/thread_status.h
4972                            {
4973                                offset += 60;  // This is the offset of pc in the GPR thread state data structure.
4974                                start_address = m_data.GetU32(&offset);
4975                                done = true;
4976                             }
4977                         break;
4978                         case llvm::MachO::CPU_TYPE_ARM64:
4979                            if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
4980                            {
4981                                offset += 256;  // This is the offset of pc in the GPR thread state data structure.
4982                                start_address = m_data.GetU64(&offset);
4983                                done = true;
4984                             }
4985                         break;
4986                         case llvm::MachO::CPU_TYPE_I386:
4987                            if (flavor == 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
4988                            {
4989                                offset += 40;  // This is the offset of eip in the GPR thread state data structure.
4990                                start_address = m_data.GetU32(&offset);
4991                                done = true;
4992                             }
4993                         break;
4994                         case llvm::MachO::CPU_TYPE_X86_64:
4995                            if (flavor == 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
4996                            {
4997                                offset += 16 * 8;  // This is the offset of rip in the GPR thread state data structure.
4998                                start_address = m_data.GetU64(&offset);
4999                                done = true;
5000                             }
5001                         break;
5002                         default:
5003                             return m_entry_point_address;
5004                         }
5005                         // Haven't found the GPR flavor yet, skip over the data for this flavor:
5006                         if (done)
5007                             break;
5008                         offset += count * 4;
5009                     }
5010                 }
5011                 break;
5012             case LC_MAIN:
5013                 {
5014                     ConstString text_segment_name ("__TEXT");
5015                     uint64_t entryoffset = m_data.GetU64(&offset);
5016                     SectionSP text_segment_sp = GetSectionList()->FindSectionByName(text_segment_name);
5017                     if (text_segment_sp)
5018                     {
5019                         done = true;
5020                         start_address = text_segment_sp->GetFileAddress() + entryoffset;
5021                     }
5022                 }
5023 
5024             default:
5025                 break;
5026             }
5027             if (done)
5028                 break;
5029 
5030             // Go to the next load command:
5031             offset = cmd_offset + load_cmd.cmdsize;
5032         }
5033 
5034         if (start_address != LLDB_INVALID_ADDRESS)
5035         {
5036             // We got the start address from the load commands, so now resolve that address in the sections
5037             // of this ObjectFile:
5038             if (!m_entry_point_address.ResolveAddressUsingFileSections (start_address, GetSectionList()))
5039             {
5040                 m_entry_point_address.Clear();
5041             }
5042         }
5043         else
5044         {
5045             // We couldn't read the UnixThread load command - maybe it wasn't there.  As a fallback look for the
5046             // "start" symbol in the main executable.
5047 
5048             ModuleSP module_sp (GetModule());
5049 
5050             if (module_sp)
5051             {
5052                 SymbolContextList contexts;
5053                 SymbolContext context;
5054                 if (module_sp->FindSymbolsWithNameAndType(ConstString ("start"), eSymbolTypeCode, contexts))
5055                 {
5056                     if (contexts.GetContextAtIndex(0, context))
5057                         m_entry_point_address = context.symbol->GetAddress();
5058                 }
5059             }
5060         }
5061     }
5062 
5063     return m_entry_point_address;
5064 
5065 }
5066 
5067 lldb_private::Address
5068 ObjectFileMachO::GetHeaderAddress ()
5069 {
5070     lldb_private::Address header_addr;
5071     SectionList *section_list = GetSectionList();
5072     if (section_list)
5073     {
5074         SectionSP text_segment_sp (section_list->FindSectionByName (GetSegmentNameTEXT()));
5075         if (text_segment_sp)
5076         {
5077             header_addr.SetSection (text_segment_sp);
5078             header_addr.SetOffset (0);
5079         }
5080     }
5081     return header_addr;
5082 }
5083 
5084 uint32_t
5085 ObjectFileMachO::GetNumThreadContexts ()
5086 {
5087     ModuleSP module_sp(GetModule());
5088     if (module_sp)
5089     {
5090         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
5091         if (!m_thread_context_offsets_valid)
5092         {
5093             m_thread_context_offsets_valid = true;
5094             lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5095             FileRangeArray::Entry file_range;
5096             thread_command thread_cmd;
5097             for (uint32_t i=0; i<m_header.ncmds; ++i)
5098             {
5099                 const uint32_t cmd_offset = offset;
5100                 if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL)
5101                     break;
5102 
5103                 if (thread_cmd.cmd == LC_THREAD)
5104                 {
5105                     file_range.SetRangeBase (offset);
5106                     file_range.SetByteSize (thread_cmd.cmdsize - 8);
5107                     m_thread_context_offsets.Append (file_range);
5108                 }
5109                 offset = cmd_offset + thread_cmd.cmdsize;
5110             }
5111         }
5112     }
5113     return m_thread_context_offsets.GetSize();
5114 }
5115 
5116 lldb::RegisterContextSP
5117 ObjectFileMachO::GetThreadContextAtIndex (uint32_t idx, lldb_private::Thread &thread)
5118 {
5119     lldb::RegisterContextSP reg_ctx_sp;
5120 
5121     ModuleSP module_sp(GetModule());
5122     if (module_sp)
5123     {
5124         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
5125         if (!m_thread_context_offsets_valid)
5126             GetNumThreadContexts ();
5127 
5128         const FileRangeArray::Entry *thread_context_file_range = m_thread_context_offsets.GetEntryAtIndex (idx);
5129         if (thread_context_file_range)
5130         {
5131 
5132             DataExtractor data (m_data,
5133                                 thread_context_file_range->GetRangeBase(),
5134                                 thread_context_file_range->GetByteSize());
5135 
5136             switch (m_header.cputype)
5137             {
5138                 case llvm::MachO::CPU_TYPE_ARM64:
5139                     reg_ctx_sp.reset (new RegisterContextDarwin_arm64_Mach (thread, data));
5140                     break;
5141 
5142                 case llvm::MachO::CPU_TYPE_ARM:
5143                     reg_ctx_sp.reset (new RegisterContextDarwin_arm_Mach (thread, data));
5144                     break;
5145 
5146                 case llvm::MachO::CPU_TYPE_I386:
5147                     reg_ctx_sp.reset (new RegisterContextDarwin_i386_Mach (thread, data));
5148                     break;
5149 
5150                 case llvm::MachO::CPU_TYPE_X86_64:
5151                     reg_ctx_sp.reset (new RegisterContextDarwin_x86_64_Mach (thread, data));
5152                     break;
5153             }
5154         }
5155     }
5156     return reg_ctx_sp;
5157 }
5158 
5159 
5160 ObjectFile::Type
5161 ObjectFileMachO::CalculateType()
5162 {
5163     switch (m_header.filetype)
5164     {
5165         case MH_OBJECT:                                         // 0x1u
5166             if (GetAddressByteSize () == 4)
5167             {
5168                 // 32 bit kexts are just object files, but they do have a valid
5169                 // UUID load command.
5170                 UUID uuid;
5171                 if (GetUUID(&uuid))
5172                 {
5173                     // this checking for the UUID load command is not enough
5174                     // we could eventually look for the symbol named
5175                     // "OSKextGetCurrentIdentifier" as this is required of kexts
5176                     if (m_strata == eStrataInvalid)
5177                         m_strata = eStrataKernel;
5178                     return eTypeSharedLibrary;
5179                 }
5180             }
5181             return eTypeObjectFile;
5182 
5183         case MH_EXECUTE:            return eTypeExecutable;     // 0x2u
5184         case MH_FVMLIB:             return eTypeSharedLibrary;  // 0x3u
5185         case MH_CORE:               return eTypeCoreFile;       // 0x4u
5186         case MH_PRELOAD:            return eTypeSharedLibrary;  // 0x5u
5187         case MH_DYLIB:              return eTypeSharedLibrary;  // 0x6u
5188         case MH_DYLINKER:           return eTypeDynamicLinker;  // 0x7u
5189         case MH_BUNDLE:             return eTypeSharedLibrary;  // 0x8u
5190         case MH_DYLIB_STUB:         return eTypeStubLibrary;    // 0x9u
5191         case MH_DSYM:               return eTypeDebugInfo;      // 0xAu
5192         case MH_KEXT_BUNDLE:        return eTypeSharedLibrary;  // 0xBu
5193         default:
5194             break;
5195     }
5196     return eTypeUnknown;
5197 }
5198 
5199 ObjectFile::Strata
5200 ObjectFileMachO::CalculateStrata()
5201 {
5202     switch (m_header.filetype)
5203     {
5204         case MH_OBJECT:                                  // 0x1u
5205             {
5206                 // 32 bit kexts are just object files, but they do have a valid
5207                 // UUID load command.
5208                 UUID uuid;
5209                 if (GetUUID(&uuid))
5210                 {
5211                     // this checking for the UUID load command is not enough
5212                     // we could eventually look for the symbol named
5213                     // "OSKextGetCurrentIdentifier" as this is required of kexts
5214                     if (m_type == eTypeInvalid)
5215                         m_type = eTypeSharedLibrary;
5216 
5217                     return eStrataKernel;
5218                 }
5219             }
5220             return eStrataUnknown;
5221 
5222         case MH_EXECUTE:                                 // 0x2u
5223             // Check for the MH_DYLDLINK bit in the flags
5224             if (m_header.flags & MH_DYLDLINK)
5225             {
5226                 return eStrataUser;
5227             }
5228             else
5229             {
5230                 SectionList *section_list = GetSectionList();
5231                 if (section_list)
5232                 {
5233                     static ConstString g_kld_section_name ("__KLD");
5234                     if (section_list->FindSectionByName(g_kld_section_name))
5235                         return eStrataKernel;
5236                 }
5237             }
5238             return eStrataRawImage;
5239 
5240         case MH_FVMLIB:      return eStrataUser;         // 0x3u
5241         case MH_CORE:        return eStrataUnknown;      // 0x4u
5242         case MH_PRELOAD:     return eStrataRawImage;     // 0x5u
5243         case MH_DYLIB:       return eStrataUser;         // 0x6u
5244         case MH_DYLINKER:    return eStrataUser;         // 0x7u
5245         case MH_BUNDLE:      return eStrataUser;         // 0x8u
5246         case MH_DYLIB_STUB:  return eStrataUser;         // 0x9u
5247         case MH_DSYM:        return eStrataUnknown;      // 0xAu
5248         case MH_KEXT_BUNDLE: return eStrataKernel;       // 0xBu
5249         default:
5250             break;
5251     }
5252     return eStrataUnknown;
5253 }
5254 
5255 
5256 uint32_t
5257 ObjectFileMachO::GetVersion (uint32_t *versions, uint32_t num_versions)
5258 {
5259     ModuleSP module_sp(GetModule());
5260     if (module_sp)
5261     {
5262         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
5263         struct dylib_command load_cmd;
5264         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5265         uint32_t version_cmd = 0;
5266         uint64_t version = 0;
5267         uint32_t i;
5268         for (i=0; i<m_header.ncmds; ++i)
5269         {
5270             const lldb::offset_t cmd_offset = offset;
5271             if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
5272                 break;
5273 
5274             if (load_cmd.cmd == LC_ID_DYLIB)
5275             {
5276                 if (version_cmd == 0)
5277                 {
5278                     version_cmd = load_cmd.cmd;
5279                     if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL)
5280                         break;
5281                     version = load_cmd.dylib.current_version;
5282                 }
5283                 break; // Break for now unless there is another more complete version
5284                        // number load command in the future.
5285             }
5286             offset = cmd_offset + load_cmd.cmdsize;
5287         }
5288 
5289         if (version_cmd == LC_ID_DYLIB)
5290         {
5291             if (versions != NULL && num_versions > 0)
5292             {
5293                 if (num_versions > 0)
5294                     versions[0] = (version & 0xFFFF0000ull) >> 16;
5295                 if (num_versions > 1)
5296                     versions[1] = (version & 0x0000FF00ull) >> 8;
5297                 if (num_versions > 2)
5298                     versions[2] = (version & 0x000000FFull);
5299                 // Fill in an remaining version numbers with invalid values
5300                 for (i=3; i<num_versions; ++i)
5301                     versions[i] = UINT32_MAX;
5302             }
5303             // The LC_ID_DYLIB load command has a version with 3 version numbers
5304             // in it, so always return 3
5305             return 3;
5306         }
5307     }
5308     return false;
5309 }
5310 
5311 bool
5312 ObjectFileMachO::GetArchitecture (ArchSpec &arch)
5313 {
5314     ModuleSP module_sp(GetModule());
5315     if (module_sp)
5316     {
5317         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
5318         return GetArchitecture (m_header, m_data, MachHeaderSizeFromMagic(m_header.magic), arch);
5319     }
5320     return false;
5321 }
5322 
5323 
5324 UUID
5325 ObjectFileMachO::GetProcessSharedCacheUUID (Process *process)
5326 {
5327     UUID uuid;
5328     if (process)
5329     {
5330         addr_t all_image_infos = process->GetImageInfoAddress();
5331 
5332         // The address returned by GetImageInfoAddress may be the address of dyld (don't want)
5333         // or it may be the address of the dyld_all_image_infos structure (want).  The first four
5334         // bytes will be either the version field (all_image_infos) or a Mach-O file magic constant.
5335         // Version 13 and higher of dyld_all_image_infos is required to get the sharedCacheUUID field.
5336 
5337         Error err;
5338         uint32_t version_or_magic = process->ReadUnsignedIntegerFromMemory (all_image_infos, 4, -1, err);
5339         if (version_or_magic != static_cast<uint32_t>(-1)
5340             && version_or_magic != MH_MAGIC
5341             && version_or_magic != MH_CIGAM
5342             && version_or_magic != MH_MAGIC_64
5343             && version_or_magic != MH_CIGAM_64
5344             && version_or_magic >= 13)
5345         {
5346             addr_t sharedCacheUUID_address = LLDB_INVALID_ADDRESS;
5347             int wordsize = process->GetAddressByteSize();
5348             if (wordsize == 8)
5349             {
5350                 sharedCacheUUID_address = all_image_infos + 160;  // sharedCacheUUID <mach-o/dyld_images.h>
5351             }
5352             if (wordsize == 4)
5353             {
5354                 sharedCacheUUID_address = all_image_infos + 84;   // sharedCacheUUID <mach-o/dyld_images.h>
5355             }
5356             if (sharedCacheUUID_address != LLDB_INVALID_ADDRESS)
5357             {
5358                 uuid_t shared_cache_uuid;
5359                 if (process->ReadMemory (sharedCacheUUID_address, shared_cache_uuid, sizeof (uuid_t), err) == sizeof (uuid_t))
5360                 {
5361                     uuid.SetBytes (shared_cache_uuid);
5362                 }
5363             }
5364         }
5365     }
5366     return uuid;
5367 }
5368 
5369 UUID
5370 ObjectFileMachO::GetLLDBSharedCacheUUID ()
5371 {
5372     UUID uuid;
5373 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
5374     uint8_t *(*dyld_get_all_image_infos)(void);
5375     dyld_get_all_image_infos = (uint8_t*(*)()) dlsym (RTLD_DEFAULT, "_dyld_get_all_image_infos");
5376     if (dyld_get_all_image_infos)
5377     {
5378         uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
5379         if (dyld_all_image_infos_address)
5380         {
5381             uint32_t *version = (uint32_t*) dyld_all_image_infos_address;              // version <mach-o/dyld_images.h>
5382             if (*version >= 13)
5383             {
5384                 uuid_t *sharedCacheUUID_address = 0;
5385                 int wordsize = sizeof (uint8_t *);
5386                 if (wordsize == 8)
5387                 {
5388                     sharedCacheUUID_address = (uuid_t*) ((uint8_t*) dyld_all_image_infos_address + 160); // sharedCacheUUID <mach-o/dyld_images.h>
5389                 }
5390                 else
5391                 {
5392                     sharedCacheUUID_address = (uuid_t*) ((uint8_t*) dyld_all_image_infos_address + 84);  // sharedCacheUUID <mach-o/dyld_images.h>
5393                 }
5394                 uuid.SetBytes (sharedCacheUUID_address);
5395             }
5396         }
5397     }
5398 #endif
5399     return uuid;
5400 }
5401 
5402 uint32_t
5403 ObjectFileMachO::GetMinimumOSVersion (uint32_t *versions, uint32_t num_versions)
5404 {
5405     if (m_min_os_versions.empty())
5406     {
5407         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5408         bool success = false;
5409         for (uint32_t i=0; success == false && i < m_header.ncmds; ++i)
5410         {
5411             const lldb::offset_t load_cmd_offset = offset;
5412 
5413             version_min_command lc;
5414             if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5415                 break;
5416             if (lc.cmd == LC_VERSION_MIN_MACOSX || lc.cmd == LC_VERSION_MIN_IPHONEOS)
5417             {
5418                 if (m_data.GetU32 (&offset, &lc.version, (sizeof(lc) / sizeof(uint32_t)) - 2))
5419                 {
5420                     const uint32_t xxxx = lc.version >> 16;
5421                     const uint32_t yy = (lc.version >> 8) & 0xffu;
5422                     const uint32_t zz = lc.version  & 0xffu;
5423                     if (xxxx)
5424                     {
5425                         m_min_os_versions.push_back(xxxx);
5426                         m_min_os_versions.push_back(yy);
5427                         m_min_os_versions.push_back(zz);
5428                     }
5429                     success = true;
5430                 }
5431             }
5432             offset = load_cmd_offset + lc.cmdsize;
5433         }
5434 
5435         if (success == false)
5436         {
5437             // Push an invalid value so we don't keep trying to
5438             m_min_os_versions.push_back(UINT32_MAX);
5439         }
5440     }
5441 
5442     if (m_min_os_versions.size() > 1 || m_min_os_versions[0] != UINT32_MAX)
5443     {
5444         if (versions != NULL && num_versions > 0)
5445         {
5446             for (size_t i=0; i<num_versions; ++i)
5447             {
5448                 if (i < m_min_os_versions.size())
5449                     versions[i] = m_min_os_versions[i];
5450                 else
5451                     versions[i] = 0;
5452             }
5453         }
5454         return m_min_os_versions.size();
5455     }
5456     // Call the superclasses version that will empty out the data
5457     return ObjectFile::GetMinimumOSVersion (versions, num_versions);
5458 }
5459 
5460 uint32_t
5461 ObjectFileMachO::GetSDKVersion(uint32_t *versions, uint32_t num_versions)
5462 {
5463     if (m_sdk_versions.empty())
5464     {
5465         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
5466         bool success = false;
5467         for (uint32_t i=0; success == false && i < m_header.ncmds; ++i)
5468         {
5469             const lldb::offset_t load_cmd_offset = offset;
5470 
5471             version_min_command lc;
5472             if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
5473                 break;
5474             if (lc.cmd == LC_VERSION_MIN_MACOSX || lc.cmd == LC_VERSION_MIN_IPHONEOS)
5475             {
5476                 if (m_data.GetU32 (&offset, &lc.version, (sizeof(lc) / sizeof(uint32_t)) - 2))
5477                 {
5478                     const uint32_t xxxx = lc.sdk >> 16;
5479                     const uint32_t yy = (lc.sdk >> 8) & 0xffu;
5480                     const uint32_t zz = lc.sdk & 0xffu;
5481                     if (xxxx)
5482                     {
5483                         m_sdk_versions.push_back(xxxx);
5484                         m_sdk_versions.push_back(yy);
5485                         m_sdk_versions.push_back(zz);
5486                     }
5487                     success = true;
5488                 }
5489             }
5490             offset = load_cmd_offset + lc.cmdsize;
5491         }
5492 
5493         if (success == false)
5494         {
5495             // Push an invalid value so we don't keep trying to
5496             m_sdk_versions.push_back(UINT32_MAX);
5497         }
5498     }
5499 
5500     if (m_sdk_versions.size() > 1 || m_sdk_versions[0] != UINT32_MAX)
5501     {
5502         if (versions != NULL && num_versions > 0)
5503         {
5504             for (size_t i=0; i<num_versions; ++i)
5505             {
5506                 if (i < m_sdk_versions.size())
5507                     versions[i] = m_sdk_versions[i];
5508                 else
5509                     versions[i] = 0;
5510             }
5511         }
5512         return m_sdk_versions.size();
5513     }
5514     // Call the superclasses version that will empty out the data
5515     return ObjectFile::GetSDKVersion (versions, num_versions);
5516 }
5517 
5518 
5519 bool
5520 ObjectFileMachO::GetIsDynamicLinkEditor()
5521 {
5522     return m_header.filetype == llvm::MachO::MH_DYLINKER;
5523 }
5524 
5525 //------------------------------------------------------------------
5526 // PluginInterface protocol
5527 //------------------------------------------------------------------
5528 lldb_private::ConstString
5529 ObjectFileMachO::GetPluginName()
5530 {
5531     return GetPluginNameStatic();
5532 }
5533 
5534 uint32_t
5535 ObjectFileMachO::GetPluginVersion()
5536 {
5537     return 1;
5538 }
5539 
5540 
5541 Section *
5542 ObjectFileMachO::GetMachHeaderSection()
5543 {
5544     // Find the first address of the mach header which is the first non-zero
5545     // file sized section whose file offset is zero. This is the base file address
5546     // of the mach-o file which can be subtracted from the vmaddr of the other
5547     // segments found in memory and added to the load address
5548     ModuleSP module_sp = GetModule();
5549     if (module_sp)
5550     {
5551         SectionList *section_list = GetSectionList ();
5552         if (section_list)
5553         {
5554             lldb::addr_t mach_base_file_addr = LLDB_INVALID_ADDRESS;
5555             const size_t num_sections = section_list->GetSize();
5556 
5557             for (size_t sect_idx = 0;
5558                  sect_idx < num_sections && mach_base_file_addr == LLDB_INVALID_ADDRESS;
5559                  ++sect_idx)
5560             {
5561                 Section *section = section_list->GetSectionAtIndex (sect_idx).get();
5562                 if (section &&
5563                     section->GetFileSize() > 0 &&
5564                     section->GetFileOffset() == 0 &&
5565                     section->IsThreadSpecific() == false &&
5566                     module_sp.get() == section->GetModule().get())
5567                 {
5568                     return section;
5569                 }
5570             }
5571         }
5572     }
5573     return nullptr;
5574 }
5575 
5576 lldb::addr_t
5577 ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage(lldb::addr_t mach_header_load_address, const Section *mach_header_section, const Section *section)
5578 {
5579     ModuleSP module_sp = GetModule();
5580     if (module_sp && mach_header_section && section && mach_header_load_address != LLDB_INVALID_ADDRESS)
5581     {
5582         lldb::addr_t mach_header_file_addr = mach_header_section->GetFileAddress();
5583         if (mach_header_file_addr != LLDB_INVALID_ADDRESS)
5584         {
5585             if (section &&
5586                 section->GetFileSize() > 0 &&
5587                 section->IsThreadSpecific() == false &&
5588                 module_sp.get() == section->GetModule().get())
5589             {
5590                 // Ignore __LINKEDIT and __DWARF segments
5591                 if (section->GetName() == GetSegmentNameLINKEDIT())
5592                 {
5593                     // Only map __LINKEDIT if we have an in memory image and this isn't
5594                     // a kernel binary like a kext or mach_kernel.
5595                     const bool is_memory_image = (bool)m_process_wp.lock();
5596                     const Strata strata = GetStrata();
5597                     if (is_memory_image == false || strata == eStrataKernel)
5598                         return LLDB_INVALID_ADDRESS;
5599                 }
5600                 return section->GetFileAddress() - mach_header_file_addr + mach_header_load_address;
5601             }
5602         }
5603     }
5604     return LLDB_INVALID_ADDRESS;
5605 }
5606 
5607 bool
5608 ObjectFileMachO::SetLoadAddress (Target &target,
5609                                  lldb::addr_t value,
5610                                  bool value_is_offset)
5611 {
5612     ModuleSP module_sp = GetModule();
5613     if (module_sp)
5614     {
5615         size_t num_loaded_sections = 0;
5616         SectionList *section_list = GetSectionList ();
5617         if (section_list)
5618         {
5619             const size_t num_sections = section_list->GetSize();
5620 
5621             if (value_is_offset)
5622             {
5623                 // "value" is an offset to apply to each top level segment
5624                 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx)
5625                 {
5626                     // Iterate through the object file sections to find all
5627                     // of the sections that size on disk (to avoid __PAGEZERO)
5628                     // and load them
5629                     SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
5630                     if (section_sp &&
5631                         section_sp->GetFileSize() > 0 &&
5632                         section_sp->IsThreadSpecific() == false &&
5633                         module_sp.get() == section_sp->GetModule().get())
5634                     {
5635                         // Ignore __LINKEDIT and __DWARF segments
5636                         if (section_sp->GetName() == GetSegmentNameLINKEDIT())
5637                         {
5638                             // Only map __LINKEDIT if we have an in memory image and this isn't
5639                             // a kernel binary like a kext or mach_kernel.
5640                             const bool is_memory_image = (bool)m_process_wp.lock();
5641                             const Strata strata = GetStrata();
5642                             if (is_memory_image == false || strata == eStrataKernel)
5643                                 continue;
5644                         }
5645                         if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() + value))
5646                             ++num_loaded_sections;
5647                     }
5648                 }
5649             }
5650             else
5651             {
5652                 // "value" is the new base address of the mach_header, adjust each
5653                 // section accordingly
5654 
5655                 Section *mach_header_section = GetMachHeaderSection();
5656                 if (mach_header_section)
5657                 {
5658                     for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx)
5659                     {
5660                         SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
5661 
5662                         lldb::addr_t section_load_addr = CalculateSectionLoadAddressForMemoryImage(value, mach_header_section, section_sp.get());
5663                         if (section_load_addr != LLDB_INVALID_ADDRESS)
5664                         {
5665                             if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_load_addr))
5666                                 ++num_loaded_sections;
5667                         }
5668                     }
5669                 }
5670             }
5671         }
5672         return num_loaded_sections > 0;
5673     }
5674     return false;
5675 }
5676 
5677 bool
5678 ObjectFileMachO::SaveCore (const lldb::ProcessSP &process_sp,
5679                            const FileSpec &outfile,
5680                            Error &error)
5681 {
5682     if (process_sp)
5683     {
5684         Target &target = process_sp->GetTarget();
5685         const ArchSpec target_arch = target.GetArchitecture();
5686         const llvm::Triple &target_triple = target_arch.GetTriple();
5687         if (target_triple.getVendor() == llvm::Triple::Apple &&
5688             (target_triple.getOS() == llvm::Triple::MacOSX ||
5689              target_triple.getOS() == llvm::Triple::IOS))
5690         {
5691             bool make_core = false;
5692             switch (target_arch.GetMachine())
5693             {
5694                 case llvm::Triple::aarch64:
5695                 case llvm::Triple::arm:
5696                 case llvm::Triple::x86:
5697                 case llvm::Triple::x86_64:
5698                     make_core = true;
5699                     break;
5700                 default:
5701                     error.SetErrorStringWithFormat ("unsupported core architecture: %s", target_triple.str().c_str());
5702                     break;
5703             }
5704 
5705             if (make_core)
5706             {
5707                 std::vector<segment_command_64> segment_load_commands;
5708 //                uint32_t range_info_idx = 0;
5709                 MemoryRegionInfo range_info;
5710                 Error range_error = process_sp->GetMemoryRegionInfo(0, range_info);
5711                 const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
5712                 const ByteOrder byte_order = target_arch.GetByteOrder();
5713                 if (range_error.Success())
5714                 {
5715                     while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS)
5716                     {
5717                         const addr_t addr = range_info.GetRange().GetRangeBase();
5718                         const addr_t size = range_info.GetRange().GetByteSize();
5719 
5720                         if (size == 0)
5721                             break;
5722 
5723                         // Calculate correct protections
5724                         uint32_t prot = 0;
5725                         if (range_info.GetReadable() == MemoryRegionInfo::eYes)
5726                             prot |= VM_PROT_READ;
5727                         if (range_info.GetWritable() == MemoryRegionInfo::eYes)
5728                             prot |= VM_PROT_WRITE;
5729                         if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
5730                             prot |= VM_PROT_EXECUTE;
5731 
5732 //                        printf ("[%3u] [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") %c%c%c\n",
5733 //                                range_info_idx,
5734 //                                addr,
5735 //                                size,
5736 //                                (prot & VM_PROT_READ   ) ? 'r' : '-',
5737 //                                (prot & VM_PROT_WRITE  ) ? 'w' : '-',
5738 //                                (prot & VM_PROT_EXECUTE) ? 'x' : '-');
5739 
5740                         if (prot != 0)
5741                         {
5742                             uint32_t cmd_type = LC_SEGMENT_64;
5743                             uint32_t segment_size = sizeof (segment_command_64);
5744                             if (addr_byte_size == 4)
5745                             {
5746                                 cmd_type = LC_SEGMENT;
5747                                 segment_size = sizeof (segment_command);
5748                             }
5749                             segment_command_64 segment = {
5750                                 cmd_type,           // uint32_t cmd;
5751                                 segment_size,       // uint32_t cmdsize;
5752                                 {0},                // char segname[16];
5753                                 addr,               // uint64_t vmaddr;    // uint32_t for 32-bit Mach-O
5754                                 size,               // uint64_t vmsize;    // uint32_t for 32-bit Mach-O
5755                                 0,                  // uint64_t fileoff;   // uint32_t for 32-bit Mach-O
5756                                 size,               // uint64_t filesize;  // uint32_t for 32-bit Mach-O
5757                                 prot,               // uint32_t maxprot;
5758                                 prot,               // uint32_t initprot;
5759                                 0,                  // uint32_t nsects;
5760                                 0 };                // uint32_t flags;
5761                             segment_load_commands.push_back(segment);
5762                         }
5763                         else
5764                         {
5765                             // No protections and a size of 1 used to be returned from old
5766                             // debugservers when we asked about a region that was past the
5767                             // last memory region and it indicates the end...
5768                             if (size == 1)
5769                                 break;
5770                         }
5771 
5772                         range_error = process_sp->GetMemoryRegionInfo(range_info.GetRange().GetRangeEnd(), range_info);
5773                         if (range_error.Fail())
5774                             break;
5775                     }
5776 
5777                     StreamString buffer (Stream::eBinary,
5778                                          addr_byte_size,
5779                                          byte_order);
5780 
5781                     mach_header_64 mach_header;
5782                     if (addr_byte_size == 8)
5783                     {
5784                         mach_header.magic = MH_MAGIC_64;
5785                     }
5786                     else
5787                     {
5788                         mach_header.magic = MH_MAGIC;
5789                     }
5790                     mach_header.cputype = target_arch.GetMachOCPUType();
5791                     mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
5792                     mach_header.filetype = MH_CORE;
5793                     mach_header.ncmds = segment_load_commands.size();
5794                     mach_header.flags = 0;
5795                     mach_header.reserved = 0;
5796                     ThreadList &thread_list = process_sp->GetThreadList();
5797                     const uint32_t num_threads = thread_list.GetSize();
5798 
5799                     // Make an array of LC_THREAD data items. Each one contains
5800                     // the contents of the LC_THREAD load command. The data doesn't
5801                     // contain the load command + load command size, we will
5802                     // add the load command and load command size as we emit the data.
5803                     std::vector<StreamString> LC_THREAD_datas(num_threads);
5804                     for (auto &LC_THREAD_data : LC_THREAD_datas)
5805                     {
5806                         LC_THREAD_data.GetFlags().Set(Stream::eBinary);
5807                         LC_THREAD_data.SetAddressByteSize(addr_byte_size);
5808                         LC_THREAD_data.SetByteOrder(byte_order);
5809                     }
5810                     for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx)
5811                     {
5812                         ThreadSP thread_sp (thread_list.GetThreadAtIndex(thread_idx));
5813                         if (thread_sp)
5814                         {
5815                             switch (mach_header.cputype)
5816                             {
5817                                 case llvm::MachO::CPU_TYPE_ARM64:
5818                                     RegisterContextDarwin_arm64_Mach::Create_LC_THREAD (thread_sp.get(), LC_THREAD_datas[thread_idx]);
5819                                     break;
5820 
5821                                 case llvm::MachO::CPU_TYPE_ARM:
5822                                     RegisterContextDarwin_arm_Mach::Create_LC_THREAD (thread_sp.get(), LC_THREAD_datas[thread_idx]);
5823                                     break;
5824 
5825                                 case llvm::MachO::CPU_TYPE_I386:
5826                                     RegisterContextDarwin_i386_Mach::Create_LC_THREAD (thread_sp.get(), LC_THREAD_datas[thread_idx]);
5827                                     break;
5828 
5829                                 case llvm::MachO::CPU_TYPE_X86_64:
5830                                     RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD (thread_sp.get(), LC_THREAD_datas[thread_idx]);
5831                                     break;
5832                             }
5833 
5834                         }
5835                     }
5836 
5837                     // The size of the load command is the size of the segments...
5838                     if (addr_byte_size == 8)
5839                     {
5840                         mach_header.sizeofcmds = segment_load_commands.size() * sizeof (struct segment_command_64);
5841                     }
5842                     else
5843                     {
5844                         mach_header.sizeofcmds = segment_load_commands.size() * sizeof (struct segment_command);
5845                     }
5846 
5847                     // and the size of all LC_THREAD load command
5848                     for (const auto &LC_THREAD_data : LC_THREAD_datas)
5849                     {
5850                         ++mach_header.ncmds;
5851                         mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
5852                     }
5853 
5854                     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",
5855                             mach_header.magic,
5856                             mach_header.cputype,
5857                             mach_header.cpusubtype,
5858                             mach_header.filetype,
5859                             mach_header.ncmds,
5860                             mach_header.sizeofcmds,
5861                             mach_header.flags,
5862                             mach_header.reserved);
5863 
5864                     // Write the mach header
5865                     buffer.PutHex32(mach_header.magic);
5866                     buffer.PutHex32(mach_header.cputype);
5867                     buffer.PutHex32(mach_header.cpusubtype);
5868                     buffer.PutHex32(mach_header.filetype);
5869                     buffer.PutHex32(mach_header.ncmds);
5870                     buffer.PutHex32(mach_header.sizeofcmds);
5871                     buffer.PutHex32(mach_header.flags);
5872                     if (addr_byte_size == 8)
5873                     {
5874                         buffer.PutHex32(mach_header.reserved);
5875                     }
5876 
5877                     // Skip the mach header and all load commands and align to the next
5878                     // 0x1000 byte boundary
5879                     addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
5880                     if (file_offset & 0x00000fff)
5881                     {
5882                         file_offset += 0x00001000ull;
5883                         file_offset &= (~0x00001000ull + 1);
5884                     }
5885 
5886                     for (auto &segment : segment_load_commands)
5887                     {
5888                         segment.fileoff = file_offset;
5889                         file_offset += segment.filesize;
5890                     }
5891 
5892                     // Write out all of the LC_THREAD load commands
5893                     for (const auto &LC_THREAD_data : LC_THREAD_datas)
5894                     {
5895                         const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
5896                         buffer.PutHex32(LC_THREAD);
5897                         buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
5898                         buffer.Write(LC_THREAD_data.GetData(), LC_THREAD_data_size);
5899                     }
5900 
5901                     // Write out all of the segment load commands
5902                     for (const auto &segment : segment_load_commands)
5903                     {
5904                         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",
5905                                 segment.cmd,
5906                                 segment.cmdsize,
5907                                 segment.vmaddr,
5908                                 segment.vmaddr + segment.vmsize,
5909                                 segment.fileoff,
5910                                 segment.filesize,
5911                                 segment.maxprot,
5912                                 segment.initprot,
5913                                 segment.nsects,
5914                                 segment.flags);
5915 
5916                         buffer.PutHex32(segment.cmd);
5917                         buffer.PutHex32(segment.cmdsize);
5918                         buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
5919                         if (addr_byte_size == 8)
5920                         {
5921                             buffer.PutHex64(segment.vmaddr);
5922                             buffer.PutHex64(segment.vmsize);
5923                             buffer.PutHex64(segment.fileoff);
5924                             buffer.PutHex64(segment.filesize);
5925                         }
5926                         else
5927                         {
5928                             buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
5929                             buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
5930                             buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
5931                             buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
5932                         }
5933                         buffer.PutHex32(segment.maxprot);
5934                         buffer.PutHex32(segment.initprot);
5935                         buffer.PutHex32(segment.nsects);
5936                         buffer.PutHex32(segment.flags);
5937                     }
5938 
5939                     File core_file;
5940                     std::string core_file_path(outfile.GetPath());
5941                     error = core_file.Open(core_file_path.c_str(),
5942                                            File::eOpenOptionWrite    |
5943                                            File::eOpenOptionTruncate |
5944                                            File::eOpenOptionCanCreate);
5945                     if (error.Success())
5946                     {
5947                         // Read 1 page at a time
5948                         uint8_t bytes[0x1000];
5949                         // Write the mach header and load commands out to the core file
5950                         size_t bytes_written = buffer.GetString().size();
5951                         error = core_file.Write(buffer.GetString().data(), bytes_written);
5952                         if (error.Success())
5953                         {
5954                             // Now write the file data for all memory segments in the process
5955                             for (const auto &segment : segment_load_commands)
5956                             {
5957                                 if (core_file.SeekFromStart(segment.fileoff) == -1)
5958                                 {
5959                                     error.SetErrorStringWithFormat("unable to seek to offset 0x%" PRIx64 " in '%s'", segment.fileoff, core_file_path.c_str());
5960                                     break;
5961                                 }
5962 
5963                                 printf ("Saving %" PRId64 " bytes of data for memory region at 0x%" PRIx64 "\n", segment.vmsize, segment.vmaddr);
5964                                 addr_t bytes_left = segment.vmsize;
5965                                 addr_t addr = segment.vmaddr;
5966                                 Error memory_read_error;
5967                                 while (bytes_left > 0 && error.Success())
5968                                 {
5969                                     const size_t bytes_to_read = bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
5970                                     const size_t bytes_read = process_sp->ReadMemory(addr, bytes, bytes_to_read, memory_read_error);
5971                                     if (bytes_read == bytes_to_read)
5972                                     {
5973                                         size_t bytes_written = bytes_read;
5974                                         error = core_file.Write(bytes, bytes_written);
5975                                         bytes_left -= bytes_read;
5976                                         addr += bytes_read;
5977                                     }
5978                                     else
5979                                     {
5980                                         // Some pages within regions are not readable, those
5981                                         // should be zero filled
5982                                         memset (bytes, 0, bytes_to_read);
5983                                         size_t bytes_written = bytes_to_read;
5984                                         error = core_file.Write(bytes, bytes_written);
5985                                         bytes_left -= bytes_to_read;
5986                                         addr += bytes_to_read;
5987                                     }
5988                                 }
5989                             }
5990                         }
5991                     }
5992                 }
5993                 else
5994                 {
5995                     error.SetErrorString("process doesn't support getting memory region info");
5996                 }
5997             }
5998             return true; // This is the right plug to handle saving core files for this process
5999         }
6000     }
6001     return false;
6002 }
6003 
6004