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 #include "llvm/Support/MachO.h"
12 
13 #include "ObjectFileMachO.h"
14 
15 #include "lldb/Core/ArchSpec.h"
16 #include "lldb/Core/DataBuffer.h"
17 #include "lldb/Core/FileSpecList.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/Section.h"
21 #include "lldb/Core/StreamFile.h"
22 #include "lldb/Core/StreamString.h"
23 #include "lldb/Core/Timer.h"
24 #include "lldb/Core/UUID.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/FileSpec.h"
27 #include "lldb/Symbol/ClangNamespaceDecl.h"
28 #include "lldb/Symbol/ObjectFile.h"
29 #include "lldb/Target/Process.h"
30 #include "Plugins/Process/Utility/RegisterContextDarwin_arm.h"
31 #include "Plugins/Process/Utility/RegisterContextDarwin_i386.h"
32 #include "Plugins/Process/Utility/RegisterContextDarwin_x86_64.h"
33 
34 
35 using namespace lldb;
36 using namespace lldb_private;
37 using namespace llvm::MachO;
38 
39 class RegisterContextDarwin_x86_64_Mach : public RegisterContextDarwin_x86_64
40 {
41 public:
42     RegisterContextDarwin_x86_64_Mach (lldb_private::Thread &thread, const DataExtractor &data) :
43         RegisterContextDarwin_x86_64 (thread, 0)
44     {
45         SetRegisterDataFrom_LC_THREAD (data);
46     }
47 
48     virtual void
49     InvalidateAllRegisters ()
50     {
51         // Do nothing... registers are always valid...
52     }
53 
54     void
55     SetRegisterDataFrom_LC_THREAD (const DataExtractor &data)
56     {
57         uint32_t offset = 0;
58         SetError (GPRRegSet, Read, -1);
59         SetError (FPURegSet, Read, -1);
60         SetError (EXCRegSet, Read, -1);
61         bool done = false;
62 
63         while (!done)
64         {
65             int flavor = data.GetU32 (&offset);
66             if (flavor == 0)
67                 done = true;
68             else
69             {
70                 uint32_t i;
71                 uint32_t count = data.GetU32 (&offset);
72                 switch (flavor)
73                 {
74                     case GPRRegSet:
75                         for (i=0; i<count; ++i)
76                             (&gpr.rax)[i] = data.GetU64(&offset);
77                         SetError (GPRRegSet, Read, 0);
78                         done = true;
79 
80                         break;
81                     case FPURegSet:
82                         // TODO: fill in FPU regs....
83                         //SetError (FPURegSet, Read, -1);
84                         done = true;
85 
86                         break;
87                     case EXCRegSet:
88                         exc.trapno = data.GetU32(&offset);
89                         exc.err = data.GetU32(&offset);
90                         exc.faultvaddr = data.GetU64(&offset);
91                         SetError (EXCRegSet, Read, 0);
92                         done = true;
93                         break;
94                     case 7:
95                     case 8:
96                     case 9:
97                         // fancy flavors that encapsulate of the the above
98                         // falvors...
99                         break;
100 
101                     default:
102                         done = true;
103                         break;
104                 }
105             }
106         }
107     }
108 protected:
109     virtual int
110     DoReadGPR (lldb::tid_t tid, int flavor, GPR &gpr)
111     {
112         return 0;
113     }
114 
115     virtual int
116     DoReadFPU (lldb::tid_t tid, int flavor, FPU &fpu)
117     {
118         return 0;
119     }
120 
121     virtual int
122     DoReadEXC (lldb::tid_t tid, int flavor, EXC &exc)
123     {
124         return 0;
125     }
126 
127     virtual int
128     DoWriteGPR (lldb::tid_t tid, int flavor, const GPR &gpr)
129     {
130         return 0;
131     }
132 
133     virtual int
134     DoWriteFPU (lldb::tid_t tid, int flavor, const FPU &fpu)
135     {
136         return 0;
137     }
138 
139     virtual int
140     DoWriteEXC (lldb::tid_t tid, int flavor, const EXC &exc)
141     {
142         return 0;
143     }
144 };
145 
146 
147 class RegisterContextDarwin_i386_Mach : public RegisterContextDarwin_i386
148 {
149 public:
150     RegisterContextDarwin_i386_Mach (lldb_private::Thread &thread, const DataExtractor &data) :
151     RegisterContextDarwin_i386 (thread, 0)
152     {
153         SetRegisterDataFrom_LC_THREAD (data);
154     }
155 
156     virtual void
157     InvalidateAllRegisters ()
158     {
159         // Do nothing... registers are always valid...
160     }
161 
162     void
163     SetRegisterDataFrom_LC_THREAD (const DataExtractor &data)
164     {
165         uint32_t offset = 0;
166         SetError (GPRRegSet, Read, -1);
167         SetError (FPURegSet, Read, -1);
168         SetError (EXCRegSet, Read, -1);
169         bool done = false;
170 
171         while (!done)
172         {
173             int flavor = data.GetU32 (&offset);
174             if (flavor == 0)
175                 done = true;
176             else
177             {
178                 uint32_t i;
179                 uint32_t count = data.GetU32 (&offset);
180                 switch (flavor)
181                 {
182                     case GPRRegSet:
183                         for (i=0; i<count; ++i)
184                             (&gpr.eax)[i] = data.GetU32(&offset);
185                         SetError (GPRRegSet, Read, 0);
186                         done = true;
187 
188                         break;
189                     case FPURegSet:
190                         // TODO: fill in FPU regs....
191                         //SetError (FPURegSet, Read, -1);
192                         done = true;
193 
194                         break;
195                     case EXCRegSet:
196                         exc.trapno = data.GetU32(&offset);
197                         exc.err = data.GetU32(&offset);
198                         exc.faultvaddr = data.GetU32(&offset);
199                         SetError (EXCRegSet, Read, 0);
200                         done = true;
201                         break;
202                     case 7:
203                     case 8:
204                     case 9:
205                         // fancy flavors that encapsulate of the the above
206                         // falvors...
207                         break;
208 
209                     default:
210                         done = true;
211                         break;
212                 }
213             }
214         }
215     }
216 protected:
217     virtual int
218     DoReadGPR (lldb::tid_t tid, int flavor, GPR &gpr)
219     {
220         return 0;
221     }
222 
223     virtual int
224     DoReadFPU (lldb::tid_t tid, int flavor, FPU &fpu)
225     {
226         return 0;
227     }
228 
229     virtual int
230     DoReadEXC (lldb::tid_t tid, int flavor, EXC &exc)
231     {
232         return 0;
233     }
234 
235     virtual int
236     DoWriteGPR (lldb::tid_t tid, int flavor, const GPR &gpr)
237     {
238         return 0;
239     }
240 
241     virtual int
242     DoWriteFPU (lldb::tid_t tid, int flavor, const FPU &fpu)
243     {
244         return 0;
245     }
246 
247     virtual int
248     DoWriteEXC (lldb::tid_t tid, int flavor, const EXC &exc)
249     {
250         return 0;
251     }
252 };
253 
254 class RegisterContextDarwin_arm_Mach : public RegisterContextDarwin_arm
255 {
256 public:
257     RegisterContextDarwin_arm_Mach (lldb_private::Thread &thread, const DataExtractor &data) :
258     RegisterContextDarwin_arm (thread, 0)
259     {
260         SetRegisterDataFrom_LC_THREAD (data);
261     }
262 
263     virtual void
264     InvalidateAllRegisters ()
265     {
266         // Do nothing... registers are always valid...
267     }
268 
269     void
270     SetRegisterDataFrom_LC_THREAD (const DataExtractor &data)
271     {
272         uint32_t offset = 0;
273         SetError (GPRRegSet, Read, -1);
274         SetError (FPURegSet, Read, -1);
275         SetError (EXCRegSet, Read, -1);
276         int flavor = data.GetU32 (&offset);
277         uint32_t count = data.GetU32 (&offset);
278         switch (flavor)
279         {
280             case GPRRegSet:
281                 for (uint32_t i=0; i<count; ++i)
282                     gpr.r[i] = data.GetU32(&offset);
283                 SetError (GPRRegSet, Read, 0);
284                 break;
285             case FPURegSet:
286                 // TODO: fill in FPU regs....
287                 //SetError (FPURegSet, Read, -1);
288                 break;
289             case EXCRegSet:
290                 exc.exception = data.GetU32(&offset);
291                 exc.fsr = data.GetU32(&offset);
292                 exc.far = data.GetU32(&offset);
293                 SetError (EXCRegSet, Read, 0);
294                 break;
295         }
296     }
297 protected:
298     virtual int
299     DoReadGPR (lldb::tid_t tid, int flavor, GPR &gpr)
300     {
301         return 0;
302     }
303 
304     virtual int
305     DoReadFPU (lldb::tid_t tid, int flavor, FPU &fpu)
306     {
307         return 0;
308     }
309 
310     virtual int
311     DoReadEXC (lldb::tid_t tid, int flavor, EXC &exc)
312     {
313         return 0;
314     }
315 
316     virtual int
317     DoWriteGPR (lldb::tid_t tid, int flavor, const GPR &gpr)
318     {
319         return 0;
320     }
321 
322     virtual int
323     DoWriteFPU (lldb::tid_t tid, int flavor, const FPU &fpu)
324     {
325         return 0;
326     }
327 
328     virtual int
329     DoWriteEXC (lldb::tid_t tid, int flavor, const EXC &exc)
330     {
331         return 0;
332     }
333 };
334 
335 #define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008
336 
337 void
338 ObjectFileMachO::Initialize()
339 {
340     PluginManager::RegisterPlugin (GetPluginNameStatic(),
341                                    GetPluginDescriptionStatic(),
342                                    CreateInstance,
343                                    CreateMemoryInstance);
344 }
345 
346 void
347 ObjectFileMachO::Terminate()
348 {
349     PluginManager::UnregisterPlugin (CreateInstance);
350 }
351 
352 
353 const char *
354 ObjectFileMachO::GetPluginNameStatic()
355 {
356     return "object-file.mach-o";
357 }
358 
359 const char *
360 ObjectFileMachO::GetPluginDescriptionStatic()
361 {
362     return "Mach-o object file reader (32 and 64 bit)";
363 }
364 
365 
366 ObjectFile *
367 ObjectFileMachO::CreateInstance (Module* module, DataBufferSP& data_sp, const FileSpec* file, addr_t offset, addr_t length)
368 {
369     if (ObjectFileMachO::MagicBytesMatch(data_sp, offset, length))
370     {
371         std::auto_ptr<ObjectFile> objfile_ap(new ObjectFileMachO (module, data_sp, file, offset, length));
372         if (objfile_ap.get() && objfile_ap->ParseHeader())
373             return objfile_ap.release();
374     }
375     return NULL;
376 }
377 
378 ObjectFile *
379 ObjectFileMachO::CreateMemoryInstance (Module* module,
380                                        DataBufferSP& data_sp,
381                                        const ProcessSP &process_sp,
382                                        lldb::addr_t header_addr)
383 {
384     if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize()))
385     {
386         std::auto_ptr<ObjectFile> objfile_ap(new ObjectFileMachO (module, data_sp, process_sp, header_addr));
387         if (objfile_ap.get() && objfile_ap->ParseHeader())
388             return objfile_ap.release();
389     }
390     return NULL;
391 }
392 
393 
394 const ConstString &
395 ObjectFileMachO::GetSegmentNameTEXT()
396 {
397     static ConstString g_segment_name_TEXT ("__TEXT");
398     return g_segment_name_TEXT;
399 }
400 
401 const ConstString &
402 ObjectFileMachO::GetSegmentNameDATA()
403 {
404     static ConstString g_segment_name_DATA ("__DATA");
405     return g_segment_name_DATA;
406 }
407 
408 const ConstString &
409 ObjectFileMachO::GetSegmentNameOBJC()
410 {
411     static ConstString g_segment_name_OBJC ("__OBJC");
412     return g_segment_name_OBJC;
413 }
414 
415 const ConstString &
416 ObjectFileMachO::GetSegmentNameLINKEDIT()
417 {
418     static ConstString g_section_name_LINKEDIT ("__LINKEDIT");
419     return g_section_name_LINKEDIT;
420 }
421 
422 const ConstString &
423 ObjectFileMachO::GetSectionNameEHFrame()
424 {
425     static ConstString g_section_name_eh_frame ("__eh_frame");
426     return g_section_name_eh_frame;
427 }
428 
429 
430 
431 static uint32_t
432 MachHeaderSizeFromMagic(uint32_t magic)
433 {
434     switch (magic)
435     {
436     case HeaderMagic32:
437     case HeaderMagic32Swapped:
438         return sizeof(struct mach_header);
439 
440     case HeaderMagic64:
441     case HeaderMagic64Swapped:
442         return sizeof(struct mach_header_64);
443         break;
444 
445     default:
446         break;
447     }
448     return 0;
449 }
450 
451 
452 bool
453 ObjectFileMachO::MagicBytesMatch (DataBufferSP& data_sp,
454                                   lldb::addr_t data_offset,
455                                   lldb::addr_t data_length)
456 {
457     DataExtractor data;
458     data.SetData (data_sp, data_offset, data_length);
459     uint32_t offset = 0;
460     uint32_t magic = data.GetU32(&offset);
461     return MachHeaderSizeFromMagic(magic) != 0;
462 }
463 
464 
465 ObjectFileMachO::ObjectFileMachO(Module* module, DataBufferSP& data_sp, const FileSpec* file, addr_t offset, addr_t length) :
466     ObjectFile(module, file, offset, length, data_sp),
467     m_mutex (Mutex::eMutexTypeRecursive),
468     m_sections_ap(),
469     m_symtab_ap(),
470     m_mach_segments(),
471     m_mach_sections(),
472     m_entry_point_address(),
473     m_thread_context_offsets(),
474     m_thread_context_offsets_valid(false)
475 {
476     ::memset (&m_header, 0, sizeof(m_header));
477     ::memset (&m_dysymtab, 0, sizeof(m_dysymtab));
478 }
479 
480 ObjectFileMachO::ObjectFileMachO (lldb_private::Module* module,
481                                   lldb::DataBufferSP& header_data_sp,
482                                   const lldb::ProcessSP &process_sp,
483                                   lldb::addr_t header_addr) :
484     ObjectFile(module, process_sp, header_addr, header_data_sp),
485     m_mutex (Mutex::eMutexTypeRecursive),
486     m_sections_ap(),
487     m_symtab_ap(),
488     m_mach_segments(),
489     m_mach_sections(),
490     m_entry_point_address(),
491     m_thread_context_offsets(),
492     m_thread_context_offsets_valid(false)
493 {
494     ::memset (&m_header, 0, sizeof(m_header));
495     ::memset (&m_dysymtab, 0, sizeof(m_dysymtab));
496 }
497 
498 ObjectFileMachO::~ObjectFileMachO()
499 {
500 }
501 
502 
503 bool
504 ObjectFileMachO::ParseHeader ()
505 {
506     lldb_private::Mutex::Locker locker(m_mutex);
507     bool can_parse = false;
508     uint32_t offset = 0;
509     m_data.SetByteOrder (lldb::endian::InlHostByteOrder());
510     // Leave magic in the original byte order
511     m_header.magic = m_data.GetU32(&offset);
512     switch (m_header.magic)
513     {
514     case HeaderMagic32:
515         m_data.SetByteOrder (lldb::endian::InlHostByteOrder());
516         m_data.SetAddressByteSize(4);
517         can_parse = true;
518         break;
519 
520     case HeaderMagic64:
521         m_data.SetByteOrder (lldb::endian::InlHostByteOrder());
522         m_data.SetAddressByteSize(8);
523         can_parse = true;
524         break;
525 
526     case HeaderMagic32Swapped:
527         m_data.SetByteOrder(lldb::endian::InlHostByteOrder() == eByteOrderBig ? eByteOrderLittle : eByteOrderBig);
528         m_data.SetAddressByteSize(4);
529         can_parse = true;
530         break;
531 
532     case HeaderMagic64Swapped:
533         m_data.SetByteOrder(lldb::endian::InlHostByteOrder() == eByteOrderBig ? eByteOrderLittle : eByteOrderBig);
534         m_data.SetAddressByteSize(8);
535         can_parse = true;
536         break;
537 
538     default:
539         break;
540     }
541 
542     if (can_parse)
543     {
544         m_data.GetU32(&offset, &m_header.cputype, 6);
545 
546         ArchSpec mach_arch(eArchTypeMachO, m_header.cputype, m_header.cpusubtype);
547 
548         if (SetModulesArchitecture (mach_arch))
549         {
550             const size_t header_and_lc_size = m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
551             if (m_data.GetByteSize() < header_and_lc_size)
552             {
553                 DataBufferSP data_sp;
554                 ProcessSP process_sp (m_process_wp.lock());
555                 if (process_sp)
556                 {
557                     data_sp = ReadMemory (process_sp, m_offset, header_and_lc_size);
558                 }
559                 else
560                 {
561                     // Read in all only the load command data from the file on disk
562                     data_sp = m_file.ReadFileContents(m_offset, header_and_lc_size);
563                     if (data_sp->GetByteSize() != header_and_lc_size)
564                         return false;
565                 }
566                 if (data_sp)
567                     m_data.SetData (data_sp);
568             }
569         }
570         return true;
571     }
572     else
573     {
574         memset(&m_header, 0, sizeof(struct mach_header));
575     }
576     return false;
577 }
578 
579 
580 ByteOrder
581 ObjectFileMachO::GetByteOrder () const
582 {
583     lldb_private::Mutex::Locker locker(m_mutex);
584     return m_data.GetByteOrder ();
585 }
586 
587 bool
588 ObjectFileMachO::IsExecutable() const
589 {
590     return m_header.filetype == HeaderFileTypeExecutable;
591 }
592 
593 size_t
594 ObjectFileMachO::GetAddressByteSize () const
595 {
596     lldb_private::Mutex::Locker locker(m_mutex);
597     return m_data.GetAddressByteSize ();
598 }
599 
600 AddressClass
601 ObjectFileMachO::GetAddressClass (lldb::addr_t file_addr)
602 {
603     Symtab *symtab = GetSymtab();
604     if (symtab)
605     {
606         Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
607         if (symbol)
608         {
609             const AddressRange *range_ptr = symbol->GetAddressRangePtr();
610             if (range_ptr)
611             {
612                 const Section *section = range_ptr->GetBaseAddress().GetSection();
613                 if (section)
614                 {
615                     const SectionType section_type = section->GetType();
616                     switch (section_type)
617                     {
618                     case eSectionTypeInvalid:               return eAddressClassUnknown;
619                     case eSectionTypeCode:
620                         if (m_header.cputype == llvm::MachO::CPUTypeARM)
621                         {
622                             // For ARM we have a bit in the n_desc field of the symbol
623                             // that tells us ARM/Thumb which is bit 0x0008.
624                             if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
625                                 return eAddressClassCodeAlternateISA;
626                         }
627                         return eAddressClassCode;
628 
629                     case eSectionTypeContainer:             return eAddressClassUnknown;
630                     case eSectionTypeData:
631                     case eSectionTypeDataCString:
632                     case eSectionTypeDataCStringPointers:
633                     case eSectionTypeDataSymbolAddress:
634                     case eSectionTypeData4:
635                     case eSectionTypeData8:
636                     case eSectionTypeData16:
637                     case eSectionTypeDataPointers:
638                     case eSectionTypeZeroFill:
639                     case eSectionTypeDataObjCMessageRefs:
640                     case eSectionTypeDataObjCCFStrings:
641                         return eAddressClassData;
642                     case eSectionTypeDebug:
643                     case eSectionTypeDWARFDebugAbbrev:
644                     case eSectionTypeDWARFDebugAranges:
645                     case eSectionTypeDWARFDebugFrame:
646                     case eSectionTypeDWARFDebugInfo:
647                     case eSectionTypeDWARFDebugLine:
648                     case eSectionTypeDWARFDebugLoc:
649                     case eSectionTypeDWARFDebugMacInfo:
650                     case eSectionTypeDWARFDebugPubNames:
651                     case eSectionTypeDWARFDebugPubTypes:
652                     case eSectionTypeDWARFDebugRanges:
653                     case eSectionTypeDWARFDebugStr:
654                     case eSectionTypeDWARFAppleNames:
655                     case eSectionTypeDWARFAppleTypes:
656                     case eSectionTypeDWARFAppleNamespaces:
657                     case eSectionTypeDWARFAppleObjC:
658                         return eAddressClassDebug;
659                     case eSectionTypeEHFrame:               return eAddressClassRuntime;
660                     case eSectionTypeOther:                 return eAddressClassUnknown;
661                     }
662                 }
663             }
664 
665             const SymbolType symbol_type = symbol->GetType();
666             switch (symbol_type)
667             {
668             case eSymbolTypeAny:            return eAddressClassUnknown;
669             case eSymbolTypeAbsolute:       return eAddressClassUnknown;
670 
671             case eSymbolTypeCode:
672             case eSymbolTypeTrampoline:
673                 if (m_header.cputype == llvm::MachO::CPUTypeARM)
674                 {
675                     // For ARM we have a bit in the n_desc field of the symbol
676                     // that tells us ARM/Thumb which is bit 0x0008.
677                     if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
678                         return eAddressClassCodeAlternateISA;
679                 }
680                 return eAddressClassCode;
681 
682             case eSymbolTypeData:           return eAddressClassData;
683             case eSymbolTypeRuntime:        return eAddressClassRuntime;
684             case eSymbolTypeException:      return eAddressClassRuntime;
685             case eSymbolTypeSourceFile:     return eAddressClassDebug;
686             case eSymbolTypeHeaderFile:     return eAddressClassDebug;
687             case eSymbolTypeObjectFile:     return eAddressClassDebug;
688             case eSymbolTypeCommonBlock:    return eAddressClassDebug;
689             case eSymbolTypeBlock:          return eAddressClassDebug;
690             case eSymbolTypeLocal:          return eAddressClassData;
691             case eSymbolTypeParam:          return eAddressClassData;
692             case eSymbolTypeVariable:       return eAddressClassData;
693             case eSymbolTypeVariableType:   return eAddressClassDebug;
694             case eSymbolTypeLineEntry:      return eAddressClassDebug;
695             case eSymbolTypeLineHeader:     return eAddressClassDebug;
696             case eSymbolTypeScopeBegin:     return eAddressClassDebug;
697             case eSymbolTypeScopeEnd:       return eAddressClassDebug;
698             case eSymbolTypeAdditional:     return eAddressClassUnknown;
699             case eSymbolTypeCompiler:       return eAddressClassDebug;
700             case eSymbolTypeInstrumentation:return eAddressClassDebug;
701             case eSymbolTypeUndefined:      return eAddressClassUnknown;
702             case eSymbolTypeObjCClass:      return eAddressClassRuntime;
703             case eSymbolTypeObjCMetaClass:  return eAddressClassRuntime;
704             case eSymbolTypeObjCIVar:       return eAddressClassRuntime;
705             }
706         }
707     }
708     return eAddressClassUnknown;
709 }
710 
711 Symtab *
712 ObjectFileMachO::GetSymtab()
713 {
714     lldb_private::Mutex::Locker symfile_locker(m_mutex);
715     if (m_symtab_ap.get() == NULL)
716     {
717         m_symtab_ap.reset(new Symtab(this));
718         Mutex::Locker symtab_locker (m_symtab_ap->GetMutex());
719         ParseSymtab (true);
720         m_symtab_ap->Finalize ();
721     }
722     return m_symtab_ap.get();
723 }
724 
725 
726 SectionList *
727 ObjectFileMachO::GetSectionList()
728 {
729     lldb_private::Mutex::Locker locker(m_mutex);
730     if (m_sections_ap.get() == NULL)
731     {
732         m_sections_ap.reset(new SectionList());
733         ParseSections();
734     }
735     return m_sections_ap.get();
736 }
737 
738 
739 size_t
740 ObjectFileMachO::ParseSections ()
741 {
742     lldb::user_id_t segID = 0;
743     lldb::user_id_t sectID = 0;
744     struct segment_command_64 load_cmd;
745     uint32_t offset = MachHeaderSizeFromMagic(m_header.magic);
746     uint32_t i;
747     const bool is_core = GetType() == eTypeCoreFile;
748     //bool dump_sections = false;
749     for (i=0; i<m_header.ncmds; ++i)
750     {
751         const uint32_t load_cmd_offset = offset;
752         if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
753             break;
754 
755         if (load_cmd.cmd == LoadCommandSegment32 || load_cmd.cmd == LoadCommandSegment64)
756         {
757             if (m_data.GetU8(&offset, (uint8_t*)load_cmd.segname, 16))
758             {
759                 load_cmd.vmaddr = m_data.GetAddress(&offset);
760                 load_cmd.vmsize = m_data.GetAddress(&offset);
761                 load_cmd.fileoff = m_data.GetAddress(&offset);
762                 load_cmd.filesize = m_data.GetAddress(&offset);
763                 if (m_data.GetU32(&offset, &load_cmd.maxprot, 4))
764                 {
765 
766                     const bool segment_is_encrypted = (load_cmd.flags & SegmentCommandFlagBitProtectedVersion1) != 0;
767 
768                     // Keep a list of mach segments around in case we need to
769                     // get at data that isn't stored in the abstracted Sections.
770                     m_mach_segments.push_back (load_cmd);
771 
772                     ConstString segment_name (load_cmd.segname, std::min<int>(strlen(load_cmd.segname), sizeof(load_cmd.segname)));
773                     // Use a segment ID of the segment index shifted left by 8 so they
774                     // never conflict with any of the sections.
775                     SectionSP segment_sp;
776                     if (segment_name || is_core)
777                     {
778                         segment_sp.reset(new Section (NULL,
779                                                       GetModule(),            // Module to which this section belongs
780                                                       ++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
781                                                       segment_name,           // Name of this section
782                                                       eSectionTypeContainer,  // This section is a container of other sections.
783                                                       load_cmd.vmaddr,        // File VM address == addresses as they are found in the object file
784                                                       load_cmd.vmsize,        // VM size in bytes of this section
785                                                       load_cmd.fileoff,       // Offset to the data for this section in the file
786                                                       load_cmd.filesize,      // Size in bytes of this section as found in the the file
787                                                       load_cmd.flags));       // Flags for this section
788 
789                         segment_sp->SetIsEncrypted (segment_is_encrypted);
790                         m_sections_ap->AddSection(segment_sp);
791                     }
792 
793                     struct section_64 sect64;
794                     ::memset (&sect64, 0, sizeof(sect64));
795                     // Push a section into our mach sections for the section at
796                     // index zero (NListSectionNoSection) if we don't have any
797                     // mach sections yet...
798                     if (m_mach_sections.empty())
799                         m_mach_sections.push_back(sect64);
800                     uint32_t segment_sect_idx;
801                     const lldb::user_id_t first_segment_sectID = sectID + 1;
802 
803 
804                     const uint32_t num_u32s = load_cmd.cmd == LoadCommandSegment32 ? 7 : 8;
805                     for (segment_sect_idx=0; segment_sect_idx<load_cmd.nsects; ++segment_sect_idx)
806                     {
807                         if (m_data.GetU8(&offset, (uint8_t*)sect64.sectname, sizeof(sect64.sectname)) == NULL)
808                             break;
809                         if (m_data.GetU8(&offset, (uint8_t*)sect64.segname, sizeof(sect64.segname)) == NULL)
810                             break;
811                         sect64.addr = m_data.GetAddress(&offset);
812                         sect64.size = m_data.GetAddress(&offset);
813 
814                         if (m_data.GetU32(&offset, &sect64.offset, num_u32s) == NULL)
815                             break;
816 
817                         // Keep a list of mach sections around in case we need to
818                         // get at data that isn't stored in the abstracted Sections.
819                         m_mach_sections.push_back (sect64);
820 
821                         ConstString section_name (sect64.sectname, std::min<size_t>(strlen(sect64.sectname), sizeof(sect64.sectname)));
822                         if (!segment_name)
823                         {
824                             // We have a segment with no name so we need to conjure up
825                             // segments that correspond to the section's segname if there
826                             // isn't already such a section. If there is such a section,
827                             // we resize the section so that it spans all sections.
828                             // We also mark these sections as fake so address matches don't
829                             // hit if they land in the gaps between the child sections.
830                             segment_name.SetTrimmedCStringWithLength(sect64.segname, sizeof(sect64.segname));
831                             segment_sp = m_sections_ap->FindSectionByName (segment_name);
832                             if (segment_sp.get())
833                             {
834                                 Section *segment = segment_sp.get();
835                                 // Grow the section size as needed.
836                                 const lldb::addr_t sect64_min_addr = sect64.addr;
837                                 const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
838                                 const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
839                                 const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
840                                 const lldb::addr_t curr_seg_max_addr = curr_seg_min_addr + curr_seg_byte_size;
841                                 if (sect64_min_addr >= curr_seg_min_addr)
842                                 {
843                                     const lldb::addr_t new_seg_byte_size = sect64_max_addr - curr_seg_min_addr;
844                                     // Only grow the section size if needed
845                                     if (new_seg_byte_size > curr_seg_byte_size)
846                                         segment->SetByteSize (new_seg_byte_size);
847                                 }
848                                 else
849                                 {
850                                     // We need to change the base address of the segment and
851                                     // adjust the child section offsets for all existing children.
852                                     const lldb::addr_t slide_amount = sect64_min_addr - curr_seg_min_addr;
853                                     segment->Slide(slide_amount, false);
854                                     segment->GetChildren().Slide (-slide_amount, false);
855                                     segment->SetByteSize (curr_seg_max_addr - sect64_min_addr);
856                                 }
857 
858                                 // Grow the section size as needed.
859                                 if (sect64.offset)
860                                 {
861                                     const lldb::addr_t segment_min_file_offset = segment->GetFileOffset();
862                                     const lldb::addr_t segment_max_file_offset = segment_min_file_offset + segment->GetFileSize();
863 
864                                     const lldb::addr_t section_min_file_offset = sect64.offset;
865                                     const lldb::addr_t section_max_file_offset = section_min_file_offset + sect64.size;
866                                     const lldb::addr_t new_file_offset = std::min (section_min_file_offset, segment_min_file_offset);
867                                     const lldb::addr_t new_file_size = std::max (section_max_file_offset, segment_max_file_offset) - new_file_offset;
868                                     segment->SetFileOffset (new_file_offset);
869                                     segment->SetFileSize (new_file_size);
870                                 }
871                             }
872                             else
873                             {
874                                 // Create a fake section for the section's named segment
875                                 segment_sp.reset(new Section(segment_sp.get(),       // Parent section
876                                                              GetModule(),            // Module to which this section belongs
877                                                              ++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
878                                                              segment_name,           // Name of this section
879                                                              eSectionTypeContainer,  // This section is a container of other sections.
880                                                              sect64.addr,            // File VM address == addresses as they are found in the object file
881                                                              sect64.size,            // VM size in bytes of this section
882                                                              sect64.offset,          // Offset to the data for this section in the file
883                                                              sect64.offset ? sect64.size : 0,        // Size in bytes of this section as found in the the file
884                                                              load_cmd.flags));       // Flags for this section
885                                 segment_sp->SetIsFake(true);
886                                 m_sections_ap->AddSection(segment_sp);
887                                 segment_sp->SetIsEncrypted (segment_is_encrypted);
888                             }
889                         }
890                         assert (segment_sp.get());
891 
892                         uint32_t mach_sect_type = sect64.flags & SectionFlagMaskSectionType;
893                         static ConstString g_sect_name_objc_data ("__objc_data");
894                         static ConstString g_sect_name_objc_msgrefs ("__objc_msgrefs");
895                         static ConstString g_sect_name_objc_selrefs ("__objc_selrefs");
896                         static ConstString g_sect_name_objc_classrefs ("__objc_classrefs");
897                         static ConstString g_sect_name_objc_superrefs ("__objc_superrefs");
898                         static ConstString g_sect_name_objc_const ("__objc_const");
899                         static ConstString g_sect_name_objc_classlist ("__objc_classlist");
900                         static ConstString g_sect_name_cfstring ("__cfstring");
901 
902                         static ConstString g_sect_name_dwarf_debug_abbrev ("__debug_abbrev");
903                         static ConstString g_sect_name_dwarf_debug_aranges ("__debug_aranges");
904                         static ConstString g_sect_name_dwarf_debug_frame ("__debug_frame");
905                         static ConstString g_sect_name_dwarf_debug_info ("__debug_info");
906                         static ConstString g_sect_name_dwarf_debug_line ("__debug_line");
907                         static ConstString g_sect_name_dwarf_debug_loc ("__debug_loc");
908                         static ConstString g_sect_name_dwarf_debug_macinfo ("__debug_macinfo");
909                         static ConstString g_sect_name_dwarf_debug_pubnames ("__debug_pubnames");
910                         static ConstString g_sect_name_dwarf_debug_pubtypes ("__debug_pubtypes");
911                         static ConstString g_sect_name_dwarf_debug_ranges ("__debug_ranges");
912                         static ConstString g_sect_name_dwarf_debug_str ("__debug_str");
913                         static ConstString g_sect_name_dwarf_apple_names ("__apple_names");
914                         static ConstString g_sect_name_dwarf_apple_types ("__apple_types");
915                         static ConstString g_sect_name_dwarf_apple_namespaces ("__apple_namespac");
916                         static ConstString g_sect_name_dwarf_apple_objc ("__apple_objc");
917                         static ConstString g_sect_name_eh_frame ("__eh_frame");
918                         static ConstString g_sect_name_DATA ("__DATA");
919                         static ConstString g_sect_name_TEXT ("__TEXT");
920 
921                         SectionType sect_type = eSectionTypeOther;
922 
923                         if (section_name == g_sect_name_dwarf_debug_abbrev)
924                             sect_type = eSectionTypeDWARFDebugAbbrev;
925                         else if (section_name == g_sect_name_dwarf_debug_aranges)
926                             sect_type = eSectionTypeDWARFDebugAranges;
927                         else if (section_name == g_sect_name_dwarf_debug_frame)
928                             sect_type = eSectionTypeDWARFDebugFrame;
929                         else if (section_name == g_sect_name_dwarf_debug_info)
930                             sect_type = eSectionTypeDWARFDebugInfo;
931                         else if (section_name == g_sect_name_dwarf_debug_line)
932                             sect_type = eSectionTypeDWARFDebugLine;
933                         else if (section_name == g_sect_name_dwarf_debug_loc)
934                             sect_type = eSectionTypeDWARFDebugLoc;
935                         else if (section_name == g_sect_name_dwarf_debug_macinfo)
936                             sect_type = eSectionTypeDWARFDebugMacInfo;
937                         else if (section_name == g_sect_name_dwarf_debug_pubnames)
938                             sect_type = eSectionTypeDWARFDebugPubNames;
939                         else if (section_name == g_sect_name_dwarf_debug_pubtypes)
940                             sect_type = eSectionTypeDWARFDebugPubTypes;
941                         else if (section_name == g_sect_name_dwarf_debug_ranges)
942                             sect_type = eSectionTypeDWARFDebugRanges;
943                         else if (section_name == g_sect_name_dwarf_debug_str)
944                             sect_type = eSectionTypeDWARFDebugStr;
945                         else if (section_name == g_sect_name_dwarf_apple_names)
946                             sect_type = eSectionTypeDWARFAppleNames;
947                         else if (section_name == g_sect_name_dwarf_apple_types)
948                             sect_type = eSectionTypeDWARFAppleTypes;
949                         else if (section_name == g_sect_name_dwarf_apple_namespaces)
950                             sect_type = eSectionTypeDWARFAppleNamespaces;
951                         else if (section_name == g_sect_name_dwarf_apple_objc)
952                             sect_type = eSectionTypeDWARFAppleObjC;
953                         else if (section_name == g_sect_name_objc_selrefs)
954                             sect_type = eSectionTypeDataCStringPointers;
955                         else if (section_name == g_sect_name_objc_msgrefs)
956                             sect_type = eSectionTypeDataObjCMessageRefs;
957                         else if (section_name == g_sect_name_eh_frame)
958                             sect_type = eSectionTypeEHFrame;
959                         else if (section_name == g_sect_name_cfstring)
960                             sect_type = eSectionTypeDataObjCCFStrings;
961                         else if (section_name == g_sect_name_objc_data ||
962                                  section_name == g_sect_name_objc_classrefs ||
963                                  section_name == g_sect_name_objc_superrefs ||
964                                  section_name == g_sect_name_objc_const ||
965                                  section_name == g_sect_name_objc_classlist)
966                         {
967                             sect_type = eSectionTypeDataPointers;
968                         }
969 
970                         if (sect_type == eSectionTypeOther)
971                         {
972                             switch (mach_sect_type)
973                             {
974                             // TODO: categorize sections by other flags for regular sections
975                             case SectionTypeRegular:
976                                 if (segment_sp->GetName() == g_sect_name_TEXT)
977                                     sect_type = eSectionTypeCode;
978                                 else if (segment_sp->GetName() == g_sect_name_DATA)
979                                     sect_type = eSectionTypeData;
980                                 else
981                                     sect_type = eSectionTypeOther;
982                                 break;
983                             case SectionTypeZeroFill:                   sect_type = eSectionTypeZeroFill; break;
984                             case SectionTypeCStringLiterals:            sect_type = eSectionTypeDataCString;    break; // section with only literal C strings
985                             case SectionType4ByteLiterals:              sect_type = eSectionTypeData4;    break; // section with only 4 byte literals
986                             case SectionType8ByteLiterals:              sect_type = eSectionTypeData8;    break; // section with only 8 byte literals
987                             case SectionTypeLiteralPointers:            sect_type = eSectionTypeDataPointers;  break; // section with only pointers to literals
988                             case SectionTypeNonLazySymbolPointers:      sect_type = eSectionTypeDataPointers;  break; // section with only non-lazy symbol pointers
989                             case SectionTypeLazySymbolPointers:         sect_type = eSectionTypeDataPointers;  break; // section with only lazy symbol pointers
990                             case SectionTypeSymbolStubs:                sect_type = eSectionTypeCode;  break; // section with only symbol stubs, byte size of stub in the reserved2 field
991                             case SectionTypeModuleInitFunctionPointers: sect_type = eSectionTypeDataPointers;    break; // section with only function pointers for initialization
992                             case SectionTypeModuleTermFunctionPointers: sect_type = eSectionTypeDataPointers; break; // section with only function pointers for termination
993                             case SectionTypeCoalesced:                  sect_type = eSectionTypeOther; break;
994                             case SectionTypeZeroFillLarge:              sect_type = eSectionTypeZeroFill; break;
995                             case SectionTypeInterposing:                sect_type = eSectionTypeCode;  break; // section with only pairs of function pointers for interposing
996                             case SectionType16ByteLiterals:             sect_type = eSectionTypeData16; break; // section with only 16 byte literals
997                             case SectionTypeDTraceObjectFormat:         sect_type = eSectionTypeDebug; break;
998                             case SectionTypeLazyDylibSymbolPointers:    sect_type = eSectionTypeDataPointers;  break;
999                             default: break;
1000                             }
1001                         }
1002 
1003                         SectionSP section_sp(new Section(segment_sp.get(),
1004                                                          GetModule(),
1005                                                          ++sectID,
1006                                                          section_name,
1007                                                          sect_type,
1008                                                          sect64.addr - segment_sp->GetFileAddress(),
1009                                                          sect64.size,
1010                                                          sect64.offset,
1011                                                          sect64.offset == 0 ? 0 : sect64.size,
1012                                                          sect64.flags));
1013                         // Set the section to be encrypted to match the segment
1014                         section_sp->SetIsEncrypted (segment_is_encrypted);
1015 
1016                         segment_sp->GetChildren().AddSection(section_sp);
1017 
1018                         if (segment_sp->IsFake())
1019                         {
1020                             segment_sp.reset();
1021                             segment_name.Clear();
1022                         }
1023                     }
1024                     if (segment_sp && m_header.filetype == HeaderFileTypeDSYM)
1025                     {
1026                         if (first_segment_sectID <= sectID)
1027                         {
1028                             lldb::user_id_t sect_uid;
1029                             for (sect_uid = first_segment_sectID; sect_uid <= sectID; ++sect_uid)
1030                             {
1031                                 SectionSP curr_section_sp(segment_sp->GetChildren().FindSectionByID (sect_uid));
1032                                 SectionSP next_section_sp;
1033                                 if (sect_uid + 1 <= sectID)
1034                                     next_section_sp = segment_sp->GetChildren().FindSectionByID (sect_uid+1);
1035 
1036                                 if (curr_section_sp.get())
1037                                 {
1038                                     if (curr_section_sp->GetByteSize() == 0)
1039                                     {
1040                                         if (next_section_sp.get() != NULL)
1041                                             curr_section_sp->SetByteSize ( next_section_sp->GetFileAddress() - curr_section_sp->GetFileAddress() );
1042                                         else
1043                                             curr_section_sp->SetByteSize ( load_cmd.vmsize );
1044                                     }
1045                                 }
1046                             }
1047                         }
1048                     }
1049                 }
1050             }
1051         }
1052         else if (load_cmd.cmd == LoadCommandDynamicSymtabInfo)
1053         {
1054             m_dysymtab.cmd = load_cmd.cmd;
1055             m_dysymtab.cmdsize = load_cmd.cmdsize;
1056             m_data.GetU32 (&offset, &m_dysymtab.ilocalsym, (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1057         }
1058 
1059         offset = load_cmd_offset + load_cmd.cmdsize;
1060     }
1061 //    if (dump_sections)
1062 //    {
1063 //        StreamFile s(stdout);
1064 //        m_sections_ap->Dump(&s, true);
1065 //    }
1066     return sectID;  // Return the number of sections we registered with the module
1067 }
1068 
1069 class MachSymtabSectionInfo
1070 {
1071 public:
1072 
1073     MachSymtabSectionInfo (SectionList *section_list) :
1074         m_section_list (section_list),
1075         m_section_infos()
1076     {
1077         // Get the number of sections down to a depth of 1 to include
1078         // all segments and their sections, but no other sections that
1079         // may be added for debug map or
1080         m_section_infos.resize(section_list->GetNumSections(1));
1081     }
1082 
1083 
1084     Section *
1085     GetSection (uint8_t n_sect, addr_t file_addr)
1086     {
1087         if (n_sect == 0)
1088             return NULL;
1089         if (n_sect < m_section_infos.size())
1090         {
1091             if (m_section_infos[n_sect].section == NULL)
1092             {
1093                 Section *section = m_section_list->FindSectionByID (n_sect).get();
1094                 m_section_infos[n_sect].section = section;
1095                 if (section != NULL)
1096                 {
1097                     m_section_infos[n_sect].vm_range.SetBaseAddress (section->GetFileAddress());
1098                     m_section_infos[n_sect].vm_range.SetByteSize (section->GetByteSize());
1099                 }
1100                 else
1101                 {
1102                     Host::SystemLog (Host::eSystemLogError, "error: unable to find section for section %u\n", n_sect);
1103                 }
1104             }
1105             if (m_section_infos[n_sect].vm_range.Contains(file_addr))
1106             {
1107                 // Symbol is in section.
1108                 return m_section_infos[n_sect].section;
1109             }
1110             else if (m_section_infos[n_sect].vm_range.GetByteSize () == 0 &&
1111                      m_section_infos[n_sect].vm_range.GetBaseAddress() == file_addr)
1112             {
1113                 // Symbol is in section with zero size, but has the same start
1114                 // address as the section. This can happen with linker symbols
1115                 // (symbols that start with the letter 'l' or 'L'.
1116                 return m_section_infos[n_sect].section;
1117             }
1118         }
1119         return m_section_list->FindSectionContainingFileAddress(file_addr).get();
1120     }
1121 
1122 protected:
1123     struct SectionInfo
1124     {
1125         SectionInfo () :
1126             vm_range(),
1127             section (NULL)
1128         {
1129         }
1130 
1131         VMRange vm_range;
1132         Section *section;
1133     };
1134     SectionList *m_section_list;
1135     std::vector<SectionInfo> m_section_infos;
1136 };
1137 
1138 
1139 
1140 size_t
1141 ObjectFileMachO::ParseSymtab (bool minimize)
1142 {
1143     Timer scoped_timer(__PRETTY_FUNCTION__,
1144                        "ObjectFileMachO::ParseSymtab () module = %s",
1145                        m_file.GetFilename().AsCString(""));
1146     struct symtab_command symtab_load_command;
1147     uint32_t offset = MachHeaderSizeFromMagic(m_header.magic);
1148     uint32_t i;
1149 
1150     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SYMBOLS));
1151 
1152     for (i=0; i<m_header.ncmds; ++i)
1153     {
1154         const uint32_t cmd_offset = offset;
1155         // Read in the load command and load command size
1156         if (m_data.GetU32(&offset, &symtab_load_command, 2) == NULL)
1157             break;
1158         // Watch for the symbol table load command
1159         if (symtab_load_command.cmd == LoadCommandSymtab)
1160         {
1161             // Read in the rest of the symtab load command
1162             if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4)) // fill in symoff, nsyms, stroff, strsize fields
1163             {
1164                 if (symtab_load_command.symoff == 0)
1165                 {
1166                     if (log)
1167                         GetModule()->LogMessage(log.get(), "LC_SYMTAB.symoff == 0");
1168                     return 0;
1169                 }
1170 
1171                 if (symtab_load_command.stroff == 0)
1172                 {
1173                     if (log)
1174                         GetModule()->LogMessage(log.get(), "LC_SYMTAB.stroff == 0");
1175                     return 0;
1176                 }
1177 
1178                 if (symtab_load_command.nsyms == 0)
1179                 {
1180                     if (log)
1181                         GetModule()->LogMessage(log.get(), "LC_SYMTAB.nsyms == 0");
1182                     return 0;
1183                 }
1184 
1185                 if (symtab_load_command.strsize == 0)
1186                 {
1187                     if (log)
1188                         GetModule()->LogMessage(log.get(), "LC_SYMTAB.strsize == 0");
1189                     return 0;
1190                 }
1191 
1192                 Symtab *symtab = m_symtab_ap.get();
1193                 SectionList *section_list = GetSectionList();
1194                 if (section_list == NULL)
1195                     return 0;
1196 
1197                 ProcessSP process_sp (m_process_wp.lock());
1198 
1199                 const size_t addr_byte_size = m_data.GetAddressByteSize();
1200                 bool bit_width_32 = addr_byte_size == 4;
1201                 const size_t nlist_byte_size = bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
1202 
1203                 DataExtractor nlist_data (NULL, 0, m_data.GetByteOrder(), m_data.GetAddressByteSize());
1204                 DataExtractor strtab_data (NULL, 0, m_data.GetByteOrder(), m_data.GetAddressByteSize());
1205 
1206                 const addr_t nlist_data_byte_size = symtab_load_command.nsyms * nlist_byte_size;
1207                 const addr_t strtab_data_byte_size = symtab_load_command.strsize;
1208                 if (process_sp)
1209                 {
1210                     Target &target = process_sp->GetTarget();
1211                     SectionSP linkedit_section_sp(section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
1212                     // Reading mach file from memory in a process or core file...
1213 
1214                     if (linkedit_section_sp)
1215                     {
1216                         const addr_t linkedit_load_addr = linkedit_section_sp->GetLoadBaseAddress(&target);
1217                         const addr_t linkedit_file_offset = linkedit_section_sp->GetFileOffset();
1218                         const addr_t symoff_addr = linkedit_load_addr + symtab_load_command.symoff - linkedit_file_offset;
1219                         const addr_t stroff_addr = linkedit_load_addr + symtab_load_command.stroff - linkedit_file_offset;
1220                         DataBufferSP nlist_data_sp (ReadMemory (process_sp, symoff_addr, nlist_data_byte_size));
1221                         if (nlist_data_sp)
1222                             nlist_data.SetData (nlist_data_sp, 0, nlist_data_sp->GetByteSize());
1223                         DataBufferSP strtab_data_sp (ReadMemory (process_sp, stroff_addr, strtab_data_byte_size));
1224                         if (strtab_data_sp)
1225                             strtab_data.SetData (strtab_data_sp, 0, strtab_data_sp->GetByteSize());
1226                     }
1227                 }
1228                 else
1229                 {
1230                     nlist_data.SetData (m_data,
1231                                         symtab_load_command.symoff,
1232                                         nlist_data_byte_size);
1233                     strtab_data.SetData (m_data,
1234                                          symtab_load_command.stroff,
1235                                          strtab_data_byte_size);
1236 
1237                 }
1238 
1239                 if (nlist_data.GetByteSize() == 0)
1240                 {
1241                     if (log)
1242                         GetModule()->LogMessage(log.get(), "failed to read nlist data");
1243                     return 0;
1244                 }
1245 
1246 
1247                 if (strtab_data.GetByteSize() == 0)
1248                 {
1249                     if (log)
1250                         GetModule()->LogMessage(log.get(), "failed to read strtab data");
1251                     return 0;
1252                 }
1253 
1254                 const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT();
1255                 const ConstString &g_segment_name_DATA = GetSegmentNameDATA();
1256                 const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC();
1257                 const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame();
1258                 SectionSP text_section_sp(section_list->FindSectionByName(g_segment_name_TEXT));
1259                 SectionSP data_section_sp(section_list->FindSectionByName(g_segment_name_DATA));
1260                 SectionSP objc_section_sp(section_list->FindSectionByName(g_segment_name_OBJC));
1261                 SectionSP eh_frame_section_sp;
1262                 if (text_section_sp.get())
1263                     eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName (g_section_name_eh_frame);
1264                 else
1265                     eh_frame_section_sp = section_list->FindSectionByName (g_section_name_eh_frame);
1266 
1267                 uint8_t TEXT_eh_frame_sectID = eh_frame_section_sp.get() ? eh_frame_section_sp->GetID() : NListSectionNoSection;
1268 
1269                 uint32_t nlist_data_offset = 0;
1270 
1271                 uint32_t N_SO_index = UINT32_MAX;
1272 
1273                 MachSymtabSectionInfo section_info (section_list);
1274                 std::vector<uint32_t> N_FUN_indexes;
1275                 std::vector<uint32_t> N_NSYM_indexes;
1276                 std::vector<uint32_t> N_INCL_indexes;
1277                 std::vector<uint32_t> N_BRAC_indexes;
1278                 std::vector<uint32_t> N_COMM_indexes;
1279                 typedef std::map <uint64_t, uint32_t> ValueToSymbolIndexMap;
1280                 typedef std::map <uint32_t, uint32_t> NListIndexToSymbolIndexMap;
1281                 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
1282                 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
1283                 // Any symbols that get merged into another will get an entry
1284                 // in this map so we know
1285                 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
1286                 uint32_t nlist_idx = 0;
1287                 Symbol *symbol_ptr = NULL;
1288 
1289                 uint32_t sym_idx = 0;
1290                 Symbol *sym = symtab->Resize (symtab_load_command.nsyms + m_dysymtab.nindirectsyms);
1291                 uint32_t num_syms = symtab->GetNumSymbols();
1292 
1293                 //symtab->Reserve (symtab_load_command.nsyms + m_dysymtab.nindirectsyms);
1294                 for (nlist_idx = 0; nlist_idx < symtab_load_command.nsyms; ++nlist_idx)
1295                 {
1296                     struct nlist_64 nlist;
1297                     if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size))
1298                         break;
1299 
1300                     nlist.n_strx  = nlist_data.GetU32_unchecked(&nlist_data_offset);
1301                     nlist.n_type  = nlist_data.GetU8_unchecked (&nlist_data_offset);
1302                     nlist.n_sect  = nlist_data.GetU8_unchecked (&nlist_data_offset);
1303                     nlist.n_desc  = nlist_data.GetU16_unchecked (&nlist_data_offset);
1304                     nlist.n_value = nlist_data.GetAddress_unchecked (&nlist_data_offset);
1305 
1306                     SymbolType type = eSymbolTypeInvalid;
1307                     const char *symbol_name = strtab_data.PeekCStr(nlist.n_strx);
1308                     if (symbol_name == NULL)
1309                     {
1310                         // No symbol should be NULL, even the symbols with no
1311                         // string values should have an offset zero which points
1312                         // to an empty C-string
1313                         Host::SystemLog (Host::eSystemLogError,
1314                                          "error: symbol[%u] has invalid string table offset 0x%x in %s/%s, ignoring symbol\n",
1315                                          nlist_idx,
1316                                          nlist.n_strx,
1317                                          m_module->GetFileSpec().GetDirectory().GetCString(),
1318                                          m_module->GetFileSpec().GetFilename().GetCString());
1319                         continue;
1320                     }
1321                     const char *symbol_name_non_abi_mangled = NULL;
1322 
1323                     if (symbol_name[0] == '\0')
1324                         symbol_name = NULL;
1325                     Section* symbol_section = NULL;
1326                     bool add_nlist = true;
1327                     bool is_debug = ((nlist.n_type & NlistMaskStab) != 0);
1328 
1329                     assert (sym_idx < num_syms);
1330 
1331                     sym[sym_idx].SetDebug (is_debug);
1332 
1333                     if (is_debug)
1334                     {
1335                         switch (nlist.n_type)
1336                         {
1337                         case StabGlobalSymbol:
1338                             // N_GSYM -- global symbol: name,,NO_SECT,type,0
1339                             // Sometimes the N_GSYM value contains the address.
1340 
1341                             // FIXME: In the .o files, we have a GSYM and a debug symbol for all the ObjC data.  They
1342                             // have the same address, but we want to ensure that we always find only the real symbol,
1343                             // 'cause we don't currently correctly attribute the GSYM one to the ObjCClass/Ivar/MetaClass
1344                             // symbol type.  This is a temporary hack to make sure the ObjectiveC symbols get treated
1345                             // correctly.  To do this right, we should coalesce all the GSYM & global symbols that have the
1346                             // same address.
1347 
1348                             if (symbol_name && symbol_name[0] == '_' && symbol_name[1] ==  'O'
1349                                 && (strncmp (symbol_name, "_OBJC_IVAR_$_", strlen ("_OBJC_IVAR_$_")) == 0
1350                                     || strncmp (symbol_name, "_OBJC_CLASS_$_", strlen ("_OBJC_CLASS_$_")) == 0
1351                                     || strncmp (symbol_name, "_OBJC_METACLASS_$_", strlen ("_OBJC_METACLASS_$_")) == 0))
1352                                 add_nlist = false;
1353                             else
1354                             {
1355                                 sym[sym_idx].SetExternal(true);
1356                                 if (nlist.n_value != 0)
1357                                     symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
1358                                 type = eSymbolTypeData;
1359                             }
1360                             break;
1361 
1362                         case StabFunctionName:
1363                             // N_FNAME -- procedure name (f77 kludge): name,,NO_SECT,0,0
1364                             type = eSymbolTypeCompiler;
1365                             break;
1366 
1367                         case StabFunction:
1368                             // N_FUN -- procedure: name,,n_sect,linenumber,address
1369                             if (symbol_name)
1370                             {
1371                                 type = eSymbolTypeCode;
1372                                 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
1373 
1374                                 N_FUN_addr_to_sym_idx[nlist.n_value] = sym_idx;
1375                                 // We use the current number of symbols in the symbol table in lieu of
1376                                 // using nlist_idx in case we ever start trimming entries out
1377                                 N_FUN_indexes.push_back(sym_idx);
1378                             }
1379                             else
1380                             {
1381                                 type = eSymbolTypeCompiler;
1382 
1383                                 if ( !N_FUN_indexes.empty() )
1384                                 {
1385                                     // Copy the size of the function into the original STAB entry so we don't have
1386                                     // to hunt for it later
1387                                     symtab->SymbolAtIndex(N_FUN_indexes.back())->SetByteSize(nlist.n_value);
1388                                     N_FUN_indexes.pop_back();
1389                                     // We don't really need the end function STAB as it contains the size which
1390                                     // we already placed with the original symbol, so don't add it if we want a
1391                                     // minimal symbol table
1392                                     if (minimize)
1393                                         add_nlist = false;
1394                                 }
1395                             }
1396                             break;
1397 
1398                         case StabStaticSymbol:
1399                             // N_STSYM -- static symbol: name,,n_sect,type,address
1400                             N_STSYM_addr_to_sym_idx[nlist.n_value] = sym_idx;
1401                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
1402                             type = eSymbolTypeData;
1403                             break;
1404 
1405                         case StabLocalCommon:
1406                             // N_LCSYM -- .lcomm symbol: name,,n_sect,type,address
1407                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
1408                             type = eSymbolTypeCommonBlock;
1409                             break;
1410 
1411                         case StabBeginSymbol:
1412                             // N_BNSYM
1413                             // We use the current number of symbols in the symbol table in lieu of
1414                             // using nlist_idx in case we ever start trimming entries out
1415                             if (minimize)
1416                             {
1417                                 // Skip these if we want minimal symbol tables
1418                                 add_nlist = false;
1419                             }
1420                             else
1421                             {
1422                                 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
1423                                 N_NSYM_indexes.push_back(sym_idx);
1424                                 type = eSymbolTypeScopeBegin;
1425                             }
1426                             break;
1427 
1428                         case StabEndSymbol:
1429                             // N_ENSYM
1430                             // Set the size of the N_BNSYM to the terminating index of this N_ENSYM
1431                             // so that we can always skip the entire symbol if we need to navigate
1432                             // more quickly at the source level when parsing STABS
1433                             if (minimize)
1434                             {
1435                                 // Skip these if we want minimal symbol tables
1436                                 add_nlist = false;
1437                             }
1438                             else
1439                             {
1440                                 if ( !N_NSYM_indexes.empty() )
1441                                 {
1442                                     symbol_ptr = symtab->SymbolAtIndex(N_NSYM_indexes.back());
1443                                     symbol_ptr->SetByteSize(sym_idx + 1);
1444                                     symbol_ptr->SetSizeIsSibling(true);
1445                                     N_NSYM_indexes.pop_back();
1446                                 }
1447                                 type = eSymbolTypeScopeEnd;
1448                             }
1449                             break;
1450 
1451 
1452                         case StabSourceFileOptions:
1453                             // N_OPT - emitted with gcc2_compiled and in gcc source
1454                             type = eSymbolTypeCompiler;
1455                             break;
1456 
1457                         case StabRegisterSymbol:
1458                             // N_RSYM - register sym: name,,NO_SECT,type,register
1459                             type = eSymbolTypeVariable;
1460                             break;
1461 
1462                         case StabSourceLine:
1463                             // N_SLINE - src line: 0,,n_sect,linenumber,address
1464                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
1465                             type = eSymbolTypeLineEntry;
1466                             break;
1467 
1468                         case StabStructureType:
1469                             // N_SSYM - structure elt: name,,NO_SECT,type,struct_offset
1470                             type = eSymbolTypeVariableType;
1471                             break;
1472 
1473                         case StabSourceFileName:
1474                             // N_SO - source file name
1475                             type = eSymbolTypeSourceFile;
1476                             if (symbol_name == NULL)
1477                             {
1478                                 if (minimize)
1479                                     add_nlist = false;
1480                                 if (N_SO_index != UINT32_MAX)
1481                                 {
1482                                     // Set the size of the N_SO to the terminating index of this N_SO
1483                                     // so that we can always skip the entire N_SO if we need to navigate
1484                                     // more quickly at the source level when parsing STABS
1485                                     symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
1486                                     symbol_ptr->SetByteSize(sym_idx + (minimize ? 0 : 1));
1487                                     symbol_ptr->SetSizeIsSibling(true);
1488                                 }
1489                                 N_NSYM_indexes.clear();
1490                                 N_INCL_indexes.clear();
1491                                 N_BRAC_indexes.clear();
1492                                 N_COMM_indexes.clear();
1493                                 N_FUN_indexes.clear();
1494                                 N_SO_index = UINT32_MAX;
1495                             }
1496                             else
1497                             {
1498                                 // We use the current number of symbols in the symbol table in lieu of
1499                                 // using nlist_idx in case we ever start trimming entries out
1500                                 if (symbol_name[0] == '/')
1501                                     N_SO_index = sym_idx;
1502                                 else if (minimize && (N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
1503                                 {
1504                                     const char *so_path = sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString();
1505                                     if (so_path && so_path[0])
1506                                     {
1507                                         std::string full_so_path (so_path);
1508                                         if (*full_so_path.rbegin() != '/')
1509                                             full_so_path += '/';
1510                                         full_so_path += symbol_name;
1511                                         sym[sym_idx - 1].GetMangled().SetValue(full_so_path.c_str(), false);
1512                                         add_nlist = false;
1513                                         m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
1514                                     }
1515                                 }
1516                             }
1517 
1518                             break;
1519 
1520                         case StabObjectFileName:
1521                             // N_OSO - object file name: name,,0,0,st_mtime
1522                             type = eSymbolTypeObjectFile;
1523                             break;
1524 
1525                         case StabLocalSymbol:
1526                             // N_LSYM - local sym: name,,NO_SECT,type,offset
1527                             type = eSymbolTypeLocal;
1528                             break;
1529 
1530                         //----------------------------------------------------------------------
1531                         // INCL scopes
1532                         //----------------------------------------------------------------------
1533                         case StabBeginIncludeFileName:
1534                             // N_BINCL - include file beginning: name,,NO_SECT,0,sum
1535                             // We use the current number of symbols in the symbol table in lieu of
1536                             // using nlist_idx in case we ever start trimming entries out
1537                             N_INCL_indexes.push_back(sym_idx);
1538                             type = eSymbolTypeScopeBegin;
1539                             break;
1540 
1541                         case StabEndIncludeFile:
1542                             // N_EINCL - include file end: name,,NO_SECT,0,0
1543                             // Set the size of the N_BINCL to the terminating index of this N_EINCL
1544                             // so that we can always skip the entire symbol if we need to navigate
1545                             // more quickly at the source level when parsing STABS
1546                             if ( !N_INCL_indexes.empty() )
1547                             {
1548                                 symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
1549                                 symbol_ptr->SetByteSize(sym_idx + 1);
1550                                 symbol_ptr->SetSizeIsSibling(true);
1551                                 N_INCL_indexes.pop_back();
1552                             }
1553                             type = eSymbolTypeScopeEnd;
1554                             break;
1555 
1556                         case StabIncludeFileName:
1557                             // N_SOL - #included file name: name,,n_sect,0,address
1558                             type = eSymbolTypeHeaderFile;
1559 
1560                             // We currently don't use the header files on darwin
1561                             if (minimize)
1562                                 add_nlist = false;
1563                             break;
1564 
1565                         case StabCompilerParameters:
1566                             // N_PARAMS - compiler parameters: name,,NO_SECT,0,0
1567                             type = eSymbolTypeCompiler;
1568                             break;
1569 
1570                         case StabCompilerVersion:
1571                             // N_VERSION - compiler version: name,,NO_SECT,0,0
1572                             type = eSymbolTypeCompiler;
1573                             break;
1574 
1575                         case StabCompilerOptLevel:
1576                             // N_OLEVEL - compiler -O level: name,,NO_SECT,0,0
1577                             type = eSymbolTypeCompiler;
1578                             break;
1579 
1580                         case StabParameter:
1581                             // N_PSYM - parameter: name,,NO_SECT,type,offset
1582                             type = eSymbolTypeVariable;
1583                             break;
1584 
1585                         case StabAlternateEntry:
1586                             // N_ENTRY - alternate entry: name,,n_sect,linenumber,address
1587                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
1588                             type = eSymbolTypeLineEntry;
1589                             break;
1590 
1591                         //----------------------------------------------------------------------
1592                         // Left and Right Braces
1593                         //----------------------------------------------------------------------
1594                         case StabLeftBracket:
1595                             // N_LBRAC - left bracket: 0,,NO_SECT,nesting level,address
1596                             // We use the current number of symbols in the symbol table in lieu of
1597                             // using nlist_idx in case we ever start trimming entries out
1598                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
1599                             N_BRAC_indexes.push_back(sym_idx);
1600                             type = eSymbolTypeScopeBegin;
1601                             break;
1602 
1603                         case StabRightBracket:
1604                             // N_RBRAC - right bracket: 0,,NO_SECT,nesting level,address
1605                             // Set the size of the N_LBRAC to the terminating index of this N_RBRAC
1606                             // so that we can always skip the entire symbol if we need to navigate
1607                             // more quickly at the source level when parsing STABS
1608                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
1609                             if ( !N_BRAC_indexes.empty() )
1610                             {
1611                                 symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
1612                                 symbol_ptr->SetByteSize(sym_idx + 1);
1613                                 symbol_ptr->SetSizeIsSibling(true);
1614                                 N_BRAC_indexes.pop_back();
1615                             }
1616                             type = eSymbolTypeScopeEnd;
1617                             break;
1618 
1619                         case StabDeletedIncludeFile:
1620                             // N_EXCL - deleted include file: name,,NO_SECT,0,sum
1621                             type = eSymbolTypeHeaderFile;
1622                             break;
1623 
1624                         //----------------------------------------------------------------------
1625                         // COMM scopes
1626                         //----------------------------------------------------------------------
1627                         case StabBeginCommon:
1628                             // N_BCOMM - begin common: name,,NO_SECT,0,0
1629                             // We use the current number of symbols in the symbol table in lieu of
1630                             // using nlist_idx in case we ever start trimming entries out
1631                             type = eSymbolTypeScopeBegin;
1632                             N_COMM_indexes.push_back(sym_idx);
1633                             break;
1634 
1635                         case StabEndCommonLocal:
1636                             // N_ECOML - end common (local name): 0,,n_sect,0,address
1637                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
1638                             // Fall through
1639 
1640                         case StabEndCommon:
1641                             // N_ECOMM - end common: name,,n_sect,0,0
1642                             // Set the size of the N_BCOMM to the terminating index of this N_ECOMM/N_ECOML
1643                             // so that we can always skip the entire symbol if we need to navigate
1644                             // more quickly at the source level when parsing STABS
1645                             if ( !N_COMM_indexes.empty() )
1646                             {
1647                                 symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
1648                                 symbol_ptr->SetByteSize(sym_idx + 1);
1649                                 symbol_ptr->SetSizeIsSibling(true);
1650                                 N_COMM_indexes.pop_back();
1651                             }
1652                             type = eSymbolTypeScopeEnd;
1653                             break;
1654 
1655                         case StabLength:
1656                             // N_LENG - second stab entry with length information
1657                             type = eSymbolTypeAdditional;
1658                             break;
1659 
1660                         default: break;
1661                         }
1662                     }
1663                     else
1664                     {
1665                         //uint8_t n_pext    = NlistMaskPrivateExternal & nlist.n_type;
1666                         uint8_t n_type  = NlistMaskType & nlist.n_type;
1667                         sym[sym_idx].SetExternal((NlistMaskExternal & nlist.n_type) != 0);
1668 
1669                         switch (n_type)
1670                         {
1671                         case NListTypeIndirect:         // N_INDR - Fall through
1672                         case NListTypePreboundUndefined:// N_PBUD - Fall through
1673                         case NListTypeUndefined:        // N_UNDF
1674                             type = eSymbolTypeUndefined;
1675                             break;
1676 
1677                         case NListTypeAbsolute:         // N_ABS
1678                             type = eSymbolTypeAbsolute;
1679                             break;
1680 
1681                         case NListTypeSection:          // N_SECT
1682                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
1683 
1684                             if (symbol_section == NULL)
1685                             {
1686                                 // TODO: warn about this?
1687                                 add_nlist = false;
1688                                 break;
1689                             }
1690 
1691                             if (TEXT_eh_frame_sectID == nlist.n_sect)
1692                             {
1693                                 type = eSymbolTypeException;
1694                             }
1695                             else
1696                             {
1697                                 uint32_t section_type = symbol_section->Get() & SectionFlagMaskSectionType;
1698 
1699                                 switch (section_type)
1700                                 {
1701                                 case SectionTypeRegular:                     break; // regular section
1702                                 //case SectionTypeZeroFill:                 type = eSymbolTypeData;    break; // zero fill on demand section
1703                                 case SectionTypeCStringLiterals:            type = eSymbolTypeData;    break; // section with only literal C strings
1704                                 case SectionType4ByteLiterals:              type = eSymbolTypeData;    break; // section with only 4 byte literals
1705                                 case SectionType8ByteLiterals:              type = eSymbolTypeData;    break; // section with only 8 byte literals
1706                                 case SectionTypeLiteralPointers:            type = eSymbolTypeTrampoline; break; // section with only pointers to literals
1707                                 case SectionTypeNonLazySymbolPointers:      type = eSymbolTypeTrampoline; break; // section with only non-lazy symbol pointers
1708                                 case SectionTypeLazySymbolPointers:         type = eSymbolTypeTrampoline; break; // section with only lazy symbol pointers
1709                                 case SectionTypeSymbolStubs:                type = eSymbolTypeTrampoline; break; // section with only symbol stubs, byte size of stub in the reserved2 field
1710                                 case SectionTypeModuleInitFunctionPointers: type = eSymbolTypeCode;    break; // section with only function pointers for initialization
1711                                 case SectionTypeModuleTermFunctionPointers: type = eSymbolTypeCode;    break; // section with only function pointers for termination
1712                                 //case SectionTypeCoalesced:                type = eSymbolType;    break; // section contains symbols that are to be coalesced
1713                                 //case SectionTypeZeroFillLarge:            type = eSymbolTypeData;    break; // zero fill on demand section (that can be larger than 4 gigabytes)
1714                                 case SectionTypeInterposing:                type = eSymbolTypeTrampoline;  break; // section with only pairs of function pointers for interposing
1715                                 case SectionType16ByteLiterals:             type = eSymbolTypeData;    break; // section with only 16 byte literals
1716                                 case SectionTypeDTraceObjectFormat:         type = eSymbolTypeInstrumentation; break;
1717                                 case SectionTypeLazyDylibSymbolPointers:    type = eSymbolTypeTrampoline; break;
1718                                 default: break;
1719                                 }
1720 
1721                                 if (type == eSymbolTypeInvalid)
1722                                 {
1723                                     const char *symbol_sect_name = symbol_section->GetName().AsCString();
1724                                     if (symbol_section->IsDescendant (text_section_sp.get()))
1725                                     {
1726                                         if (symbol_section->IsClear(SectionAttrUserPureInstructions |
1727                                                                     SectionAttrUserSelfModifyingCode |
1728                                                                     SectionAttrSytemSomeInstructions))
1729                                             type = eSymbolTypeData;
1730                                         else
1731                                             type = eSymbolTypeCode;
1732                                     }
1733                                     else
1734                                     if (symbol_section->IsDescendant(data_section_sp.get()))
1735                                     {
1736                                         if (symbol_sect_name && ::strstr (symbol_sect_name, "__objc") == symbol_sect_name)
1737                                         {
1738                                             type = eSymbolTypeRuntime;
1739 
1740                                             if (symbol_name &&
1741                                                 symbol_name[0] == '_' &&
1742                                                 symbol_name[1] == 'O' &&
1743                                                 symbol_name[2] == 'B')
1744                                             {
1745                                                 llvm::StringRef symbol_name_ref(symbol_name);
1746                                                 static const llvm::StringRef g_objc_v2_prefix_class ("_OBJC_CLASS_$_");
1747                                                 static const llvm::StringRef g_objc_v2_prefix_metaclass ("_OBJC_METACLASS_$_");
1748                                                 static const llvm::StringRef g_objc_v2_prefix_ivar ("_OBJC_IVAR_$_");
1749                                                 if (symbol_name_ref.startswith(g_objc_v2_prefix_class))
1750                                                 {
1751                                                     symbol_name_non_abi_mangled = symbol_name + 1;
1752                                                     symbol_name = symbol_name + g_objc_v2_prefix_class.size();
1753                                                     type = eSymbolTypeObjCClass;
1754                                                 }
1755                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass))
1756                                                 {
1757                                                     symbol_name_non_abi_mangled = symbol_name + 1;
1758                                                     symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
1759                                                     type = eSymbolTypeObjCMetaClass;
1760                                                 }
1761                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar))
1762                                                 {
1763                                                     symbol_name_non_abi_mangled = symbol_name + 1;
1764                                                     symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
1765                                                     type = eSymbolTypeObjCIVar;
1766                                                 }
1767                                             }
1768                                         }
1769                                         else
1770                                         if (symbol_sect_name && ::strstr (symbol_sect_name, "__gcc_except_tab") == symbol_sect_name)
1771                                         {
1772                                             type = eSymbolTypeException;
1773                                         }
1774                                         else
1775                                         {
1776                                             type = eSymbolTypeData;
1777                                         }
1778                                     }
1779                                     else
1780                                     if (symbol_sect_name && ::strstr (symbol_sect_name, "__IMPORT") == symbol_sect_name)
1781                                     {
1782                                         type = eSymbolTypeTrampoline;
1783                                     }
1784                                     else
1785                                     if (symbol_section->IsDescendant(objc_section_sp.get()))
1786                                     {
1787                                         type = eSymbolTypeRuntime;
1788                                         if (symbol_name && symbol_name[0] == '.')
1789                                         {
1790                                             llvm::StringRef symbol_name_ref(symbol_name);
1791                                             static const llvm::StringRef g_objc_v1_prefix_class (".objc_class_name_");
1792                                             if (symbol_name_ref.startswith(g_objc_v1_prefix_class))
1793                                             {
1794                                                 symbol_name_non_abi_mangled = symbol_name;
1795                                                 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
1796                                                 type = eSymbolTypeObjCClass;
1797                                             }
1798                                         }
1799                                     }
1800                                 }
1801                             }
1802                             break;
1803                         }
1804                     }
1805 
1806                     if (add_nlist)
1807                     {
1808                         uint64_t symbol_value = nlist.n_value;
1809                         bool symbol_name_is_mangled = false;
1810 
1811                         if (symbol_name_non_abi_mangled)
1812                         {
1813                             sym[sym_idx].GetMangled().SetMangledName (symbol_name_non_abi_mangled);
1814                             sym[sym_idx].GetMangled().SetDemangledName (symbol_name);
1815                         }
1816                         else
1817                         {
1818                             if (symbol_name && symbol_name[0] == '_')
1819                             {
1820                                 symbol_name_is_mangled = symbol_name[1] == '_';
1821                                 symbol_name++;  // Skip the leading underscore
1822                             }
1823 
1824                             if (symbol_name)
1825                             {
1826                                 sym[sym_idx].GetMangled().SetValue(symbol_name, symbol_name_is_mangled);
1827                             }
1828                         }
1829 
1830                         if (is_debug == false)
1831                         {
1832                             if (type == eSymbolTypeCode)
1833                             {
1834                                 // See if we can find a N_FUN entry for any code symbols.
1835                                 // If we do find a match, and the name matches, then we
1836                                 // can merge the two into just the function symbol to avoid
1837                                 // duplicate entries in the symbol table
1838                                 ValueToSymbolIndexMap::const_iterator pos = N_FUN_addr_to_sym_idx.find (nlist.n_value);
1839                                 if (pos != N_FUN_addr_to_sym_idx.end())
1840                                 {
1841                                     if ((symbol_name_is_mangled == true && sym[sym_idx].GetMangled().GetMangledName() == sym[pos->second].GetMangled().GetMangledName()) ||
1842                                         (symbol_name_is_mangled == false && sym[sym_idx].GetMangled().GetDemangledName() == sym[pos->second].GetMangled().GetDemangledName()))
1843                                     {
1844                                         m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
1845                                         // We just need the flags from the linker symbol, so put these flags
1846                                         // into the N_FUN flags to avoid duplicate symbols in the symbol table
1847                                         sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
1848                                         sym[sym_idx].Clear();
1849                                         continue;
1850                                     }
1851                                 }
1852                             }
1853                             else if (type == eSymbolTypeData)
1854                             {
1855                                 // See if we can find a N_STSYM entry for any data symbols.
1856                                 // If we do find a match, and the name matches, then we
1857                                 // can merge the two into just the Static symbol to avoid
1858                                 // duplicate entries in the symbol table
1859                                 ValueToSymbolIndexMap::const_iterator pos = N_STSYM_addr_to_sym_idx.find (nlist.n_value);
1860                                 if (pos != N_STSYM_addr_to_sym_idx.end())
1861                                 {
1862                                     if ((symbol_name_is_mangled == true && sym[sym_idx].GetMangled().GetMangledName() == sym[pos->second].GetMangled().GetMangledName()) ||
1863                                         (symbol_name_is_mangled == false && sym[sym_idx].GetMangled().GetDemangledName() == sym[pos->second].GetMangled().GetDemangledName()))
1864                                     {
1865                                         m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
1866                                         // We just need the flags from the linker symbol, so put these flags
1867                                         // into the N_STSYM flags to avoid duplicate symbols in the symbol table
1868                                         sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
1869                                         sym[sym_idx].Clear();
1870                                         continue;
1871                                     }
1872                                 }
1873                             }
1874                         }
1875                         if (symbol_section != NULL)
1876                             symbol_value -= symbol_section->GetFileAddress();
1877 
1878                         sym[sym_idx].SetID (nlist_idx);
1879                         sym[sym_idx].SetType (type);
1880                         sym[sym_idx].GetAddressRangeRef().GetBaseAddress().SetSection (symbol_section);
1881                         sym[sym_idx].GetAddressRangeRef().GetBaseAddress().SetOffset (symbol_value);
1882                         sym[sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
1883 
1884                         ++sym_idx;
1885                     }
1886                     else
1887                     {
1888                         sym[sym_idx].Clear();
1889                     }
1890 
1891                 }
1892 
1893                 // STAB N_GSYM entries end up having a symbol type eSymbolTypeGlobal and when the symbol value
1894                 // is zero, the address of the global ends up being in a non-STAB entry. Try and fix up all
1895                 // such entries by figuring out what the address for the global is by looking up this non-STAB
1896                 // entry and copying the value into the debug symbol's value to save us the hassle in the
1897                 // debug symbol parser.
1898 
1899                 Symbol *global_symbol = NULL;
1900                 for (nlist_idx = 0;
1901                      nlist_idx < symtab_load_command.nsyms && (global_symbol = symtab->FindSymbolWithType (eSymbolTypeData, Symtab::eDebugYes, Symtab::eVisibilityAny, nlist_idx)) != NULL;
1902                      nlist_idx++)
1903                 {
1904                     if (global_symbol->GetValue().GetFileAddress() == 0)
1905                     {
1906                         std::vector<uint32_t> indexes;
1907                         if (symtab->AppendSymbolIndexesWithName (global_symbol->GetMangled().GetName(), indexes) > 0)
1908                         {
1909                             std::vector<uint32_t>::const_iterator pos;
1910                             std::vector<uint32_t>::const_iterator end = indexes.end();
1911                             for (pos = indexes.begin(); pos != end; ++pos)
1912                             {
1913                                 symbol_ptr = symtab->SymbolAtIndex(*pos);
1914                                 if (symbol_ptr != global_symbol && symbol_ptr->IsDebug() == false)
1915                                 {
1916                                     global_symbol->SetValue(symbol_ptr->GetValue());
1917                                     break;
1918                                 }
1919                             }
1920                         }
1921                     }
1922                 }
1923 
1924                 // Trim our symbols down to just what we ended up with after
1925                 // removing any symbols.
1926                 if (sym_idx < num_syms)
1927                 {
1928                     num_syms = sym_idx;
1929                     sym = symtab->Resize (num_syms);
1930                 }
1931 
1932                 // Now synthesize indirect symbols
1933                 if (m_dysymtab.nindirectsyms != 0)
1934                 {
1935                     DataExtractor indirect_symbol_index_data (m_data, m_dysymtab.indirectsymoff, m_dysymtab.nindirectsyms * 4);
1936 
1937                     if (indirect_symbol_index_data.GetByteSize())
1938                     {
1939                         NListIndexToSymbolIndexMap::const_iterator end_index_pos = m_nlist_idx_to_sym_idx.end();
1940 
1941                         for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size(); ++sect_idx)
1942                         {
1943                             if ((m_mach_sections[sect_idx].flags & SectionFlagMaskSectionType) == SectionTypeSymbolStubs)
1944                             {
1945                                 uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2;
1946                                 if (symbol_stub_byte_size == 0)
1947                                     continue;
1948 
1949                                 const uint32_t num_symbol_stubs = m_mach_sections[sect_idx].size / symbol_stub_byte_size;
1950 
1951                                 if (num_symbol_stubs == 0)
1952                                     continue;
1953 
1954                                 const uint32_t symbol_stub_index_offset = m_mach_sections[sect_idx].reserved1;
1955                                 uint32_t synthetic_stub_sym_id = symtab_load_command.nsyms;
1956                                 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx)
1957                                 {
1958                                     const uint32_t symbol_stub_index = symbol_stub_index_offset + stub_idx;
1959                                     const lldb::addr_t symbol_stub_addr = m_mach_sections[sect_idx].addr + (stub_idx * symbol_stub_byte_size);
1960                                     uint32_t symbol_stub_offset = symbol_stub_index * 4;
1961                                     if (indirect_symbol_index_data.ValidOffsetForDataOfSize(symbol_stub_offset, 4))
1962                                     {
1963                                         const uint32_t stub_sym_id = indirect_symbol_index_data.GetU32 (&symbol_stub_offset);
1964                                         if (stub_sym_id & (IndirectSymbolAbsolute | IndirectSymbolLocal))
1965                                             continue;
1966 
1967                                         NListIndexToSymbolIndexMap::const_iterator index_pos = m_nlist_idx_to_sym_idx.find (stub_sym_id);
1968                                         Symbol *stub_symbol = NULL;
1969                                         if (index_pos != end_index_pos)
1970                                         {
1971                                             // We have a remapping from the original nlist index to
1972                                             // a current symbol index, so just look this up by index
1973                                             stub_symbol = symtab->SymbolAtIndex (index_pos->second);
1974                                         }
1975                                         else
1976                                         {
1977                                             // We need to lookup a symbol using the original nlist
1978                                             // symbol index since this index is coming from the
1979                                             // S_SYMBOL_STUBS
1980                                             stub_symbol = symtab->FindSymbolByID (stub_sym_id);
1981                                         }
1982 
1983                                         assert (stub_symbol);
1984                                         if (stub_symbol)
1985                                         {
1986                                             Address so_addr(symbol_stub_addr, section_list);
1987 
1988                                             if (stub_symbol->GetType() == eSymbolTypeUndefined)
1989                                             {
1990                                                 // Change the external symbol into a trampoline that makes sense
1991                                                 // These symbols were N_UNDF N_EXT, and are useless to us, so we
1992                                                 // can re-use them so we don't have to make up a synthetic symbol
1993                                                 // for no good reason.
1994                                                 stub_symbol->SetType (eSymbolTypeTrampoline);
1995                                                 stub_symbol->SetExternal (false);
1996                                                 stub_symbol->GetAddressRangeRef().GetBaseAddress() = so_addr;
1997                                                 stub_symbol->GetAddressRangeRef().SetByteSize (symbol_stub_byte_size);
1998                                             }
1999                                             else
2000                                             {
2001                                                 // Make a synthetic symbol to describe the trampoline stub
2002                                                 if (sym_idx >= num_syms)
2003                                                     sym = symtab->Resize (++num_syms);
2004                                                 sym[sym_idx].SetID (synthetic_stub_sym_id++);
2005                                                 sym[sym_idx].GetMangled() = stub_symbol->GetMangled();
2006                                                 sym[sym_idx].SetType (eSymbolTypeTrampoline);
2007                                                 sym[sym_idx].SetIsSynthetic (true);
2008                                                 sym[sym_idx].GetAddressRangeRef().GetBaseAddress() = so_addr;
2009                                                 sym[sym_idx].GetAddressRangeRef().SetByteSize (symbol_stub_byte_size);
2010                                                 ++sym_idx;
2011                                             }
2012                                         }
2013                                     }
2014                                 }
2015                             }
2016                         }
2017                     }
2018                 }
2019                 return symtab->GetNumSymbols();
2020             }
2021         }
2022         offset = cmd_offset + symtab_load_command.cmdsize;
2023     }
2024     return 0;
2025 }
2026 
2027 
2028 void
2029 ObjectFileMachO::Dump (Stream *s)
2030 {
2031     lldb_private::Mutex::Locker locker(m_mutex);
2032     s->Printf("%p: ", this);
2033     s->Indent();
2034     if (m_header.magic == HeaderMagic64 || m_header.magic == HeaderMagic64Swapped)
2035         s->PutCString("ObjectFileMachO64");
2036     else
2037         s->PutCString("ObjectFileMachO32");
2038 
2039     ArchSpec header_arch(eArchTypeMachO, m_header.cputype, m_header.cpusubtype);
2040 
2041     *s << ", file = '" << m_file << "', arch = " << header_arch.GetArchitectureName() << "\n";
2042 
2043     if (m_sections_ap.get())
2044         m_sections_ap->Dump(s, NULL, true, UINT32_MAX);
2045 
2046     if (m_symtab_ap.get())
2047         m_symtab_ap->Dump(s, NULL, eSortOrderNone);
2048 }
2049 
2050 
2051 bool
2052 ObjectFileMachO::GetUUID (lldb_private::UUID* uuid)
2053 {
2054     lldb_private::Mutex::Locker locker(m_mutex);
2055     struct uuid_command load_cmd;
2056     uint32_t offset = MachHeaderSizeFromMagic(m_header.magic);
2057     uint32_t i;
2058     for (i=0; i<m_header.ncmds; ++i)
2059     {
2060         const uint32_t cmd_offset = offset;
2061         if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
2062             break;
2063 
2064         if (load_cmd.cmd == LoadCommandUUID)
2065         {
2066             const uint8_t *uuid_bytes = m_data.PeekData(offset, 16);
2067             if (uuid_bytes)
2068             {
2069                 uuid->SetBytes (uuid_bytes);
2070                 return true;
2071             }
2072             return false;
2073         }
2074         offset = cmd_offset + load_cmd.cmdsize;
2075     }
2076     return false;
2077 }
2078 
2079 
2080 uint32_t
2081 ObjectFileMachO::GetDependentModules (FileSpecList& files)
2082 {
2083     lldb_private::Mutex::Locker locker(m_mutex);
2084     struct load_command load_cmd;
2085     uint32_t offset = MachHeaderSizeFromMagic(m_header.magic);
2086     uint32_t count = 0;
2087     const bool resolve_path = false; // Don't resolve the dependend file paths since they may not reside on this system
2088     uint32_t i;
2089     for (i=0; i<m_header.ncmds; ++i)
2090     {
2091         const uint32_t cmd_offset = offset;
2092         if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
2093             break;
2094 
2095         switch (load_cmd.cmd)
2096         {
2097         case LoadCommandDylibLoad:
2098         case LoadCommandDylibLoadWeak:
2099         case LoadCommandDylibReexport:
2100         case LoadCommandDynamicLinkerLoad:
2101         case LoadCommandFixedVMShlibLoad:
2102         case LoadCommandDylibLoadUpward:
2103             {
2104                 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
2105                 const char *path = m_data.PeekCStr(name_offset);
2106                 // Skip any path that starts with '@' since these are usually:
2107                 // @executable_path/.../file
2108                 // @rpath/.../file
2109                 if (path && path[0] != '@')
2110                 {
2111                     FileSpec file_spec(path, resolve_path);
2112                     if (files.AppendIfUnique(file_spec))
2113                         count++;
2114                 }
2115             }
2116             break;
2117 
2118         default:
2119             break;
2120         }
2121         offset = cmd_offset + load_cmd.cmdsize;
2122     }
2123     return count;
2124 }
2125 
2126 lldb_private::Address
2127 ObjectFileMachO::GetEntryPointAddress ()
2128 {
2129     // If the object file is not an executable it can't hold the entry point.  m_entry_point_address
2130     // is initialized to an invalid address, so we can just return that.
2131     // If m_entry_point_address is valid it means we've found it already, so return the cached value.
2132 
2133     if (!IsExecutable() || m_entry_point_address.IsValid())
2134         return m_entry_point_address;
2135 
2136     // Otherwise, look for the UnixThread or Thread command.  The data for the Thread command is given in
2137     // /usr/include/mach-o.h, but it is basically:
2138     //
2139     //  uint32_t flavor  - this is the flavor argument you would pass to thread_get_state
2140     //  uint32_t count   - this is the count of longs in the thread state data
2141     //  struct XXX_thread_state state - this is the structure from <machine/thread_status.h> corresponding to the flavor.
2142     //  <repeat this trio>
2143     //
2144     // So we just keep reading the various register flavors till we find the GPR one, then read the PC out of there.
2145     // FIXME: We will need to have a "RegisterContext data provider" class at some point that can get all the registers
2146     // out of data in this form & attach them to a given thread.  That should underlie the MacOS X User process plugin,
2147     // and we'll also need it for the MacOS X Core File process plugin.  When we have that we can also use it here.
2148     //
2149     // For now we hard-code the offsets and flavors we need:
2150     //
2151     //
2152 
2153     lldb_private::Mutex::Locker locker(m_mutex);
2154     struct load_command load_cmd;
2155     uint32_t offset = MachHeaderSizeFromMagic(m_header.magic);
2156     uint32_t i;
2157     lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
2158     bool done = false;
2159 
2160     for (i=0; i<m_header.ncmds; ++i)
2161     {
2162         const uint32_t cmd_offset = offset;
2163         if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
2164             break;
2165 
2166         switch (load_cmd.cmd)
2167         {
2168         case LoadCommandUnixThread:
2169         case LoadCommandThread:
2170             {
2171                 while (offset < cmd_offset + load_cmd.cmdsize)
2172                 {
2173                     uint32_t flavor = m_data.GetU32(&offset);
2174                     uint32_t count = m_data.GetU32(&offset);
2175                     if (count == 0)
2176                     {
2177                         // We've gotten off somehow, log and exit;
2178                         return m_entry_point_address;
2179                     }
2180 
2181                     switch (m_header.cputype)
2182                     {
2183                     case llvm::MachO::CPUTypeARM:
2184                        if (flavor == 1) // ARM_THREAD_STATE from mach/arm/thread_status.h
2185                        {
2186                            offset += 60;  // This is the offset of pc in the GPR thread state data structure.
2187                            start_address = m_data.GetU32(&offset);
2188                            done = true;
2189                         }
2190                     break;
2191                     case llvm::MachO::CPUTypeI386:
2192                        if (flavor == 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
2193                        {
2194                            offset += 40;  // This is the offset of eip in the GPR thread state data structure.
2195                            start_address = m_data.GetU32(&offset);
2196                            done = true;
2197                         }
2198                     break;
2199                     case llvm::MachO::CPUTypeX86_64:
2200                        if (flavor == 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
2201                        {
2202                            offset += 16 * 8;  // This is the offset of rip in the GPR thread state data structure.
2203                            start_address = m_data.GetU64(&offset);
2204                            done = true;
2205                         }
2206                     break;
2207                     default:
2208                         return m_entry_point_address;
2209                     }
2210                     // Haven't found the GPR flavor yet, skip over the data for this flavor:
2211                     if (done)
2212                         break;
2213                     offset += count * 4;
2214                 }
2215             }
2216             break;
2217 
2218         default:
2219             break;
2220         }
2221         if (done)
2222             break;
2223 
2224         // Go to the next load command:
2225         offset = cmd_offset + load_cmd.cmdsize;
2226     }
2227 
2228     if (start_address != LLDB_INVALID_ADDRESS)
2229     {
2230         // We got the start address from the load commands, so now resolve that address in the sections
2231         // of this ObjectFile:
2232         if (!m_entry_point_address.ResolveAddressUsingFileSections (start_address, GetSectionList()))
2233         {
2234             m_entry_point_address.Clear();
2235         }
2236     }
2237     else
2238     {
2239         // We couldn't read the UnixThread load command - maybe it wasn't there.  As a fallback look for the
2240         // "start" symbol in the main executable.
2241 
2242         SymbolContextList contexts;
2243         SymbolContext context;
2244         if (!m_module->FindSymbolsWithNameAndType(ConstString ("start"), eSymbolTypeCode, contexts))
2245             return m_entry_point_address;
2246 
2247         contexts.GetContextAtIndex(0, context);
2248 
2249         m_entry_point_address = context.symbol->GetValue();
2250     }
2251 
2252     return m_entry_point_address;
2253 
2254 }
2255 
2256 lldb_private::Address
2257 ObjectFileMachO::GetHeaderAddress ()
2258 {
2259     lldb_private::Address header_addr;
2260     SectionList *section_list = GetSectionList();
2261     if (section_list)
2262     {
2263         SectionSP text_segment_sp (section_list->FindSectionByName (GetSegmentNameTEXT()));
2264         if (text_segment_sp)
2265         {
2266             header_addr.SetSection (text_segment_sp.get());
2267             header_addr.SetOffset (0);
2268         }
2269     }
2270     return header_addr;
2271 }
2272 
2273 uint32_t
2274 ObjectFileMachO::GetNumThreadContexts ()
2275 {
2276     lldb_private::Mutex::Locker locker(m_mutex);
2277     if (!m_thread_context_offsets_valid)
2278     {
2279         m_thread_context_offsets_valid = true;
2280         uint32_t offset = MachHeaderSizeFromMagic(m_header.magic);
2281         FileRangeArray::Entry file_range;
2282         thread_command thread_cmd;
2283         for (uint32_t i=0; i<m_header.ncmds; ++i)
2284         {
2285             const uint32_t cmd_offset = offset;
2286             if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL)
2287                 break;
2288 
2289             if (thread_cmd.cmd == LoadCommandThread)
2290             {
2291                 file_range.SetRangeBase (offset);
2292                 file_range.SetByteSize (thread_cmd.cmdsize - 8);
2293                 m_thread_context_offsets.Append (file_range);
2294             }
2295             offset = cmd_offset + thread_cmd.cmdsize;
2296         }
2297     }
2298     return m_thread_context_offsets.GetSize();
2299 }
2300 
2301 lldb::RegisterContextSP
2302 ObjectFileMachO::GetThreadContextAtIndex (uint32_t idx, lldb_private::Thread &thread)
2303 {
2304     lldb_private::Mutex::Locker locker(m_mutex);
2305     if (!m_thread_context_offsets_valid)
2306         GetNumThreadContexts ();
2307 
2308     lldb::RegisterContextSP reg_ctx_sp;
2309     const FileRangeArray::Entry *thread_context_file_range = m_thread_context_offsets.GetEntryAtIndex (idx);
2310 
2311     DataExtractor data (m_data,
2312                         thread_context_file_range->GetRangeBase(),
2313                         thread_context_file_range->GetByteSize());
2314 
2315     switch (m_header.cputype)
2316     {
2317         case llvm::MachO::CPUTypeARM:
2318             reg_ctx_sp.reset (new RegisterContextDarwin_arm_Mach (thread, data));
2319             break;
2320 
2321         case llvm::MachO::CPUTypeI386:
2322             reg_ctx_sp.reset (new RegisterContextDarwin_i386_Mach (thread, data));
2323             break;
2324 
2325         case llvm::MachO::CPUTypeX86_64:
2326             reg_ctx_sp.reset (new RegisterContextDarwin_x86_64_Mach (thread, data));
2327             break;
2328     }
2329     return reg_ctx_sp;
2330 }
2331 
2332 
2333 ObjectFile::Type
2334 ObjectFileMachO::CalculateType()
2335 {
2336     switch (m_header.filetype)
2337     {
2338         case HeaderFileTypeObject:                                          // 0x1u MH_OBJECT
2339             if (GetAddressByteSize () == 4)
2340             {
2341                 // 32 bit kexts are just object files, but they do have a valid
2342                 // UUID load command.
2343                 UUID uuid;
2344                 if (GetUUID(&uuid))
2345                 {
2346                     // this checking for the UUID load command is not enough
2347                     // we could eventually look for the symbol named
2348                     // "OSKextGetCurrentIdentifier" as this is required of kexts
2349                     if (m_strata == eStrataInvalid)
2350                         m_strata = eStrataKernel;
2351                     return eTypeSharedLibrary;
2352                 }
2353             }
2354             return eTypeObjectFile;
2355 
2356         case HeaderFileTypeExecutable:          return eTypeExecutable;     // 0x2u MH_EXECUTE
2357         case HeaderFileTypeFixedVMShlib:        return eTypeSharedLibrary;  // 0x3u MH_FVMLIB
2358         case HeaderFileTypeCore:                return eTypeCoreFile;       // 0x4u MH_CORE
2359         case HeaderFileTypePreloadedExecutable: return eTypeSharedLibrary;  // 0x5u MH_PRELOAD
2360         case HeaderFileTypeDynamicShlib:        return eTypeSharedLibrary;  // 0x6u MH_DYLIB
2361         case HeaderFileTypeDynamicLinkEditor:   return eTypeDynamicLinker;  // 0x7u MH_DYLINKER
2362         case HeaderFileTypeBundle:              return eTypeSharedLibrary;  // 0x8u MH_BUNDLE
2363         case HeaderFileTypeDynamicShlibStub:    return eTypeStubLibrary;    // 0x9u MH_DYLIB_STUB
2364         case HeaderFileTypeDSYM:                return eTypeDebugInfo;      // 0xAu MH_DSYM
2365         case HeaderFileTypeKextBundle:          return eTypeSharedLibrary;  // 0xBu MH_KEXT_BUNDLE
2366         default:
2367             break;
2368     }
2369     return eTypeUnknown;
2370 }
2371 
2372 ObjectFile::Strata
2373 ObjectFileMachO::CalculateStrata()
2374 {
2375     switch (m_header.filetype)
2376     {
2377         case HeaderFileTypeObject:      // 0x1u MH_OBJECT
2378             {
2379                 // 32 bit kexts are just object files, but they do have a valid
2380                 // UUID load command.
2381                 UUID uuid;
2382                 if (GetUUID(&uuid))
2383                 {
2384                     // this checking for the UUID load command is not enough
2385                     // we could eventually look for the symbol named
2386                     // "OSKextGetCurrentIdentifier" as this is required of kexts
2387                     if (m_type == eTypeInvalid)
2388                         m_type = eTypeSharedLibrary;
2389 
2390                     return eStrataKernel;
2391                 }
2392             }
2393             return eStrataUnknown;
2394 
2395         case HeaderFileTypeExecutable:                                     // 0x2u MH_EXECUTE
2396             // Check for the MH_DYLDLINK bit in the flags
2397             if (m_header.flags & HeaderFlagBitIsDynamicLinkObject)
2398             {
2399                 return eStrataUser;
2400             }
2401             else
2402             {
2403                 SectionList *section_list = GetSectionList();
2404                 if (section_list)
2405                 {
2406                     static ConstString g_kld_section_name ("__KLD");
2407                     if (section_list->FindSectionByName(g_kld_section_name))
2408                         return eStrataKernel;
2409                 }
2410             }
2411             return eStrataRawImage;
2412 
2413         case HeaderFileTypeFixedVMShlib:        return eStrataUser;         // 0x3u MH_FVMLIB
2414         case HeaderFileTypeCore:                return eStrataUnknown;      // 0x4u MH_CORE
2415         case HeaderFileTypePreloadedExecutable: return eStrataRawImage;     // 0x5u MH_PRELOAD
2416         case HeaderFileTypeDynamicShlib:        return eStrataUser;         // 0x6u MH_DYLIB
2417         case HeaderFileTypeDynamicLinkEditor:   return eStrataUser;         // 0x7u MH_DYLINKER
2418         case HeaderFileTypeBundle:              return eStrataUser;         // 0x8u MH_BUNDLE
2419         case HeaderFileTypeDynamicShlibStub:    return eStrataUser;         // 0x9u MH_DYLIB_STUB
2420         case HeaderFileTypeDSYM:                return eStrataUnknown;      // 0xAu MH_DSYM
2421         case HeaderFileTypeKextBundle:          return eStrataKernel;       // 0xBu MH_KEXT_BUNDLE
2422         default:
2423             break;
2424     }
2425     return eStrataUnknown;
2426 }
2427 
2428 
2429 bool
2430 ObjectFileMachO::GetArchitecture (ArchSpec &arch)
2431 {
2432     lldb_private::Mutex::Locker locker(m_mutex);
2433     arch.SetArchitecture (eArchTypeMachO, m_header.cputype, m_header.cpusubtype);
2434 
2435     // Files with type MH_PRELOAD are currently used in cases where the image
2436     // debugs at the addresses in the file itself. Below we set the OS to
2437     // unknown to make sure we use the DynamicLoaderStatic()...
2438     if (m_header.filetype == HeaderFileTypePreloadedExecutable)
2439     {
2440         arch.GetTriple().setOS (llvm::Triple::UnknownOS);
2441     }
2442 
2443     return true;
2444 }
2445 
2446 
2447 //------------------------------------------------------------------
2448 // PluginInterface protocol
2449 //------------------------------------------------------------------
2450 const char *
2451 ObjectFileMachO::GetPluginName()
2452 {
2453     return "ObjectFileMachO";
2454 }
2455 
2456 const char *
2457 ObjectFileMachO::GetShortPluginName()
2458 {
2459     return GetPluginNameStatic();
2460 }
2461 
2462 uint32_t
2463 ObjectFileMachO::GetPluginVersion()
2464 {
2465     return 1;
2466 }
2467 
2468