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/lldb-private-log.h"
16 #include "lldb/Core/ArchSpec.h"
17 #include "lldb/Core/DataBuffer.h"
18 #include "lldb/Core/Debugger.h"
19 #include "lldb/Core/FileSpecList.h"
20 #include "lldb/Core/Log.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Core/ModuleSpec.h"
23 #include "lldb/Core/PluginManager.h"
24 #include "lldb/Core/RangeMap.h"
25 #include "lldb/Core/Section.h"
26 #include "lldb/Core/StreamFile.h"
27 #include "lldb/Core/StreamString.h"
28 #include "lldb/Core/Timer.h"
29 #include "lldb/Core/UUID.h"
30 #include "lldb/Host/Host.h"
31 #include "lldb/Host/FileSpec.h"
32 #include "lldb/Symbol/ClangNamespaceDecl.h"
33 #include "lldb/Symbol/DWARFCallFrameInfo.h"
34 #include "lldb/Symbol/ObjectFile.h"
35 #include "lldb/Target/Platform.h"
36 #include "lldb/Target/Process.h"
37 #include "lldb/Target/Target.h"
38 #include "Plugins/Process/Utility/RegisterContextDarwin_arm.h"
39 #include "Plugins/Process/Utility/RegisterContextDarwin_i386.h"
40 #include "Plugins/Process/Utility/RegisterContextDarwin_x86_64.h"
41 
42 #if defined (__APPLE__) && defined (__arm__)
43 // GetLLDBSharedCacheUUID() needs to call dlsym()
44 #include <dlfcn.h>
45 #endif
46 
47 #ifndef __APPLE__
48 #include "Utility/UuidCompatibility.h"
49 #endif
50 
51 using namespace lldb;
52 using namespace lldb_private;
53 using namespace llvm::MachO;
54 
55 class RegisterContextDarwin_x86_64_Mach : public RegisterContextDarwin_x86_64
56 {
57 public:
58     RegisterContextDarwin_x86_64_Mach (lldb_private::Thread &thread, const DataExtractor &data) :
59         RegisterContextDarwin_x86_64 (thread, 0)
60     {
61         SetRegisterDataFrom_LC_THREAD (data);
62     }
63 
64     virtual void
65     InvalidateAllRegisters ()
66     {
67         // Do nothing... registers are always valid...
68     }
69 
70     void
71     SetRegisterDataFrom_LC_THREAD (const DataExtractor &data)
72     {
73         lldb::offset_t offset = 0;
74         SetError (GPRRegSet, Read, -1);
75         SetError (FPURegSet, Read, -1);
76         SetError (EXCRegSet, Read, -1);
77         bool done = false;
78 
79         while (!done)
80         {
81             int flavor = data.GetU32 (&offset);
82             if (flavor == 0)
83                 done = true;
84             else
85             {
86                 uint32_t i;
87                 uint32_t count = data.GetU32 (&offset);
88                 switch (flavor)
89                 {
90                     case GPRRegSet:
91                         for (i=0; i<count; ++i)
92                             (&gpr.rax)[i] = data.GetU64(&offset);
93                         SetError (GPRRegSet, Read, 0);
94                         done = true;
95 
96                         break;
97                     case FPURegSet:
98                         // TODO: fill in FPU regs....
99                         //SetError (FPURegSet, Read, -1);
100                         done = true;
101 
102                         break;
103                     case EXCRegSet:
104                         exc.trapno = data.GetU32(&offset);
105                         exc.err = data.GetU32(&offset);
106                         exc.faultvaddr = data.GetU64(&offset);
107                         SetError (EXCRegSet, Read, 0);
108                         done = true;
109                         break;
110                     case 7:
111                     case 8:
112                     case 9:
113                         // fancy flavors that encapsulate of the the above
114                         // falvors...
115                         break;
116 
117                     default:
118                         done = true;
119                         break;
120                 }
121             }
122         }
123     }
124 protected:
125     virtual int
126     DoReadGPR (lldb::tid_t tid, int flavor, GPR &gpr)
127     {
128         return 0;
129     }
130 
131     virtual int
132     DoReadFPU (lldb::tid_t tid, int flavor, FPU &fpu)
133     {
134         return 0;
135     }
136 
137     virtual int
138     DoReadEXC (lldb::tid_t tid, int flavor, EXC &exc)
139     {
140         return 0;
141     }
142 
143     virtual int
144     DoWriteGPR (lldb::tid_t tid, int flavor, const GPR &gpr)
145     {
146         return 0;
147     }
148 
149     virtual int
150     DoWriteFPU (lldb::tid_t tid, int flavor, const FPU &fpu)
151     {
152         return 0;
153     }
154 
155     virtual int
156     DoWriteEXC (lldb::tid_t tid, int flavor, const EXC &exc)
157     {
158         return 0;
159     }
160 };
161 
162 
163 class RegisterContextDarwin_i386_Mach : public RegisterContextDarwin_i386
164 {
165 public:
166     RegisterContextDarwin_i386_Mach (lldb_private::Thread &thread, const DataExtractor &data) :
167     RegisterContextDarwin_i386 (thread, 0)
168     {
169         SetRegisterDataFrom_LC_THREAD (data);
170     }
171 
172     virtual void
173     InvalidateAllRegisters ()
174     {
175         // Do nothing... registers are always valid...
176     }
177 
178     void
179     SetRegisterDataFrom_LC_THREAD (const DataExtractor &data)
180     {
181         lldb::offset_t offset = 0;
182         SetError (GPRRegSet, Read, -1);
183         SetError (FPURegSet, Read, -1);
184         SetError (EXCRegSet, Read, -1);
185         bool done = false;
186 
187         while (!done)
188         {
189             int flavor = data.GetU32 (&offset);
190             if (flavor == 0)
191                 done = true;
192             else
193             {
194                 uint32_t i;
195                 uint32_t count = data.GetU32 (&offset);
196                 switch (flavor)
197                 {
198                     case GPRRegSet:
199                         for (i=0; i<count; ++i)
200                             (&gpr.eax)[i] = data.GetU32(&offset);
201                         SetError (GPRRegSet, Read, 0);
202                         done = true;
203 
204                         break;
205                     case FPURegSet:
206                         // TODO: fill in FPU regs....
207                         //SetError (FPURegSet, Read, -1);
208                         done = true;
209 
210                         break;
211                     case EXCRegSet:
212                         exc.trapno = data.GetU32(&offset);
213                         exc.err = data.GetU32(&offset);
214                         exc.faultvaddr = data.GetU32(&offset);
215                         SetError (EXCRegSet, Read, 0);
216                         done = true;
217                         break;
218                     case 7:
219                     case 8:
220                     case 9:
221                         // fancy flavors that encapsulate of the the above
222                         // falvors...
223                         break;
224 
225                     default:
226                         done = true;
227                         break;
228                 }
229             }
230         }
231     }
232 protected:
233     virtual int
234     DoReadGPR (lldb::tid_t tid, int flavor, GPR &gpr)
235     {
236         return 0;
237     }
238 
239     virtual int
240     DoReadFPU (lldb::tid_t tid, int flavor, FPU &fpu)
241     {
242         return 0;
243     }
244 
245     virtual int
246     DoReadEXC (lldb::tid_t tid, int flavor, EXC &exc)
247     {
248         return 0;
249     }
250 
251     virtual int
252     DoWriteGPR (lldb::tid_t tid, int flavor, const GPR &gpr)
253     {
254         return 0;
255     }
256 
257     virtual int
258     DoWriteFPU (lldb::tid_t tid, int flavor, const FPU &fpu)
259     {
260         return 0;
261     }
262 
263     virtual int
264     DoWriteEXC (lldb::tid_t tid, int flavor, const EXC &exc)
265     {
266         return 0;
267     }
268 };
269 
270 class RegisterContextDarwin_arm_Mach : public RegisterContextDarwin_arm
271 {
272 public:
273     RegisterContextDarwin_arm_Mach (lldb_private::Thread &thread, const DataExtractor &data) :
274         RegisterContextDarwin_arm (thread, 0)
275     {
276         SetRegisterDataFrom_LC_THREAD (data);
277     }
278 
279     virtual void
280     InvalidateAllRegisters ()
281     {
282         // Do nothing... registers are always valid...
283     }
284 
285     void
286     SetRegisterDataFrom_LC_THREAD (const DataExtractor &data)
287     {
288         lldb::offset_t offset = 0;
289         SetError (GPRRegSet, Read, -1);
290         SetError (FPURegSet, Read, -1);
291         SetError (EXCRegSet, Read, -1);
292         bool done = false;
293 
294         while (!done)
295         {
296             int flavor = data.GetU32 (&offset);
297             uint32_t count = data.GetU32 (&offset);
298             lldb::offset_t next_thread_state = offset + (count * 4);
299             switch (flavor)
300             {
301                 case GPRRegSet:
302                     for (uint32_t i=0; i<count; ++i)
303                     {
304                         gpr.r[i] = data.GetU32(&offset);
305                     }
306 
307                     // Note that gpr.cpsr is also copied by the above loop; this loop technically extends
308                     // one element past the end of the gpr.r[] array.
309 
310                     SetError (GPRRegSet, Read, 0);
311                     offset = next_thread_state;
312                     break;
313 
314                 case FPURegSet:
315                     {
316                         uint8_t  *fpu_reg_buf = (uint8_t*) &fpu.floats.s[0];
317                         const int fpu_reg_buf_size = sizeof (fpu.floats);
318                         if (data.ExtractBytes (offset, fpu_reg_buf_size, eByteOrderLittle, fpu_reg_buf) == fpu_reg_buf_size)
319                         {
320                             offset += fpu_reg_buf_size;
321                             fpu.fpscr = data.GetU32(&offset);
322                             SetError (FPURegSet, Read, 0);
323                         }
324                         else
325                         {
326                             done = true;
327                         }
328                     }
329                     offset = next_thread_state;
330                     break;
331 
332                 case EXCRegSet:
333                     if (count == 3)
334                     {
335                         exc.exception = data.GetU32(&offset);
336                         exc.fsr = data.GetU32(&offset);
337                         exc.far = data.GetU32(&offset);
338                         SetError (EXCRegSet, Read, 0);
339                     }
340                     done = true;
341                     offset = next_thread_state;
342                     break;
343 
344                 // Unknown register set flavor, stop trying to parse.
345                 default:
346                     done = true;
347             }
348         }
349     }
350 protected:
351     virtual int
352     DoReadGPR (lldb::tid_t tid, int flavor, GPR &gpr)
353     {
354         return -1;
355     }
356 
357     virtual int
358     DoReadFPU (lldb::tid_t tid, int flavor, FPU &fpu)
359     {
360         return -1;
361     }
362 
363     virtual int
364     DoReadEXC (lldb::tid_t tid, int flavor, EXC &exc)
365     {
366         return -1;
367     }
368 
369     virtual int
370     DoReadDBG (lldb::tid_t tid, int flavor, DBG &dbg)
371     {
372         return -1;
373     }
374 
375     virtual int
376     DoWriteGPR (lldb::tid_t tid, int flavor, const GPR &gpr)
377     {
378         return 0;
379     }
380 
381     virtual int
382     DoWriteFPU (lldb::tid_t tid, int flavor, const FPU &fpu)
383     {
384         return 0;
385     }
386 
387     virtual int
388     DoWriteEXC (lldb::tid_t tid, int flavor, const EXC &exc)
389     {
390         return 0;
391     }
392 
393     virtual int
394     DoWriteDBG (lldb::tid_t tid, int flavor, const DBG &dbg)
395     {
396         return -1;
397     }
398 };
399 
400 static uint32_t
401 MachHeaderSizeFromMagic(uint32_t magic)
402 {
403     switch (magic)
404     {
405         case MH_MAGIC:
406         case MH_CIGAM:
407             return sizeof(struct mach_header);
408 
409         case MH_MAGIC_64:
410         case MH_CIGAM_64:
411             return sizeof(struct mach_header_64);
412             break;
413 
414         default:
415             break;
416     }
417     return 0;
418 }
419 
420 #define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008
421 
422 void
423 ObjectFileMachO::Initialize()
424 {
425     PluginManager::RegisterPlugin (GetPluginNameStatic(),
426                                    GetPluginDescriptionStatic(),
427                                    CreateInstance,
428                                    CreateMemoryInstance,
429                                    GetModuleSpecifications);
430 }
431 
432 void
433 ObjectFileMachO::Terminate()
434 {
435     PluginManager::UnregisterPlugin (CreateInstance);
436 }
437 
438 
439 lldb_private::ConstString
440 ObjectFileMachO::GetPluginNameStatic()
441 {
442     static ConstString g_name("mach-o");
443     return g_name;
444 }
445 
446 const char *
447 ObjectFileMachO::GetPluginDescriptionStatic()
448 {
449     return "Mach-o object file reader (32 and 64 bit)";
450 }
451 
452 ObjectFile *
453 ObjectFileMachO::CreateInstance (const lldb::ModuleSP &module_sp,
454                                  DataBufferSP& data_sp,
455                                  lldb::offset_t data_offset,
456                                  const FileSpec* file,
457                                  lldb::offset_t file_offset,
458                                  lldb::offset_t length)
459 {
460     if (!data_sp)
461     {
462         data_sp = file->MemoryMapFileContents(file_offset, length);
463         data_offset = 0;
464     }
465 
466     if (ObjectFileMachO::MagicBytesMatch(data_sp, data_offset, length))
467     {
468         // Update the data to contain the entire file if it doesn't already
469         if (data_sp->GetByteSize() < length)
470         {
471             data_sp = file->MemoryMapFileContents(file_offset, length);
472             data_offset = 0;
473         }
474         std::unique_ptr<ObjectFile> objfile_ap(new ObjectFileMachO (module_sp, data_sp, data_offset, file, file_offset, length));
475         if (objfile_ap.get() && objfile_ap->ParseHeader())
476             return objfile_ap.release();
477     }
478     return NULL;
479 }
480 
481 ObjectFile *
482 ObjectFileMachO::CreateMemoryInstance (const lldb::ModuleSP &module_sp,
483                                        DataBufferSP& data_sp,
484                                        const ProcessSP &process_sp,
485                                        lldb::addr_t header_addr)
486 {
487     if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize()))
488     {
489         std::unique_ptr<ObjectFile> objfile_ap(new ObjectFileMachO (module_sp, data_sp, process_sp, header_addr));
490         if (objfile_ap.get() && objfile_ap->ParseHeader())
491             return objfile_ap.release();
492     }
493     return NULL;
494 }
495 
496 size_t
497 ObjectFileMachO::GetModuleSpecifications (const lldb_private::FileSpec& file,
498                                           lldb::DataBufferSP& data_sp,
499                                           lldb::offset_t data_offset,
500                                           lldb::offset_t file_offset,
501                                           lldb::offset_t length,
502                                           lldb_private::ModuleSpecList &specs)
503 {
504     const size_t initial_count = specs.GetSize();
505 
506     if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize()))
507     {
508         DataExtractor data;
509         data.SetData(data_sp);
510         llvm::MachO::mach_header header;
511         if (ParseHeader (data, &data_offset, header))
512         {
513             if (header.sizeofcmds >= data_sp->GetByteSize())
514             {
515                 data_sp = file.ReadFileContents(file_offset, header.sizeofcmds);
516                 data.SetData(data_sp);
517                 data_offset = MachHeaderSizeFromMagic(header.magic);
518             }
519             if (data_sp)
520             {
521                 ModuleSpec spec;
522                 spec.GetFileSpec() = file;
523                 spec.GetArchitecture().SetArchitecture(eArchTypeMachO,
524                                                        header.cputype,
525                                                        header.cpusubtype);
526                 if (header.filetype == MH_PRELOAD) // 0x5u
527                 {
528                     // Set OS to "unknown" - this is a standalone binary with no dyld et al
529                     spec.GetArchitecture().GetTriple().setOS (llvm::Triple::UnknownOS);
530                 }
531                 if (spec.GetArchitecture().IsValid())
532                 {
533                     GetUUID (header, data, data_offset, spec.GetUUID());
534                     specs.Append(spec);
535                 }
536             }
537         }
538     }
539     return specs.GetSize() - initial_count;
540 }
541 
542 
543 
544 const ConstString &
545 ObjectFileMachO::GetSegmentNameTEXT()
546 {
547     static ConstString g_segment_name_TEXT ("__TEXT");
548     return g_segment_name_TEXT;
549 }
550 
551 const ConstString &
552 ObjectFileMachO::GetSegmentNameDATA()
553 {
554     static ConstString g_segment_name_DATA ("__DATA");
555     return g_segment_name_DATA;
556 }
557 
558 const ConstString &
559 ObjectFileMachO::GetSegmentNameOBJC()
560 {
561     static ConstString g_segment_name_OBJC ("__OBJC");
562     return g_segment_name_OBJC;
563 }
564 
565 const ConstString &
566 ObjectFileMachO::GetSegmentNameLINKEDIT()
567 {
568     static ConstString g_section_name_LINKEDIT ("__LINKEDIT");
569     return g_section_name_LINKEDIT;
570 }
571 
572 const ConstString &
573 ObjectFileMachO::GetSectionNameEHFrame()
574 {
575     static ConstString g_section_name_eh_frame ("__eh_frame");
576     return g_section_name_eh_frame;
577 }
578 
579 bool
580 ObjectFileMachO::MagicBytesMatch (DataBufferSP& data_sp,
581                                   lldb::addr_t data_offset,
582                                   lldb::addr_t data_length)
583 {
584     DataExtractor data;
585     data.SetData (data_sp, data_offset, data_length);
586     lldb::offset_t offset = 0;
587     uint32_t magic = data.GetU32(&offset);
588     return MachHeaderSizeFromMagic(magic) != 0;
589 }
590 
591 
592 ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp,
593                                  DataBufferSP& data_sp,
594                                  lldb::offset_t data_offset,
595                                  const FileSpec* file,
596                                  lldb::offset_t file_offset,
597                                  lldb::offset_t length) :
598     ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
599     m_mach_segments(),
600     m_mach_sections(),
601     m_entry_point_address(),
602     m_thread_context_offsets(),
603     m_thread_context_offsets_valid(false)
604 {
605     ::memset (&m_header, 0, sizeof(m_header));
606     ::memset (&m_dysymtab, 0, sizeof(m_dysymtab));
607 }
608 
609 ObjectFileMachO::ObjectFileMachO (const lldb::ModuleSP &module_sp,
610                                   lldb::DataBufferSP& header_data_sp,
611                                   const lldb::ProcessSP &process_sp,
612                                   lldb::addr_t header_addr) :
613     ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
614     m_mach_segments(),
615     m_mach_sections(),
616     m_entry_point_address(),
617     m_thread_context_offsets(),
618     m_thread_context_offsets_valid(false)
619 {
620     ::memset (&m_header, 0, sizeof(m_header));
621     ::memset (&m_dysymtab, 0, sizeof(m_dysymtab));
622 }
623 
624 ObjectFileMachO::~ObjectFileMachO()
625 {
626 }
627 
628 bool
629 ObjectFileMachO::ParseHeader (DataExtractor &data,
630                               lldb::offset_t *data_offset_ptr,
631                               llvm::MachO::mach_header &header)
632 {
633     data.SetByteOrder (lldb::endian::InlHostByteOrder());
634     // Leave magic in the original byte order
635     header.magic = data.GetU32(data_offset_ptr);
636     bool can_parse = false;
637     bool is_64_bit = false;
638     switch (header.magic)
639     {
640         case MH_MAGIC:
641             data.SetByteOrder (lldb::endian::InlHostByteOrder());
642             data.SetAddressByteSize(4);
643             can_parse = true;
644             break;
645 
646         case MH_MAGIC_64:
647             data.SetByteOrder (lldb::endian::InlHostByteOrder());
648             data.SetAddressByteSize(8);
649             can_parse = true;
650             is_64_bit = true;
651             break;
652 
653         case MH_CIGAM:
654             data.SetByteOrder(lldb::endian::InlHostByteOrder() == eByteOrderBig ? eByteOrderLittle : eByteOrderBig);
655             data.SetAddressByteSize(4);
656             can_parse = true;
657             break;
658 
659         case MH_CIGAM_64:
660             data.SetByteOrder(lldb::endian::InlHostByteOrder() == eByteOrderBig ? eByteOrderLittle : eByteOrderBig);
661             data.SetAddressByteSize(8);
662             is_64_bit = true;
663             can_parse = true;
664             break;
665 
666         default:
667             break;
668     }
669 
670     if (can_parse)
671     {
672         data.GetU32(data_offset_ptr, &header.cputype, 6);
673         if (is_64_bit)
674             *data_offset_ptr += 4;
675         return true;
676     }
677     else
678     {
679         memset(&header, 0, sizeof(header));
680     }
681     return false;
682 }
683 
684 bool
685 ObjectFileMachO::ParseHeader ()
686 {
687     ModuleSP module_sp(GetModule());
688     if (module_sp)
689     {
690         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
691         bool can_parse = false;
692         lldb::offset_t offset = 0;
693         m_data.SetByteOrder (lldb::endian::InlHostByteOrder());
694         // Leave magic in the original byte order
695         m_header.magic = m_data.GetU32(&offset);
696         switch (m_header.magic)
697         {
698         case MH_MAGIC:
699             m_data.SetByteOrder (lldb::endian::InlHostByteOrder());
700             m_data.SetAddressByteSize(4);
701             can_parse = true;
702             break;
703 
704         case MH_MAGIC_64:
705             m_data.SetByteOrder (lldb::endian::InlHostByteOrder());
706             m_data.SetAddressByteSize(8);
707             can_parse = true;
708             break;
709 
710         case MH_CIGAM:
711             m_data.SetByteOrder(lldb::endian::InlHostByteOrder() == eByteOrderBig ? eByteOrderLittle : eByteOrderBig);
712             m_data.SetAddressByteSize(4);
713             can_parse = true;
714             break;
715 
716         case MH_CIGAM_64:
717             m_data.SetByteOrder(lldb::endian::InlHostByteOrder() == eByteOrderBig ? eByteOrderLittle : eByteOrderBig);
718             m_data.SetAddressByteSize(8);
719             can_parse = true;
720             break;
721 
722         default:
723             break;
724         }
725 
726         if (can_parse)
727         {
728             m_data.GetU32(&offset, &m_header.cputype, 6);
729 
730             ArchSpec mach_arch(eArchTypeMachO, m_header.cputype, m_header.cpusubtype);
731 
732             // Check if the module has a required architecture
733             const ArchSpec &module_arch = module_sp->GetArchitecture();
734             if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch))
735                 return false;
736 
737             if (SetModulesArchitecture (mach_arch))
738             {
739                 const size_t header_and_lc_size = m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
740                 if (m_data.GetByteSize() < header_and_lc_size)
741                 {
742                     DataBufferSP data_sp;
743                     ProcessSP process_sp (m_process_wp.lock());
744                     if (process_sp)
745                     {
746                         data_sp = ReadMemory (process_sp, m_memory_addr, header_and_lc_size);
747                     }
748                     else
749                     {
750                         // Read in all only the load command data from the file on disk
751                         data_sp = m_file.ReadFileContents(m_file_offset, header_and_lc_size);
752                         if (data_sp->GetByteSize() != header_and_lc_size)
753                             return false;
754                     }
755                     if (data_sp)
756                         m_data.SetData (data_sp);
757                 }
758             }
759             return true;
760         }
761         else
762         {
763             memset(&m_header, 0, sizeof(struct mach_header));
764         }
765     }
766     return false;
767 }
768 
769 
770 ByteOrder
771 ObjectFileMachO::GetByteOrder () const
772 {
773     return m_data.GetByteOrder ();
774 }
775 
776 bool
777 ObjectFileMachO::IsExecutable() const
778 {
779     return m_header.filetype == MH_EXECUTE;
780 }
781 
782 uint32_t
783 ObjectFileMachO::GetAddressByteSize () const
784 {
785     return m_data.GetAddressByteSize ();
786 }
787 
788 AddressClass
789 ObjectFileMachO::GetAddressClass (lldb::addr_t file_addr)
790 {
791     Symtab *symtab = GetSymtab();
792     if (symtab)
793     {
794         Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
795         if (symbol)
796         {
797             if (symbol->ValueIsAddress())
798             {
799                 SectionSP section_sp (symbol->GetAddress().GetSection());
800                 if (section_sp)
801                 {
802                     const lldb::SectionType section_type = section_sp->GetType();
803                     switch (section_type)
804                     {
805                     case eSectionTypeInvalid:               return eAddressClassUnknown;
806                     case eSectionTypeCode:
807                         if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM)
808                         {
809                             // For ARM we have a bit in the n_desc field of the symbol
810                             // that tells us ARM/Thumb which is bit 0x0008.
811                             if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
812                                 return eAddressClassCodeAlternateISA;
813                         }
814                         return eAddressClassCode;
815 
816                     case eSectionTypeContainer:             return eAddressClassUnknown;
817                     case eSectionTypeData:
818                     case eSectionTypeDataCString:
819                     case eSectionTypeDataCStringPointers:
820                     case eSectionTypeDataSymbolAddress:
821                     case eSectionTypeData4:
822                     case eSectionTypeData8:
823                     case eSectionTypeData16:
824                     case eSectionTypeDataPointers:
825                     case eSectionTypeZeroFill:
826                     case eSectionTypeDataObjCMessageRefs:
827                     case eSectionTypeDataObjCCFStrings:
828                         return eAddressClassData;
829                     case eSectionTypeDebug:
830                     case eSectionTypeDWARFDebugAbbrev:
831                     case eSectionTypeDWARFDebugAranges:
832                     case eSectionTypeDWARFDebugFrame:
833                     case eSectionTypeDWARFDebugInfo:
834                     case eSectionTypeDWARFDebugLine:
835                     case eSectionTypeDWARFDebugLoc:
836                     case eSectionTypeDWARFDebugMacInfo:
837                     case eSectionTypeDWARFDebugPubNames:
838                     case eSectionTypeDWARFDebugPubTypes:
839                     case eSectionTypeDWARFDebugRanges:
840                     case eSectionTypeDWARFDebugStr:
841                     case eSectionTypeDWARFAppleNames:
842                     case eSectionTypeDWARFAppleTypes:
843                     case eSectionTypeDWARFAppleNamespaces:
844                     case eSectionTypeDWARFAppleObjC:
845                         return eAddressClassDebug;
846                     case eSectionTypeEHFrame:               return eAddressClassRuntime;
847                     case eSectionTypeELFSymbolTable:
848                     case eSectionTypeELFDynamicSymbols:
849                     case eSectionTypeELFRelocationEntries:
850                     case eSectionTypeELFDynamicLinkInfo:
851                     case eSectionTypeOther:                 return eAddressClassUnknown;
852                     }
853                 }
854             }
855 
856             const SymbolType symbol_type = symbol->GetType();
857             switch (symbol_type)
858             {
859             case eSymbolTypeAny:            return eAddressClassUnknown;
860             case eSymbolTypeAbsolute:       return eAddressClassUnknown;
861 
862             case eSymbolTypeCode:
863             case eSymbolTypeTrampoline:
864             case eSymbolTypeResolver:
865                 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM)
866                 {
867                     // For ARM we have a bit in the n_desc field of the symbol
868                     // that tells us ARM/Thumb which is bit 0x0008.
869                     if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB)
870                         return eAddressClassCodeAlternateISA;
871                 }
872                 return eAddressClassCode;
873 
874             case eSymbolTypeData:           return eAddressClassData;
875             case eSymbolTypeRuntime:        return eAddressClassRuntime;
876             case eSymbolTypeException:      return eAddressClassRuntime;
877             case eSymbolTypeSourceFile:     return eAddressClassDebug;
878             case eSymbolTypeHeaderFile:     return eAddressClassDebug;
879             case eSymbolTypeObjectFile:     return eAddressClassDebug;
880             case eSymbolTypeCommonBlock:    return eAddressClassDebug;
881             case eSymbolTypeBlock:          return eAddressClassDebug;
882             case eSymbolTypeLocal:          return eAddressClassData;
883             case eSymbolTypeParam:          return eAddressClassData;
884             case eSymbolTypeVariable:       return eAddressClassData;
885             case eSymbolTypeVariableType:   return eAddressClassDebug;
886             case eSymbolTypeLineEntry:      return eAddressClassDebug;
887             case eSymbolTypeLineHeader:     return eAddressClassDebug;
888             case eSymbolTypeScopeBegin:     return eAddressClassDebug;
889             case eSymbolTypeScopeEnd:       return eAddressClassDebug;
890             case eSymbolTypeAdditional:     return eAddressClassUnknown;
891             case eSymbolTypeCompiler:       return eAddressClassDebug;
892             case eSymbolTypeInstrumentation:return eAddressClassDebug;
893             case eSymbolTypeUndefined:      return eAddressClassUnknown;
894             case eSymbolTypeObjCClass:      return eAddressClassRuntime;
895             case eSymbolTypeObjCMetaClass:  return eAddressClassRuntime;
896             case eSymbolTypeObjCIVar:       return eAddressClassRuntime;
897             case eSymbolTypeReExported:     return eAddressClassRuntime;
898             }
899         }
900     }
901     return eAddressClassUnknown;
902 }
903 
904 Symtab *
905 ObjectFileMachO::GetSymtab()
906 {
907     ModuleSP module_sp(GetModule());
908     if (module_sp)
909     {
910         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
911         if (m_symtab_ap.get() == NULL)
912         {
913             m_symtab_ap.reset(new Symtab(this));
914             Mutex::Locker symtab_locker (m_symtab_ap->GetMutex());
915             ParseSymtab ();
916             m_symtab_ap->Finalize ();
917         }
918     }
919     return m_symtab_ap.get();
920 }
921 
922 bool
923 ObjectFileMachO::IsStripped ()
924 {
925     if (m_dysymtab.cmd == 0)
926     {
927         ModuleSP module_sp(GetModule());
928         if (module_sp)
929         {
930             lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
931             for (uint32_t i=0; i<m_header.ncmds; ++i)
932             {
933                 const lldb::offset_t load_cmd_offset = offset;
934 
935                 load_command lc;
936                 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
937                     break;
938                 if (lc.cmd == LC_DYSYMTAB)
939                 {
940                     m_dysymtab.cmd = lc.cmd;
941                     m_dysymtab.cmdsize = lc.cmdsize;
942                     if (m_data.GetU32 (&offset, &m_dysymtab.ilocalsym, (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) == NULL)
943                     {
944                         // Clear m_dysymtab if we were unable to read all items from the load command
945                         ::memset (&m_dysymtab, 0, sizeof(m_dysymtab));
946                     }
947                 }
948                 offset = load_cmd_offset + lc.cmdsize;
949             }
950         }
951     }
952     if (m_dysymtab.cmd)
953         return m_dysymtab.nlocalsym <= 1;
954     return false;
955 }
956 
957 void
958 ObjectFileMachO::CreateSections (SectionList &unified_section_list)
959 {
960     if (!m_sections_ap.get())
961     {
962         m_sections_ap.reset(new SectionList());
963 
964         const bool is_dsym = (m_header.filetype == MH_DSYM);
965         lldb::user_id_t segID = 0;
966         lldb::user_id_t sectID = 0;
967         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
968         uint32_t i;
969         const bool is_core = GetType() == eTypeCoreFile;
970         //bool dump_sections = false;
971         ModuleSP module_sp (GetModule());
972         // First look up any LC_ENCRYPTION_INFO load commands
973         typedef RangeArray<uint32_t, uint32_t, 8> EncryptedFileRanges;
974         EncryptedFileRanges encrypted_file_ranges;
975         encryption_info_command encryption_cmd;
976         for (i=0; i<m_header.ncmds; ++i)
977         {
978             const lldb::offset_t load_cmd_offset = offset;
979             if (m_data.GetU32(&offset, &encryption_cmd, 2) == NULL)
980                 break;
981 
982             if (encryption_cmd.cmd == LC_ENCRYPTION_INFO)
983             {
984                 if (m_data.GetU32(&offset, &encryption_cmd.cryptoff, 3))
985                 {
986                     if (encryption_cmd.cryptid != 0)
987                     {
988                         EncryptedFileRanges::Entry entry;
989                         entry.SetRangeBase(encryption_cmd.cryptoff);
990                         entry.SetByteSize(encryption_cmd.cryptsize);
991                         encrypted_file_ranges.Append(entry);
992                     }
993                 }
994             }
995             offset = load_cmd_offset + encryption_cmd.cmdsize;
996         }
997 
998         offset = MachHeaderSizeFromMagic(m_header.magic);
999 
1000         struct segment_command_64 load_cmd;
1001         for (i=0; i<m_header.ncmds; ++i)
1002         {
1003             const lldb::offset_t load_cmd_offset = offset;
1004             if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
1005                 break;
1006 
1007             if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
1008             {
1009                 if (m_data.GetU8(&offset, (uint8_t*)load_cmd.segname, 16))
1010                 {
1011                     bool add_section = true;
1012                     bool add_to_unified = true;
1013                     ConstString const_segname (load_cmd.segname, std::min<size_t>(strlen(load_cmd.segname), sizeof(load_cmd.segname)));
1014 
1015                     SectionSP unified_section_sp(unified_section_list.FindSectionByName(const_segname));
1016                     if (is_dsym && unified_section_sp)
1017                     {
1018                         if (const_segname == GetSegmentNameLINKEDIT())
1019                         {
1020                             // We need to keep the __LINKEDIT segment private to this object file only
1021                             add_to_unified = false;
1022                         }
1023                         else
1024                         {
1025                             // This is the dSYM file and this section has already been created by
1026                             // the object file, no need to create it.
1027                             add_section = false;
1028                         }
1029                     }
1030                     load_cmd.vmaddr = m_data.GetAddress(&offset);
1031                     load_cmd.vmsize = m_data.GetAddress(&offset);
1032                     load_cmd.fileoff = m_data.GetAddress(&offset);
1033                     load_cmd.filesize = m_data.GetAddress(&offset);
1034                     if (m_length != 0 && load_cmd.filesize != 0)
1035                     {
1036                         if (load_cmd.fileoff > m_length)
1037                         {
1038                             // We have a load command that says it extends past the end of hte file.  This is likely
1039                             // a corrupt file.  We don't have any way to return an error condition here (this method
1040                             // was likely invokved from something like ObjectFile::GetSectionList()) -- all we can do
1041                             // is null out the SectionList vector and if a process has been set up, dump a message
1042                             // to stdout.  The most common case here is core file debugging with a truncated file.
1043                             const char *lc_segment_name = load_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1044                             module_sp->ReportWarning("load command %u %s has a fileoff (0x%" PRIx64 ") that extends beyond the end of the file (0x%" PRIx64 "), ignoring this section",
1045                                                    i,
1046                                                    lc_segment_name,
1047                                                    load_cmd.fileoff,
1048                                                    m_length);
1049 
1050                             load_cmd.fileoff = 0;
1051                             load_cmd.filesize = 0;
1052                         }
1053 
1054                         if (load_cmd.fileoff + load_cmd.filesize > m_length)
1055                         {
1056                             // We have a load command that says it extends past the end of hte file.  This is likely
1057                             // a corrupt file.  We don't have any way to return an error condition here (this method
1058                             // was likely invokved from something like ObjectFile::GetSectionList()) -- all we can do
1059                             // is null out the SectionList vector and if a process has been set up, dump a message
1060                             // to stdout.  The most common case here is core file debugging with a truncated file.
1061                             const char *lc_segment_name = load_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1062                             GetModule()->ReportWarning("load command %u %s has a fileoff + filesize (0x%" PRIx64 ") that extends beyond the end of the file (0x%" PRIx64 "), the segment will be truncated to match",
1063                                                      i,
1064                                                      lc_segment_name,
1065                                                      load_cmd.fileoff + load_cmd.filesize,
1066                                                      m_length);
1067 
1068                             // Tuncase the length
1069                             load_cmd.filesize = m_length - load_cmd.fileoff;
1070                         }
1071                     }
1072                     if (m_data.GetU32(&offset, &load_cmd.maxprot, 4))
1073                     {
1074 
1075                         const bool segment_is_encrypted = (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
1076 
1077                         // Keep a list of mach segments around in case we need to
1078                         // get at data that isn't stored in the abstracted Sections.
1079                         m_mach_segments.push_back (load_cmd);
1080 
1081                         // Use a segment ID of the segment index shifted left by 8 so they
1082                         // never conflict with any of the sections.
1083                         SectionSP segment_sp;
1084                         if (add_section && (const_segname || is_core))
1085                         {
1086                             segment_sp.reset(new Section (module_sp,              // Module to which this section belongs
1087                                                           this,                   // Object file to which this sections belongs
1088                                                           ++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
1089                                                           const_segname,          // Name of this section
1090                                                           eSectionTypeContainer,  // This section is a container of other sections.
1091                                                           load_cmd.vmaddr,        // File VM address == addresses as they are found in the object file
1092                                                           load_cmd.vmsize,        // VM size in bytes of this section
1093                                                           load_cmd.fileoff,       // Offset to the data for this section in the file
1094                                                           load_cmd.filesize,      // Size in bytes of this section as found in the the file
1095                                                           load_cmd.flags));       // Flags for this section
1096 
1097                             segment_sp->SetIsEncrypted (segment_is_encrypted);
1098                             m_sections_ap->AddSection(segment_sp);
1099                             if (add_to_unified)
1100                                 unified_section_list.AddSection(segment_sp);
1101                         }
1102                         else if (unified_section_sp)
1103                         {
1104                             if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr)
1105                             {
1106                                 // Check to see if the module was read from memory?
1107                                 if (module_sp->GetObjectFile()->GetHeaderAddress().IsValid())
1108                                 {
1109                                     // We have a module that is in memory and needs to have its
1110                                     // file address adjusted. We need to do this because when we
1111                                     // load a file from memory, its addresses will be slid already,
1112                                     // yet the addresses in the new symbol file will still be unslid.
1113                                     // Since everything is stored as section offset, this shouldn't
1114                                     // cause any problems.
1115 
1116                                     // Make sure we've parsed the symbol table from the
1117                                     // ObjectFile before we go around changing its Sections.
1118                                     module_sp->GetObjectFile()->GetSymtab();
1119                                     // eh_frame would present the same problems but we parse that on
1120                                     // a per-function basis as-needed so it's more difficult to
1121                                     // remove its use of the Sections.  Realistically, the environments
1122                                     // where this code path will be taken will not have eh_frame sections.
1123 
1124                                     unified_section_sp->SetFileAddress(load_cmd.vmaddr);
1125                                 }
1126                             }
1127                             m_sections_ap->AddSection(unified_section_sp);
1128                         }
1129 
1130                         struct section_64 sect64;
1131                         ::memset (&sect64, 0, sizeof(sect64));
1132                         // Push a section into our mach sections for the section at
1133                         // index zero (NO_SECT) if we don't have any mach sections yet...
1134                         if (m_mach_sections.empty())
1135                             m_mach_sections.push_back(sect64);
1136                         uint32_t segment_sect_idx;
1137                         const lldb::user_id_t first_segment_sectID = sectID + 1;
1138 
1139 
1140                         const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
1141                         for (segment_sect_idx=0; segment_sect_idx<load_cmd.nsects; ++segment_sect_idx)
1142                         {
1143                             if (m_data.GetU8(&offset, (uint8_t*)sect64.sectname, sizeof(sect64.sectname)) == NULL)
1144                                 break;
1145                             if (m_data.GetU8(&offset, (uint8_t*)sect64.segname, sizeof(sect64.segname)) == NULL)
1146                                 break;
1147                             sect64.addr = m_data.GetAddress(&offset);
1148                             sect64.size = m_data.GetAddress(&offset);
1149 
1150                             if (m_data.GetU32(&offset, &sect64.offset, num_u32s) == NULL)
1151                                 break;
1152 
1153                             // Keep a list of mach sections around in case we need to
1154                             // get at data that isn't stored in the abstracted Sections.
1155                             m_mach_sections.push_back (sect64);
1156 
1157                             if (add_section)
1158                             {
1159                                 ConstString section_name (sect64.sectname, std::min<size_t>(strlen(sect64.sectname), sizeof(sect64.sectname)));
1160                                 if (!const_segname)
1161                                 {
1162                                     // We have a segment with no name so we need to conjure up
1163                                     // segments that correspond to the section's segname if there
1164                                     // isn't already such a section. If there is such a section,
1165                                     // we resize the section so that it spans all sections.
1166                                     // We also mark these sections as fake so address matches don't
1167                                     // hit if they land in the gaps between the child sections.
1168                                     const_segname.SetTrimmedCStringWithLength(sect64.segname, sizeof(sect64.segname));
1169                                     segment_sp = unified_section_list.FindSectionByName (const_segname);
1170                                     if (segment_sp.get())
1171                                     {
1172                                         Section *segment = segment_sp.get();
1173                                         // Grow the section size as needed.
1174                                         const lldb::addr_t sect64_min_addr = sect64.addr;
1175                                         const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
1176                                         const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
1177                                         const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
1178                                         const lldb::addr_t curr_seg_max_addr = curr_seg_min_addr + curr_seg_byte_size;
1179                                         if (sect64_min_addr >= curr_seg_min_addr)
1180                                         {
1181                                             const lldb::addr_t new_seg_byte_size = sect64_max_addr - curr_seg_min_addr;
1182                                             // Only grow the section size if needed
1183                                             if (new_seg_byte_size > curr_seg_byte_size)
1184                                                 segment->SetByteSize (new_seg_byte_size);
1185                                         }
1186                                         else
1187                                         {
1188                                             // We need to change the base address of the segment and
1189                                             // adjust the child section offsets for all existing children.
1190                                             const lldb::addr_t slide_amount = sect64_min_addr - curr_seg_min_addr;
1191                                             segment->Slide(slide_amount, false);
1192                                             segment->GetChildren().Slide(-slide_amount, false);
1193                                             segment->SetByteSize (curr_seg_max_addr - sect64_min_addr);
1194                                         }
1195 
1196                                         // Grow the section size as needed.
1197                                         if (sect64.offset)
1198                                         {
1199                                             const lldb::addr_t segment_min_file_offset = segment->GetFileOffset();
1200                                             const lldb::addr_t segment_max_file_offset = segment_min_file_offset + segment->GetFileSize();
1201 
1202                                             const lldb::addr_t section_min_file_offset = sect64.offset;
1203                                             const lldb::addr_t section_max_file_offset = section_min_file_offset + sect64.size;
1204                                             const lldb::addr_t new_file_offset = std::min (section_min_file_offset, segment_min_file_offset);
1205                                             const lldb::addr_t new_file_size = std::max (section_max_file_offset, segment_max_file_offset) - new_file_offset;
1206                                             segment->SetFileOffset (new_file_offset);
1207                                             segment->SetFileSize (new_file_size);
1208                                         }
1209                                     }
1210                                     else
1211                                     {
1212                                         // Create a fake section for the section's named segment
1213                                         segment_sp.reset(new Section (segment_sp,            // Parent section
1214                                                                       module_sp,             // Module to which this section belongs
1215                                                                       this,                  // Object file to which this section belongs
1216                                                                       ++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
1217                                                                       const_segname,         // Name of this section
1218                                                                       eSectionTypeContainer, // This section is a container of other sections.
1219                                                                       sect64.addr,           // File VM address == addresses as they are found in the object file
1220                                                                       sect64.size,           // VM size in bytes of this section
1221                                                                       sect64.offset,         // Offset to the data for this section in the file
1222                                                                       sect64.offset ? sect64.size : 0,        // Size in bytes of this section as found in the the file
1223                                                                       load_cmd.flags));      // Flags for this section
1224                                         segment_sp->SetIsFake(true);
1225 
1226                                         m_sections_ap->AddSection(segment_sp);
1227                                         if (add_to_unified)
1228                                             unified_section_list.AddSection(segment_sp);
1229                                         segment_sp->SetIsEncrypted (segment_is_encrypted);
1230                                     }
1231                                 }
1232                                 assert (segment_sp.get());
1233 
1234                                 uint32_t mach_sect_type = sect64.flags & SECTION_TYPE;
1235                                 static ConstString g_sect_name_objc_data ("__objc_data");
1236                                 static ConstString g_sect_name_objc_msgrefs ("__objc_msgrefs");
1237                                 static ConstString g_sect_name_objc_selrefs ("__objc_selrefs");
1238                                 static ConstString g_sect_name_objc_classrefs ("__objc_classrefs");
1239                                 static ConstString g_sect_name_objc_superrefs ("__objc_superrefs");
1240                                 static ConstString g_sect_name_objc_const ("__objc_const");
1241                                 static ConstString g_sect_name_objc_classlist ("__objc_classlist");
1242                                 static ConstString g_sect_name_cfstring ("__cfstring");
1243 
1244                                 static ConstString g_sect_name_dwarf_debug_abbrev ("__debug_abbrev");
1245                                 static ConstString g_sect_name_dwarf_debug_aranges ("__debug_aranges");
1246                                 static ConstString g_sect_name_dwarf_debug_frame ("__debug_frame");
1247                                 static ConstString g_sect_name_dwarf_debug_info ("__debug_info");
1248                                 static ConstString g_sect_name_dwarf_debug_line ("__debug_line");
1249                                 static ConstString g_sect_name_dwarf_debug_loc ("__debug_loc");
1250                                 static ConstString g_sect_name_dwarf_debug_macinfo ("__debug_macinfo");
1251                                 static ConstString g_sect_name_dwarf_debug_pubnames ("__debug_pubnames");
1252                                 static ConstString g_sect_name_dwarf_debug_pubtypes ("__debug_pubtypes");
1253                                 static ConstString g_sect_name_dwarf_debug_ranges ("__debug_ranges");
1254                                 static ConstString g_sect_name_dwarf_debug_str ("__debug_str");
1255                                 static ConstString g_sect_name_dwarf_apple_names ("__apple_names");
1256                                 static ConstString g_sect_name_dwarf_apple_types ("__apple_types");
1257                                 static ConstString g_sect_name_dwarf_apple_namespaces ("__apple_namespac");
1258                                 static ConstString g_sect_name_dwarf_apple_objc ("__apple_objc");
1259                                 static ConstString g_sect_name_eh_frame ("__eh_frame");
1260                                 static ConstString g_sect_name_DATA ("__DATA");
1261                                 static ConstString g_sect_name_TEXT ("__TEXT");
1262 
1263                                 lldb::SectionType sect_type = eSectionTypeOther;
1264 
1265                                 if (section_name == g_sect_name_dwarf_debug_abbrev)
1266                                     sect_type = eSectionTypeDWARFDebugAbbrev;
1267                                 else if (section_name == g_sect_name_dwarf_debug_aranges)
1268                                     sect_type = eSectionTypeDWARFDebugAranges;
1269                                 else if (section_name == g_sect_name_dwarf_debug_frame)
1270                                     sect_type = eSectionTypeDWARFDebugFrame;
1271                                 else if (section_name == g_sect_name_dwarf_debug_info)
1272                                     sect_type = eSectionTypeDWARFDebugInfo;
1273                                 else if (section_name == g_sect_name_dwarf_debug_line)
1274                                     sect_type = eSectionTypeDWARFDebugLine;
1275                                 else if (section_name == g_sect_name_dwarf_debug_loc)
1276                                     sect_type = eSectionTypeDWARFDebugLoc;
1277                                 else if (section_name == g_sect_name_dwarf_debug_macinfo)
1278                                     sect_type = eSectionTypeDWARFDebugMacInfo;
1279                                 else if (section_name == g_sect_name_dwarf_debug_pubnames)
1280                                     sect_type = eSectionTypeDWARFDebugPubNames;
1281                                 else if (section_name == g_sect_name_dwarf_debug_pubtypes)
1282                                     sect_type = eSectionTypeDWARFDebugPubTypes;
1283                                 else if (section_name == g_sect_name_dwarf_debug_ranges)
1284                                     sect_type = eSectionTypeDWARFDebugRanges;
1285                                 else if (section_name == g_sect_name_dwarf_debug_str)
1286                                     sect_type = eSectionTypeDWARFDebugStr;
1287                                 else if (section_name == g_sect_name_dwarf_apple_names)
1288                                     sect_type = eSectionTypeDWARFAppleNames;
1289                                 else if (section_name == g_sect_name_dwarf_apple_types)
1290                                     sect_type = eSectionTypeDWARFAppleTypes;
1291                                 else if (section_name == g_sect_name_dwarf_apple_namespaces)
1292                                     sect_type = eSectionTypeDWARFAppleNamespaces;
1293                                 else if (section_name == g_sect_name_dwarf_apple_objc)
1294                                     sect_type = eSectionTypeDWARFAppleObjC;
1295                                 else if (section_name == g_sect_name_objc_selrefs)
1296                                     sect_type = eSectionTypeDataCStringPointers;
1297                                 else if (section_name == g_sect_name_objc_msgrefs)
1298                                     sect_type = eSectionTypeDataObjCMessageRefs;
1299                                 else if (section_name == g_sect_name_eh_frame)
1300                                     sect_type = eSectionTypeEHFrame;
1301                                 else if (section_name == g_sect_name_cfstring)
1302                                     sect_type = eSectionTypeDataObjCCFStrings;
1303                                 else if (section_name == g_sect_name_objc_data ||
1304                                          section_name == g_sect_name_objc_classrefs ||
1305                                          section_name == g_sect_name_objc_superrefs ||
1306                                          section_name == g_sect_name_objc_const ||
1307                                          section_name == g_sect_name_objc_classlist)
1308                                 {
1309                                     sect_type = eSectionTypeDataPointers;
1310                                 }
1311 
1312                                 if (sect_type == eSectionTypeOther)
1313                                 {
1314                                     switch (mach_sect_type)
1315                                     {
1316                                     // TODO: categorize sections by other flags for regular sections
1317                                     case S_REGULAR:
1318                                         if (segment_sp->GetName() == g_sect_name_TEXT)
1319                                             sect_type = eSectionTypeCode;
1320                                         else if (segment_sp->GetName() == g_sect_name_DATA)
1321                                             sect_type = eSectionTypeData;
1322                                         else
1323                                             sect_type = eSectionTypeOther;
1324                                         break;
1325                                     case S_ZEROFILL:                   sect_type = eSectionTypeZeroFill; break;
1326                                     case S_CSTRING_LITERALS:           sect_type = eSectionTypeDataCString;    break; // section with only literal C strings
1327                                     case S_4BYTE_LITERALS:             sect_type = eSectionTypeData4;    break; // section with only 4 byte literals
1328                                     case S_8BYTE_LITERALS:             sect_type = eSectionTypeData8;    break; // section with only 8 byte literals
1329                                     case S_LITERAL_POINTERS:           sect_type = eSectionTypeDataPointers;  break; // section with only pointers to literals
1330                                     case S_NON_LAZY_SYMBOL_POINTERS:   sect_type = eSectionTypeDataPointers;  break; // section with only non-lazy symbol pointers
1331                                     case S_LAZY_SYMBOL_POINTERS:       sect_type = eSectionTypeDataPointers;  break; // section with only lazy symbol pointers
1332                                     case S_SYMBOL_STUBS:               sect_type = eSectionTypeCode;  break; // section with only symbol stubs, byte size of stub in the reserved2 field
1333                                     case S_MOD_INIT_FUNC_POINTERS:     sect_type = eSectionTypeDataPointers;    break; // section with only function pointers for initialization
1334                                     case S_MOD_TERM_FUNC_POINTERS:     sect_type = eSectionTypeDataPointers; break; // section with only function pointers for termination
1335                                     case S_COALESCED:                  sect_type = eSectionTypeOther; break;
1336                                     case S_GB_ZEROFILL:                sect_type = eSectionTypeZeroFill; break;
1337                                     case S_INTERPOSING:                sect_type = eSectionTypeCode;  break; // section with only pairs of function pointers for interposing
1338                                     case S_16BYTE_LITERALS:            sect_type = eSectionTypeData16; break; // section with only 16 byte literals
1339                                     case S_DTRACE_DOF:                 sect_type = eSectionTypeDebug; break;
1340                                     case S_LAZY_DYLIB_SYMBOL_POINTERS: sect_type = eSectionTypeDataPointers;  break;
1341                                     default: break;
1342                                     }
1343                                 }
1344 
1345                                 SectionSP section_sp(new Section (segment_sp,
1346                                                                   module_sp,
1347                                                                   this,
1348                                                                   ++sectID,
1349                                                                   section_name,
1350                                                                   sect_type,
1351                                                                   sect64.addr - segment_sp->GetFileAddress(),
1352                                                                   sect64.size,
1353                                                                   sect64.offset,
1354                                                                   sect64.offset == 0 ? 0 : sect64.size,
1355                                                                   sect64.flags));
1356                                 // Set the section to be encrypted to match the segment
1357 
1358                                 bool section_is_encrypted = false;
1359                                 if (!segment_is_encrypted && load_cmd.filesize != 0)
1360                                     section_is_encrypted = encrypted_file_ranges.FindEntryThatContains(sect64.offset) != NULL;
1361 
1362                                 section_sp->SetIsEncrypted (segment_is_encrypted || section_is_encrypted);
1363                                 segment_sp->GetChildren().AddSection(section_sp);
1364 
1365                                 if (segment_sp->IsFake())
1366                                 {
1367                                     segment_sp.reset();
1368                                     const_segname.Clear();
1369                                 }
1370                             }
1371                         }
1372                         if (segment_sp && is_dsym)
1373                         {
1374                             if (first_segment_sectID <= sectID)
1375                             {
1376                                 lldb::user_id_t sect_uid;
1377                                 for (sect_uid = first_segment_sectID; sect_uid <= sectID; ++sect_uid)
1378                                 {
1379                                     SectionSP curr_section_sp(segment_sp->GetChildren().FindSectionByID (sect_uid));
1380                                     SectionSP next_section_sp;
1381                                     if (sect_uid + 1 <= sectID)
1382                                         next_section_sp = segment_sp->GetChildren().FindSectionByID (sect_uid+1);
1383 
1384                                     if (curr_section_sp.get())
1385                                     {
1386                                         if (curr_section_sp->GetByteSize() == 0)
1387                                         {
1388                                             if (next_section_sp.get() != NULL)
1389                                                 curr_section_sp->SetByteSize ( next_section_sp->GetFileAddress() - curr_section_sp->GetFileAddress() );
1390                                             else
1391                                                 curr_section_sp->SetByteSize ( load_cmd.vmsize );
1392                                         }
1393                                     }
1394                                 }
1395                             }
1396                         }
1397                     }
1398                 }
1399             }
1400             else if (load_cmd.cmd == LC_DYSYMTAB)
1401             {
1402                 m_dysymtab.cmd = load_cmd.cmd;
1403                 m_dysymtab.cmdsize = load_cmd.cmdsize;
1404                 m_data.GetU32 (&offset, &m_dysymtab.ilocalsym, (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1405             }
1406 
1407             offset = load_cmd_offset + load_cmd.cmdsize;
1408         }
1409 
1410 //        StreamFile s(stdout, false);                    // REMOVE THIS LINE
1411 //        s.Printf ("Sections for %s:\n", m_file.GetPath().c_str());// REMOVE THIS LINE
1412 //        m_sections_ap->Dump(&s, NULL, true, UINT32_MAX);// REMOVE THIS LINE
1413     }
1414 }
1415 
1416 class MachSymtabSectionInfo
1417 {
1418 public:
1419 
1420     MachSymtabSectionInfo (SectionList *section_list) :
1421         m_section_list (section_list),
1422         m_section_infos()
1423     {
1424         // Get the number of sections down to a depth of 1 to include
1425         // all segments and their sections, but no other sections that
1426         // may be added for debug map or
1427         m_section_infos.resize(section_list->GetNumSections(1));
1428     }
1429 
1430 
1431     SectionSP
1432     GetSection (uint8_t n_sect, addr_t file_addr)
1433     {
1434         if (n_sect == 0)
1435             return SectionSP();
1436         if (n_sect < m_section_infos.size())
1437         {
1438             if (!m_section_infos[n_sect].section_sp)
1439             {
1440                 SectionSP section_sp (m_section_list->FindSectionByID (n_sect));
1441                 m_section_infos[n_sect].section_sp = section_sp;
1442                 if (section_sp)
1443                 {
1444                     m_section_infos[n_sect].vm_range.SetBaseAddress (section_sp->GetFileAddress());
1445                     m_section_infos[n_sect].vm_range.SetByteSize (section_sp->GetByteSize());
1446                 }
1447                 else
1448                 {
1449                     Host::SystemLog (Host::eSystemLogError, "error: unable to find section for section %u\n", n_sect);
1450                 }
1451             }
1452             if (m_section_infos[n_sect].vm_range.Contains(file_addr))
1453             {
1454                 // Symbol is in section.
1455                 return m_section_infos[n_sect].section_sp;
1456             }
1457             else if (m_section_infos[n_sect].vm_range.GetByteSize () == 0 &&
1458                      m_section_infos[n_sect].vm_range.GetBaseAddress() == file_addr)
1459             {
1460                 // Symbol is in section with zero size, but has the same start
1461                 // address as the section. This can happen with linker symbols
1462                 // (symbols that start with the letter 'l' or 'L'.
1463                 return m_section_infos[n_sect].section_sp;
1464             }
1465         }
1466         return m_section_list->FindSectionContainingFileAddress(file_addr);
1467     }
1468 
1469 protected:
1470     struct SectionInfo
1471     {
1472         SectionInfo () :
1473             vm_range(),
1474             section_sp ()
1475         {
1476         }
1477 
1478         VMRange vm_range;
1479         SectionSP section_sp;
1480     };
1481     SectionList *m_section_list;
1482     std::vector<SectionInfo> m_section_infos;
1483 };
1484 
1485 struct TrieEntry
1486 {
1487     TrieEntry () :
1488         name(),
1489         address(LLDB_INVALID_ADDRESS),
1490         flags (0),
1491         other(0),
1492         import_name()
1493     {
1494     }
1495 
1496     void
1497     Clear ()
1498     {
1499         name.Clear();
1500         address = LLDB_INVALID_ADDRESS;
1501         flags = 0;
1502         other = 0;
1503         import_name.Clear();
1504     }
1505 
1506     void
1507     Dump () const
1508     {
1509         printf ("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"", address, flags, other, name.GetCString());
1510         if (import_name)
1511             printf (" -> \"%s\"\n", import_name.GetCString());
1512         else
1513             printf ("\n");
1514     }
1515     ConstString		name;
1516     uint64_t		address;
1517     uint64_t		flags;
1518     uint64_t		other;
1519     ConstString		import_name;
1520 };
1521 
1522 struct TrieEntryWithOffset
1523 {
1524 	lldb::offset_t nodeOffset;
1525 	TrieEntry entry;
1526 
1527     TrieEntryWithOffset (lldb::offset_t offset) :
1528         nodeOffset (offset),
1529         entry()
1530     {
1531     }
1532 
1533     void
1534     Dump (uint32_t idx) const
1535     {
1536         printf ("[%3u] 0x%16.16llx: ", idx, nodeOffset);
1537         entry.Dump();
1538     }
1539 
1540 	bool
1541     operator<(const TrieEntryWithOffset& other) const
1542     {
1543         return ( nodeOffset < other.nodeOffset );
1544     }
1545 };
1546 
1547 static void
1548 ParseTrieEntries (DataExtractor &data,
1549                   lldb::offset_t offset,
1550                   std::vector<llvm::StringRef> &nameSlices,
1551                   std::set<lldb::addr_t> &resolver_addresses,
1552                   std::vector<TrieEntryWithOffset>& output)
1553 {
1554 	if (!data.ValidOffset(offset))
1555         return;
1556 
1557 	const uint64_t terminalSize = data.GetULEB128(&offset);
1558 	lldb::offset_t children_offset = offset + terminalSize;
1559 	if ( terminalSize != 0 ) {
1560 		TrieEntryWithOffset e (offset);
1561 		e.entry.flags = data.GetULEB128(&offset);
1562         const char *import_name = NULL;
1563 		if ( e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT ) {
1564 			e.entry.address = 0;
1565 			e.entry.other = data.GetULEB128(&offset); // dylib ordinal
1566             import_name = data.GetCStr(&offset);
1567 		}
1568 		else {
1569 			e.entry.address = data.GetULEB128(&offset);
1570 			if ( e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER )
1571             {
1572                 resolver_addresses.insert(e.entry.address);
1573 				e.entry.other = data.GetULEB128(&offset);
1574             }
1575 			else
1576 				e.entry.other = 0;
1577 		}
1578         // Only add symbols that are reexport symbols with a valid import name
1579         if (EXPORT_SYMBOL_FLAGS_REEXPORT & e.entry.flags && import_name && import_name[0])
1580         {
1581             std::string name;
1582             if (!nameSlices.empty())
1583             {
1584                 for (auto name_slice: nameSlices)
1585                     name.append(name_slice.data(), name_slice.size());
1586             }
1587             if (name.size() > 1)
1588             {
1589                 // Skip the leading '_'
1590                 e.entry.name.SetCStringWithLength(name.c_str() + 1,name.size() - 1);
1591             }
1592             if (import_name)
1593             {
1594                 // Skip the leading '_'
1595                 e.entry.import_name.SetCString(import_name+1);
1596             }
1597             output.push_back(e);
1598         }
1599 	}
1600 
1601 	const uint8_t childrenCount = data.GetU8(&children_offset);
1602 	for (uint8_t i=0; i < childrenCount; ++i) {
1603         nameSlices.push_back(data.GetCStr(&children_offset));
1604         lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset);
1605 		if (childNodeOffset)
1606         {
1607             ParseTrieEntries(data,
1608                              childNodeOffset,
1609                              nameSlices,
1610                              resolver_addresses,
1611                              output);
1612         }
1613         nameSlices.pop_back();
1614 	}
1615 }
1616 
1617 size_t
1618 ObjectFileMachO::ParseSymtab ()
1619 {
1620     Timer scoped_timer(__PRETTY_FUNCTION__,
1621                        "ObjectFileMachO::ParseSymtab () module = %s",
1622                        m_file.GetFilename().AsCString(""));
1623     ModuleSP module_sp (GetModule());
1624     if (!module_sp)
1625         return 0;
1626 
1627     struct symtab_command symtab_load_command = { 0, 0, 0, 0, 0, 0 };
1628     struct linkedit_data_command function_starts_load_command = { 0, 0, 0, 0 };
1629     struct dyld_info_command dyld_info = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
1630     typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
1631     FunctionStarts function_starts;
1632     lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
1633     uint32_t i;
1634     FileSpecList dylib_files;
1635     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SYMBOLS));
1636 
1637     for (i=0; i<m_header.ncmds; ++i)
1638     {
1639         const lldb::offset_t cmd_offset = offset;
1640         // Read in the load command and load command size
1641         struct load_command lc;
1642         if (m_data.GetU32(&offset, &lc, 2) == NULL)
1643             break;
1644         // Watch for the symbol table load command
1645         switch (lc.cmd)
1646         {
1647         case LC_SYMTAB:
1648             symtab_load_command.cmd = lc.cmd;
1649             symtab_load_command.cmdsize = lc.cmdsize;
1650             // Read in the rest of the symtab load command
1651             if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) == 0) // fill in symoff, nsyms, stroff, strsize fields
1652                 return 0;
1653             if (symtab_load_command.symoff == 0)
1654             {
1655                 if (log)
1656                     module_sp->LogMessage(log, "LC_SYMTAB.symoff == 0");
1657                 return 0;
1658             }
1659 
1660             if (symtab_load_command.stroff == 0)
1661             {
1662                 if (log)
1663                     module_sp->LogMessage(log, "LC_SYMTAB.stroff == 0");
1664                 return 0;
1665             }
1666 
1667             if (symtab_load_command.nsyms == 0)
1668             {
1669                 if (log)
1670                     module_sp->LogMessage(log, "LC_SYMTAB.nsyms == 0");
1671                 return 0;
1672             }
1673 
1674             if (symtab_load_command.strsize == 0)
1675             {
1676                 if (log)
1677                     module_sp->LogMessage(log, "LC_SYMTAB.strsize == 0");
1678                 return 0;
1679             }
1680             break;
1681 
1682         case LC_DYLD_INFO:
1683         case LC_DYLD_INFO_ONLY:
1684             if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10))
1685             {
1686                 dyld_info.cmd = lc.cmd;
1687                 dyld_info.cmdsize = lc.cmdsize;
1688             }
1689             else
1690             {
1691                 memset (&dyld_info, 0, sizeof(dyld_info));
1692             }
1693             break;
1694 
1695         case LC_LOAD_DYLIB:
1696         case LC_LOAD_WEAK_DYLIB:
1697         case LC_REEXPORT_DYLIB:
1698         case LC_LOADFVMLIB:
1699         case LC_LOAD_UPWARD_DYLIB:
1700             {
1701                 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
1702                 const char *path = m_data.PeekCStr(name_offset);
1703                 if (path)
1704                 {
1705                     FileSpec file_spec(path, false);
1706                     // Strip the path if there is @rpath, @executanble, etc so we just use the basename
1707                     if (path[0] == '@')
1708                         file_spec.GetDirectory().Clear();
1709 
1710                     dylib_files.Append(file_spec);
1711                 }
1712             }
1713             break;
1714 
1715         case LC_FUNCTION_STARTS:
1716             function_starts_load_command.cmd = lc.cmd;
1717             function_starts_load_command.cmdsize = lc.cmdsize;
1718             if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) == NULL) // fill in symoff, nsyms, stroff, strsize fields
1719                 memset (&function_starts_load_command, 0, sizeof(function_starts_load_command));
1720             break;
1721 
1722         default:
1723             break;
1724         }
1725         offset = cmd_offset + lc.cmdsize;
1726     }
1727 
1728     if (symtab_load_command.cmd)
1729     {
1730         Symtab *symtab = m_symtab_ap.get();
1731         SectionList *section_list = GetSectionList();
1732         if (section_list == NULL)
1733             return 0;
1734 
1735         const uint32_t addr_byte_size = m_data.GetAddressByteSize();
1736         const ByteOrder byte_order = m_data.GetByteOrder();
1737         bool bit_width_32 = addr_byte_size == 4;
1738         const size_t nlist_byte_size = bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
1739 
1740         DataExtractor nlist_data (NULL, 0, byte_order, addr_byte_size);
1741         DataExtractor strtab_data (NULL, 0, byte_order, addr_byte_size);
1742         DataExtractor function_starts_data (NULL, 0, byte_order, addr_byte_size);
1743         DataExtractor indirect_symbol_index_data (NULL, 0, byte_order, addr_byte_size);
1744         DataExtractor dyld_trie_data (NULL, 0, byte_order, addr_byte_size);
1745 
1746         const addr_t nlist_data_byte_size = symtab_load_command.nsyms * nlist_byte_size;
1747         const addr_t strtab_data_byte_size = symtab_load_command.strsize;
1748         addr_t strtab_addr = LLDB_INVALID_ADDRESS;
1749 
1750         ProcessSP process_sp (m_process_wp.lock());
1751         Process *process = process_sp.get();
1752 
1753         uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
1754 
1755         if (process)
1756         {
1757             Target &target = process->GetTarget();
1758 
1759             memory_module_load_level = target.GetMemoryModuleLoadLevel();
1760 
1761             SectionSP linkedit_section_sp(section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
1762             // Reading mach file from memory in a process or core file...
1763 
1764             if (linkedit_section_sp)
1765             {
1766                 const addr_t linkedit_load_addr = linkedit_section_sp->GetLoadBaseAddress(&target);
1767                 const addr_t linkedit_file_offset = linkedit_section_sp->GetFileOffset();
1768                 const addr_t symoff_addr = linkedit_load_addr + symtab_load_command.symoff - linkedit_file_offset;
1769                 strtab_addr = linkedit_load_addr + symtab_load_command.stroff - linkedit_file_offset;
1770 
1771                 bool data_was_read = false;
1772 
1773 #if defined (__APPLE__) && defined (__arm__)
1774                 if (m_header.flags & 0x80000000u)
1775                 {
1776                     // This mach-o memory file is in the dyld shared cache. If this
1777                     // program is not remote and this is iOS, then this process will
1778                     // share the same shared cache as the process we are debugging and
1779                     // we can read the entire __LINKEDIT from the address space in this
1780                     // process. This is a needed optimization that is used for local iOS
1781                     // debugging only since all shared libraries in the shared cache do
1782                     // not have corresponding files that exist in the file system of the
1783                     // device. They have been combined into a single file. This means we
1784                     // always have to load these files from memory. All of the symbol and
1785                     // string tables from all of the __LINKEDIT sections from the shared
1786                     // libraries in the shared cache have been merged into a single large
1787                     // symbol and string table. Reading all of this symbol and string table
1788                     // data across can slow down debug launch times, so we optimize this by
1789                     // reading the memory for the __LINKEDIT section from this process.
1790 
1791                     UUID lldb_shared_cache(GetLLDBSharedCacheUUID());
1792                     UUID process_shared_cache(GetProcessSharedCacheUUID(process));
1793                     bool use_lldb_cache = true;
1794                     if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() && lldb_shared_cache != process_shared_cache)
1795                     {
1796                             use_lldb_cache = false;
1797                             ModuleSP module_sp (GetModule());
1798                             if (module_sp)
1799                                 module_sp->ReportWarning ("shared cache in process does not match lldb's own shared cache, startup will be slow.");
1800 
1801                     }
1802 
1803                     PlatformSP platform_sp (target.GetPlatform());
1804                     if (platform_sp && platform_sp->IsHost() && use_lldb_cache)
1805                     {
1806                         data_was_read = true;
1807                         nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size, eByteOrderLittle);
1808                         strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size, eByteOrderLittle);
1809                         if (function_starts_load_command.cmd)
1810                         {
1811                             const addr_t func_start_addr = linkedit_load_addr + function_starts_load_command.dataoff - linkedit_file_offset;
1812                             function_starts_data.SetData ((void *)func_start_addr, function_starts_load_command.datasize, eByteOrderLittle);
1813                         }
1814                     }
1815                 }
1816 #endif
1817 
1818                 if (!data_was_read)
1819                 {
1820                     if (memory_module_load_level == eMemoryModuleLoadLevelComplete)
1821                     {
1822                         DataBufferSP nlist_data_sp (ReadMemory (process_sp, symoff_addr, nlist_data_byte_size));
1823                         if (nlist_data_sp)
1824                             nlist_data.SetData (nlist_data_sp, 0, nlist_data_sp->GetByteSize());
1825                         // Load strings individually from memory when loading from memory since shared cache
1826                         // string tables contain strings for all symbols from all shared cached libraries
1827                         //DataBufferSP strtab_data_sp (ReadMemory (process_sp, strtab_addr, strtab_data_byte_size));
1828                         //if (strtab_data_sp)
1829                         //    strtab_data.SetData (strtab_data_sp, 0, strtab_data_sp->GetByteSize());
1830                         if (m_dysymtab.nindirectsyms != 0)
1831                         {
1832                             const addr_t indirect_syms_addr = linkedit_load_addr + m_dysymtab.indirectsymoff - linkedit_file_offset;
1833                             DataBufferSP indirect_syms_data_sp (ReadMemory (process_sp, indirect_syms_addr, m_dysymtab.nindirectsyms * 4));
1834                             if (indirect_syms_data_sp)
1835                                 indirect_symbol_index_data.SetData (indirect_syms_data_sp, 0, indirect_syms_data_sp->GetByteSize());
1836                         }
1837                     }
1838 
1839                     if (memory_module_load_level >= eMemoryModuleLoadLevelPartial)
1840                     {
1841                         if (function_starts_load_command.cmd)
1842                         {
1843                             const addr_t func_start_addr = linkedit_load_addr + function_starts_load_command.dataoff - linkedit_file_offset;
1844                             DataBufferSP func_start_data_sp (ReadMemory (process_sp, func_start_addr, function_starts_load_command.datasize));
1845                             if (func_start_data_sp)
1846                                 function_starts_data.SetData (func_start_data_sp, 0, func_start_data_sp->GetByteSize());
1847                         }
1848                     }
1849                 }
1850             }
1851         }
1852         else
1853         {
1854             nlist_data.SetData (m_data,
1855                                 symtab_load_command.symoff,
1856                                 nlist_data_byte_size);
1857             strtab_data.SetData (m_data,
1858                                  symtab_load_command.stroff,
1859                                  strtab_data_byte_size);
1860 
1861             if (dyld_info.export_size > 0)
1862             {
1863                 dyld_trie_data.SetData (m_data,
1864                                         dyld_info.export_off,
1865                                         dyld_info.export_size);
1866             }
1867 
1868             if (m_dysymtab.nindirectsyms != 0)
1869             {
1870                 indirect_symbol_index_data.SetData (m_data,
1871                                                     m_dysymtab.indirectsymoff,
1872                                                     m_dysymtab.nindirectsyms * 4);
1873             }
1874             if (function_starts_load_command.cmd)
1875             {
1876                 function_starts_data.SetData (m_data,
1877                                               function_starts_load_command.dataoff,
1878                                               function_starts_load_command.datasize);
1879             }
1880         }
1881 
1882         if (nlist_data.GetByteSize() == 0 && memory_module_load_level == eMemoryModuleLoadLevelComplete)
1883         {
1884             if (log)
1885                 module_sp->LogMessage(log, "failed to read nlist data");
1886             return 0;
1887         }
1888 
1889 
1890         const bool have_strtab_data = strtab_data.GetByteSize() > 0;
1891         if (!have_strtab_data)
1892         {
1893             if (process)
1894             {
1895                 if (strtab_addr == LLDB_INVALID_ADDRESS)
1896                 {
1897                     if (log)
1898                         module_sp->LogMessage(log, "failed to locate the strtab in memory");
1899                     return 0;
1900                 }
1901             }
1902             else
1903             {
1904                 if (log)
1905                     module_sp->LogMessage(log, "failed to read strtab data");
1906                 return 0;
1907             }
1908         }
1909 
1910         const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT();
1911         const ConstString &g_segment_name_DATA = GetSegmentNameDATA();
1912         const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC();
1913         const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame();
1914         SectionSP text_section_sp(section_list->FindSectionByName(g_segment_name_TEXT));
1915         SectionSP data_section_sp(section_list->FindSectionByName(g_segment_name_DATA));
1916         SectionSP objc_section_sp(section_list->FindSectionByName(g_segment_name_OBJC));
1917         SectionSP eh_frame_section_sp;
1918         if (text_section_sp.get())
1919             eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName (g_section_name_eh_frame);
1920         else
1921             eh_frame_section_sp = section_list->FindSectionByName (g_section_name_eh_frame);
1922 
1923         const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
1924 
1925         // lldb works best if it knows the start addresss of all functions in a module.
1926         // Linker symbols or debug info are normally the best source of information for start addr / size but
1927         // they may be stripped in a released binary.
1928         // Two additional sources of information exist in Mach-O binaries:
1929         //    LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each function's start address in the
1930         //                         binary, relative to the text section.
1931         //    eh_frame           - the eh_frame FDEs have the start addr & size of each function
1932         //  LC_FUNCTION_STARTS is the fastest source to read in, and is present on all modern binaries.
1933         //  Binaries built to run on older releases may need to use eh_frame information.
1934 
1935         if (text_section_sp && function_starts_data.GetByteSize())
1936         {
1937             FunctionStarts::Entry function_start_entry;
1938             function_start_entry.data = false;
1939             lldb::offset_t function_start_offset = 0;
1940             function_start_entry.addr = text_section_sp->GetFileAddress();
1941             uint64_t delta;
1942             while ((delta = function_starts_data.GetULEB128(&function_start_offset)) > 0)
1943             {
1944                 // Now append the current entry
1945                 function_start_entry.addr += delta;
1946                 function_starts.Append(function_start_entry);
1947             }
1948         }
1949         else
1950         {
1951             // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the load command claiming an eh_frame
1952             // but it doesn't actually have the eh_frame content.  And if we have a dSYM, we don't need to do any
1953             // of this fill-in-the-missing-symbols works anyway - the debug info should give us all the functions in
1954             // the module.
1955             if (text_section_sp.get() && eh_frame_section_sp.get() && m_type != eTypeDebugInfo)
1956             {
1957                 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp, eRegisterKindGCC, true);
1958                 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
1959                 eh_frame.GetFunctionAddressAndSizeVector (functions);
1960                 addr_t text_base_addr = text_section_sp->GetFileAddress();
1961                 size_t count = functions.GetSize();
1962                 for (size_t i = 0; i < count; ++i)
1963                 {
1964                     const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func = functions.GetEntryAtIndex (i);
1965                     if (func)
1966                     {
1967                         FunctionStarts::Entry function_start_entry;
1968                         function_start_entry.addr = func->base - text_base_addr;
1969                         function_starts.Append(function_start_entry);
1970                     }
1971                 }
1972             }
1973         }
1974 
1975         const size_t function_starts_count = function_starts.GetSize();
1976 
1977         const user_id_t TEXT_eh_frame_sectID = eh_frame_section_sp.get() ? eh_frame_section_sp->GetID() : NO_SECT;
1978 
1979         lldb::offset_t nlist_data_offset = 0;
1980 
1981         uint32_t N_SO_index = UINT32_MAX;
1982 
1983         MachSymtabSectionInfo section_info (section_list);
1984         std::vector<uint32_t> N_FUN_indexes;
1985         std::vector<uint32_t> N_NSYM_indexes;
1986         std::vector<uint32_t> N_INCL_indexes;
1987         std::vector<uint32_t> N_BRAC_indexes;
1988         std::vector<uint32_t> N_COMM_indexes;
1989         typedef std::map <uint64_t, uint32_t> ValueToSymbolIndexMap;
1990         typedef std::map <uint32_t, uint32_t> NListIndexToSymbolIndexMap;
1991         typedef std::map <const char *, uint32_t> ConstNameToSymbolIndexMap;
1992         ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
1993         ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
1994         ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
1995         // Any symbols that get merged into another will get an entry
1996         // in this map so we know
1997         NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
1998         uint32_t nlist_idx = 0;
1999         Symbol *symbol_ptr = NULL;
2000 
2001         uint32_t sym_idx = 0;
2002         Symbol *sym = NULL;
2003         size_t num_syms = 0;
2004         std::string memory_symbol_name;
2005         uint32_t unmapped_local_symbols_found = 0;
2006 
2007 #if defined (__APPLE__) && defined (__arm__)
2008 
2009         // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been optimized by moving LOCAL
2010         // symbols out of the memory mapped portion of the DSC. The symbol information has all been retained,
2011         // but it isn't available in the normal nlist data. However, there *are* duplicate entries of *some*
2012         // LOCAL symbols in the normal nlist data. To handle this situation correctly, we must first attempt
2013         // to parse any DSC unmapped symbol information. If we find any, we set a flag that tells the normal
2014         // nlist parser to ignore all LOCAL symbols.
2015 
2016         if (m_header.flags & 0x80000000u)
2017         {
2018             // Before we can start mapping the DSC, we need to make certain the target process is actually
2019             // using the cache we can find.
2020 
2021             // Next we need to determine the correct path for the dyld shared cache.
2022 
2023             ArchSpec header_arch(eArchTypeMachO, m_header.cputype, m_header.cpusubtype);
2024             char dsc_path[PATH_MAX];
2025 
2026             snprintf(dsc_path, sizeof(dsc_path), "%s%s%s",
2027                      "/System/Library/Caches/com.apple.dyld/",  /* IPHONE_DYLD_SHARED_CACHE_DIR */
2028                      "dyld_shared_cache_",          /* DYLD_SHARED_CACHE_BASE_NAME */
2029                      header_arch.GetArchitectureName());
2030 
2031             FileSpec dsc_filespec(dsc_path, false);
2032 
2033             // We need definitions of two structures in the on-disk DSC, copy them here manually
2034             struct lldb_copy_dyld_cache_header_v0
2035             {
2036                 char        magic[16];            // e.g. "dyld_v0    i386", "dyld_v1   armv7", etc.
2037                 uint32_t    mappingOffset;        // file offset to first dyld_cache_mapping_info
2038                 uint32_t    mappingCount;         // number of dyld_cache_mapping_info entries
2039                 uint32_t    imagesOffset;
2040                 uint32_t    imagesCount;
2041                 uint64_t    dyldBaseAddress;
2042                 uint64_t    codeSignatureOffset;
2043                 uint64_t    codeSignatureSize;
2044                 uint64_t    slideInfoOffset;
2045                 uint64_t    slideInfoSize;
2046                 uint64_t    localSymbolsOffset;   // file offset of where local symbols are stored
2047                 uint64_t    localSymbolsSize;     // size of local symbols information
2048             };
2049             struct lldb_copy_dyld_cache_header_v1
2050             {
2051                 char        magic[16];            // e.g. "dyld_v0    i386", "dyld_v1   armv7", etc.
2052                 uint32_t    mappingOffset;        // file offset to first dyld_cache_mapping_info
2053                 uint32_t    mappingCount;         // number of dyld_cache_mapping_info entries
2054                 uint32_t    imagesOffset;
2055                 uint32_t    imagesCount;
2056                 uint64_t    dyldBaseAddress;
2057                 uint64_t    codeSignatureOffset;
2058                 uint64_t    codeSignatureSize;
2059                 uint64_t    slideInfoOffset;
2060                 uint64_t    slideInfoSize;
2061                 uint64_t    localSymbolsOffset;
2062                 uint64_t    localSymbolsSize;
2063                 uint8_t     uuid[16];             // v1 and above, also recorded in dyld_all_image_infos v13 and later
2064             };
2065 
2066             struct lldb_copy_dyld_cache_mapping_info
2067             {
2068                 uint64_t        address;
2069                 uint64_t        size;
2070                 uint64_t        fileOffset;
2071                 uint32_t        maxProt;
2072                 uint32_t        initProt;
2073             };
2074 
2075             struct lldb_copy_dyld_cache_local_symbols_info
2076             {
2077                 uint32_t        nlistOffset;
2078                 uint32_t        nlistCount;
2079                 uint32_t        stringsOffset;
2080                 uint32_t        stringsSize;
2081                 uint32_t        entriesOffset;
2082                 uint32_t        entriesCount;
2083             };
2084             struct lldb_copy_dyld_cache_local_symbols_entry
2085             {
2086                 uint32_t        dylibOffset;
2087                 uint32_t        nlistStartIndex;
2088                 uint32_t        nlistCount;
2089             };
2090 
2091             /* The dyld_cache_header has a pointer to the dyld_cache_local_symbols_info structure (localSymbolsOffset).
2092                The dyld_cache_local_symbols_info structure gives us three things:
2093                  1. The start and count of the nlist records in the dyld_shared_cache file
2094                  2. The start and size of the strings for these nlist records
2095                  3. The start and count of dyld_cache_local_symbols_entry entries
2096 
2097                There is one dyld_cache_local_symbols_entry per dylib/framework in the dyld shared cache.
2098                The "dylibOffset" field is the Mach-O header of this dylib/framework in the dyld shared cache.
2099                The dyld_cache_local_symbols_entry also lists the start of this dylib/framework's nlist records
2100                and the count of how many nlist records there are for this dylib/framework.
2101             */
2102 
2103             // Process the dsc header to find the unmapped symbols
2104             //
2105             // Save some VM space, do not map the entire cache in one shot.
2106 
2107             DataBufferSP dsc_data_sp;
2108             dsc_data_sp = dsc_filespec.MemoryMapFileContents(0, sizeof(struct lldb_copy_dyld_cache_header_v1));
2109 
2110             if (dsc_data_sp)
2111             {
2112                 DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2113 
2114                 char version_str[17];
2115                 int version = -1;
2116                 lldb::offset_t offset = 0;
2117                 memcpy (version_str, dsc_header_data.GetData (&offset, 16), 16);
2118                 version_str[16] = '\0';
2119                 if (strncmp (version_str, "dyld_v", 6) == 0 && isdigit (version_str[6]))
2120                 {
2121                     int v;
2122                     if (::sscanf (version_str + 6, "%d", &v) == 1)
2123                     {
2124                         version = v;
2125                     }
2126                 }
2127 
2128                 UUID dsc_uuid;
2129                 if (version >= 1)
2130                 {
2131                     offset = offsetof (struct lldb_copy_dyld_cache_header_v1, uuid);
2132                     uint8_t uuid_bytes[sizeof (uuid_t)];
2133                     memcpy (uuid_bytes, dsc_header_data.GetData (&offset, sizeof (uuid_t)), sizeof (uuid_t));
2134                     dsc_uuid.SetBytes (uuid_bytes);
2135                 }
2136 
2137                 bool uuid_match = true;
2138                 if (dsc_uuid.IsValid() && process)
2139                 {
2140                     UUID shared_cache_uuid(GetProcessSharedCacheUUID(process));
2141 
2142                     if (shared_cache_uuid.IsValid() && dsc_uuid != shared_cache_uuid)
2143                     {
2144                         // The on-disk dyld_shared_cache file is not the same as the one in this
2145                         // process' memory, don't use it.
2146                         uuid_match = false;
2147                         ModuleSP module_sp (GetModule());
2148                         if (module_sp)
2149                             module_sp->ReportWarning ("process shared cache does not match on-disk dyld_shared_cache file, some symbol names will be missing.");
2150                     }
2151                 }
2152 
2153                 offset = offsetof (struct lldb_copy_dyld_cache_header_v1, mappingOffset);
2154 
2155                 uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
2156 
2157                 // If the mappingOffset points to a location inside the header, we've
2158                 // opened an old dyld shared cache, and should not proceed further.
2159                 if (uuid_match && mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v0))
2160                 {
2161 
2162                     DataBufferSP dsc_mapping_info_data_sp = dsc_filespec.MemoryMapFileContents(mappingOffset, sizeof (struct lldb_copy_dyld_cache_mapping_info));
2163                     DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp, byte_order, addr_byte_size);
2164                     offset = 0;
2165 
2166                     // The File addresses (from the in-memory Mach-O load commands) for the shared libraries
2167                     // in the shared library cache need to be adjusted by an offset to match up with the
2168                     // dylibOffset identifying field in the dyld_cache_local_symbol_entry's.  This offset is
2169                     // recorded in mapping_offset_value.
2170                     const uint64_t mapping_offset_value = dsc_mapping_info_data.GetU64(&offset);
2171 
2172                     offset = offsetof (struct lldb_copy_dyld_cache_header_v1, localSymbolsOffset);
2173                     uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2174                     uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
2175 
2176                     if (localSymbolsOffset && localSymbolsSize)
2177                     {
2178                         // Map the local symbols
2179                         if (DataBufferSP dsc_local_symbols_data_sp = dsc_filespec.MemoryMapFileContents(localSymbolsOffset, localSymbolsSize))
2180                         {
2181                             DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp, byte_order, addr_byte_size);
2182 
2183                             offset = 0;
2184 
2185                             // Read the local_symbols_infos struct in one shot
2186                             struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
2187                             dsc_local_symbols_data.GetU32(&offset, &local_symbols_info.nlistOffset, 6);
2188 
2189                             SectionSP text_section_sp(section_list->FindSectionByName(GetSegmentNameTEXT()));
2190 
2191                             uint32_t header_file_offset = (text_section_sp->GetFileAddress() - mapping_offset_value);
2192 
2193                             offset = local_symbols_info.entriesOffset;
2194                             for (uint32_t entry_index = 0; entry_index < local_symbols_info.entriesCount; entry_index++)
2195                             {
2196                                 struct lldb_copy_dyld_cache_local_symbols_entry local_symbols_entry;
2197                                 local_symbols_entry.dylibOffset = dsc_local_symbols_data.GetU32(&offset);
2198                                 local_symbols_entry.nlistStartIndex = dsc_local_symbols_data.GetU32(&offset);
2199                                 local_symbols_entry.nlistCount = dsc_local_symbols_data.GetU32(&offset);
2200 
2201                                 if (header_file_offset == local_symbols_entry.dylibOffset)
2202                                 {
2203                                     unmapped_local_symbols_found = local_symbols_entry.nlistCount;
2204 
2205                                     // The normal nlist code cannot correctly size the Symbols array, we need to allocate it here.
2206                                     sym = symtab->Resize (symtab_load_command.nsyms + m_dysymtab.nindirectsyms + unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2207                                     num_syms = symtab->GetNumSymbols();
2208 
2209                                     nlist_data_offset = local_symbols_info.nlistOffset + (nlist_byte_size * local_symbols_entry.nlistStartIndex);
2210                                     uint32_t string_table_offset = local_symbols_info.stringsOffset;
2211 
2212                                     for (uint32_t nlist_index = 0; nlist_index < local_symbols_entry.nlistCount; nlist_index++)
2213                                     {
2214                                         /////////////////////////////
2215                                         {
2216                                             struct nlist_64 nlist;
2217                                             if (!dsc_local_symbols_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size))
2218                                                 break;
2219 
2220                                             nlist.n_strx  = dsc_local_symbols_data.GetU32_unchecked(&nlist_data_offset);
2221                                             nlist.n_type  = dsc_local_symbols_data.GetU8_unchecked (&nlist_data_offset);
2222                                             nlist.n_sect  = dsc_local_symbols_data.GetU8_unchecked (&nlist_data_offset);
2223                                             nlist.n_desc  = dsc_local_symbols_data.GetU16_unchecked (&nlist_data_offset);
2224                                             nlist.n_value = dsc_local_symbols_data.GetAddress_unchecked (&nlist_data_offset);
2225 
2226                                             SymbolType type = eSymbolTypeInvalid;
2227                                             const char *symbol_name = dsc_local_symbols_data.PeekCStr(string_table_offset + nlist.n_strx);
2228 
2229                                             if (symbol_name == NULL)
2230                                             {
2231                                                 // No symbol should be NULL, even the symbols with no
2232                                                 // string values should have an offset zero which points
2233                                                 // to an empty C-string
2234                                                 Host::SystemLog (Host::eSystemLogError,
2235                                                                  "error: DSC unmapped local symbol[%u] has invalid string table offset 0x%x in %s, ignoring symbol\n",
2236                                                                  entry_index,
2237                                                                  nlist.n_strx,
2238                                                                  module_sp->GetFileSpec().GetPath().c_str());
2239                                                 continue;
2240                                             }
2241                                             if (symbol_name[0] == '\0')
2242                                                 symbol_name = NULL;
2243 
2244                                             const char *symbol_name_non_abi_mangled = NULL;
2245 
2246                                             SectionSP symbol_section;
2247                                             uint32_t symbol_byte_size = 0;
2248                                             bool add_nlist = true;
2249                                             bool is_debug = ((nlist.n_type & N_STAB) != 0);
2250                                             bool demangled_is_synthesized = false;
2251                                             bool is_gsym = false;
2252 
2253                                             assert (sym_idx < num_syms);
2254 
2255                                             sym[sym_idx].SetDebug (is_debug);
2256 
2257                                             if (is_debug)
2258                                             {
2259                                                 switch (nlist.n_type)
2260                                                 {
2261                                                     case N_GSYM:
2262                                                         // global symbol: name,,NO_SECT,type,0
2263                                                         // Sometimes the N_GSYM value contains the address.
2264 
2265                                                         // FIXME: In the .o files, we have a GSYM and a debug symbol for all the ObjC data.  They
2266                                                         // have the same address, but we want to ensure that we always find only the real symbol,
2267                                                         // 'cause we don't currently correctly attribute the GSYM one to the ObjCClass/Ivar/MetaClass
2268                                                         // symbol type.  This is a temporary hack to make sure the ObjectiveC symbols get treated
2269                                                         // correctly.  To do this right, we should coalesce all the GSYM & global symbols that have the
2270                                                         // same address.
2271 
2272                                                         if (symbol_name && symbol_name[0] == '_' && symbol_name[1] ==  'O'
2273                                                             && (strncmp (symbol_name, "_OBJC_IVAR_$_", strlen ("_OBJC_IVAR_$_")) == 0
2274                                                                 || strncmp (symbol_name, "_OBJC_CLASS_$_", strlen ("_OBJC_CLASS_$_")) == 0
2275                                                                 || strncmp (symbol_name, "_OBJC_METACLASS_$_", strlen ("_OBJC_METACLASS_$_")) == 0))
2276                                                             add_nlist = false;
2277                                                         else
2278                                                         {
2279                                                             is_gsym = true;
2280                                                             sym[sym_idx].SetExternal(true);
2281                                                             if (nlist.n_value != 0)
2282                                                                 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2283                                                             type = eSymbolTypeData;
2284                                                         }
2285                                                         break;
2286 
2287                                                     case N_FNAME:
2288                                                         // procedure name (f77 kludge): name,,NO_SECT,0,0
2289                                                         type = eSymbolTypeCompiler;
2290                                                         break;
2291 
2292                                                     case N_FUN:
2293                                                         // procedure: name,,n_sect,linenumber,address
2294                                                         if (symbol_name)
2295                                                         {
2296                                                             type = eSymbolTypeCode;
2297                                                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2298 
2299                                                             N_FUN_addr_to_sym_idx[nlist.n_value] = sym_idx;
2300                                                             // We use the current number of symbols in the symbol table in lieu of
2301                                                             // using nlist_idx in case we ever start trimming entries out
2302                                                             N_FUN_indexes.push_back(sym_idx);
2303                                                         }
2304                                                         else
2305                                                         {
2306                                                             type = eSymbolTypeCompiler;
2307 
2308                                                             if ( !N_FUN_indexes.empty() )
2309                                                             {
2310                                                                 // Copy the size of the function into the original STAB entry so we don't have
2311                                                                 // to hunt for it later
2312                                                                 symtab->SymbolAtIndex(N_FUN_indexes.back())->SetByteSize(nlist.n_value);
2313                                                                 N_FUN_indexes.pop_back();
2314                                                                 // We don't really need the end function STAB as it contains the size which
2315                                                                 // we already placed with the original symbol, so don't add it if we want a
2316                                                                 // minimal symbol table
2317                                                                 add_nlist = false;
2318                                                             }
2319                                                         }
2320                                                         break;
2321 
2322                                                     case N_STSYM:
2323                                                         // static symbol: name,,n_sect,type,address
2324                                                         N_STSYM_addr_to_sym_idx[nlist.n_value] = sym_idx;
2325                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2326                                                         type = eSymbolTypeData;
2327                                                         break;
2328 
2329                                                     case N_LCSYM:
2330                                                         // .lcomm symbol: name,,n_sect,type,address
2331                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2332                                                         type = eSymbolTypeCommonBlock;
2333                                                         break;
2334 
2335                                                     case N_BNSYM:
2336                                                         // We use the current number of symbols in the symbol table in lieu of
2337                                                         // using nlist_idx in case we ever start trimming entries out
2338                                                         // Skip these if we want minimal symbol tables
2339                                                         add_nlist = false;
2340                                                         break;
2341 
2342                                                     case N_ENSYM:
2343                                                         // Set the size of the N_BNSYM to the terminating index of this N_ENSYM
2344                                                         // so that we can always skip the entire symbol if we need to navigate
2345                                                         // more quickly at the source level when parsing STABS
2346                                                         // Skip these if we want minimal symbol tables
2347                                                         add_nlist = false;
2348                                                         break;
2349 
2350 
2351                                                     case N_OPT:
2352                                                         // emitted with gcc2_compiled and in gcc source
2353                                                         type = eSymbolTypeCompiler;
2354                                                         break;
2355 
2356                                                     case N_RSYM:
2357                                                         // register sym: name,,NO_SECT,type,register
2358                                                         type = eSymbolTypeVariable;
2359                                                         break;
2360 
2361                                                     case N_SLINE:
2362                                                         // src line: 0,,n_sect,linenumber,address
2363                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2364                                                         type = eSymbolTypeLineEntry;
2365                                                         break;
2366 
2367                                                     case N_SSYM:
2368                                                         // structure elt: name,,NO_SECT,type,struct_offset
2369                                                         type = eSymbolTypeVariableType;
2370                                                         break;
2371 
2372                                                     case N_SO:
2373                                                         // source file name
2374                                                         type = eSymbolTypeSourceFile;
2375                                                         if (symbol_name == NULL)
2376                                                         {
2377                                                             add_nlist = false;
2378                                                             if (N_SO_index != UINT32_MAX)
2379                                                             {
2380                                                                 // Set the size of the N_SO to the terminating index of this N_SO
2381                                                                 // so that we can always skip the entire N_SO if we need to navigate
2382                                                                 // more quickly at the source level when parsing STABS
2383                                                                 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
2384                                                                 symbol_ptr->SetByteSize(sym_idx);
2385                                                                 symbol_ptr->SetSizeIsSibling(true);
2386                                                             }
2387                                                             N_NSYM_indexes.clear();
2388                                                             N_INCL_indexes.clear();
2389                                                             N_BRAC_indexes.clear();
2390                                                             N_COMM_indexes.clear();
2391                                                             N_FUN_indexes.clear();
2392                                                             N_SO_index = UINT32_MAX;
2393                                                         }
2394                                                         else
2395                                                         {
2396                                                             // We use the current number of symbols in the symbol table in lieu of
2397                                                             // using nlist_idx in case we ever start trimming entries out
2398                                                             const bool N_SO_has_full_path = symbol_name[0] == '/';
2399                                                             if (N_SO_has_full_path)
2400                                                             {
2401                                                                 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
2402                                                                 {
2403                                                                     // We have two consecutive N_SO entries where the first contains a directory
2404                                                                     // and the second contains a full path.
2405                                                                     sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name), false);
2406                                                                     m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
2407                                                                     add_nlist = false;
2408                                                                 }
2409                                                                 else
2410                                                                 {
2411                                                                     // This is the first entry in a N_SO that contains a directory or
2412                                                                     // a full path to the source file
2413                                                                     N_SO_index = sym_idx;
2414                                                                 }
2415                                                             }
2416                                                             else if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
2417                                                             {
2418                                                                 // This is usually the second N_SO entry that contains just the filename,
2419                                                                 // so here we combine it with the first one if we are minimizing the symbol table
2420                                                                 const char *so_path = sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString();
2421                                                                 if (so_path && so_path[0])
2422                                                                 {
2423                                                                     std::string full_so_path (so_path);
2424                                                                     const size_t double_slash_pos = full_so_path.find("//");
2425                                                                     if (double_slash_pos != std::string::npos)
2426                                                                     {
2427                                                                         // The linker has been generating bad N_SO entries with doubled up paths
2428                                                                         // in the format "%s%s" where the first string in the DW_AT_comp_dir,
2429                                                                         // and the second is the directory for the source file so you end up with
2430                                                                         // a path that looks like "/tmp/src//tmp/src/"
2431                                                                         FileSpec so_dir(so_path, false);
2432                                                                         if (!so_dir.Exists())
2433                                                                         {
2434                                                                             so_dir.SetFile(&full_so_path[double_slash_pos + 1], false);
2435                                                                             if (so_dir.Exists())
2436                                                                             {
2437                                                                                 // Trim off the incorrect path
2438                                                                                 full_so_path.erase(0, double_slash_pos + 1);
2439                                                                             }
2440                                                                         }
2441                                                                     }
2442                                                                     if (*full_so_path.rbegin() != '/')
2443                                                                         full_so_path += '/';
2444                                                                     full_so_path += symbol_name;
2445                                                                     sym[sym_idx - 1].GetMangled().SetValue(ConstString(full_so_path.c_str()), false);
2446                                                                     add_nlist = false;
2447                                                                     m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
2448                                                                 }
2449                                                             }
2450                                                             else
2451                                                             {
2452                                                                 // This could be a relative path to a N_SO
2453                                                                 N_SO_index = sym_idx;
2454                                                             }
2455                                                         }
2456                                                         break;
2457 
2458                                                     case N_OSO:
2459                                                         // object file name: name,,0,0,st_mtime
2460                                                         type = eSymbolTypeObjectFile;
2461                                                         break;
2462 
2463                                                     case N_LSYM:
2464                                                         // local sym: name,,NO_SECT,type,offset
2465                                                         type = eSymbolTypeLocal;
2466                                                         break;
2467 
2468                                                         //----------------------------------------------------------------------
2469                                                         // INCL scopes
2470                                                         //----------------------------------------------------------------------
2471                                                     case N_BINCL:
2472                                                         // include file beginning: name,,NO_SECT,0,sum
2473                                                         // We use the current number of symbols in the symbol table in lieu of
2474                                                         // using nlist_idx in case we ever start trimming entries out
2475                                                         N_INCL_indexes.push_back(sym_idx);
2476                                                         type = eSymbolTypeScopeBegin;
2477                                                         break;
2478 
2479                                                     case N_EINCL:
2480                                                         // include file end: name,,NO_SECT,0,0
2481                                                         // Set the size of the N_BINCL to the terminating index of this N_EINCL
2482                                                         // so that we can always skip the entire symbol if we need to navigate
2483                                                         // more quickly at the source level when parsing STABS
2484                                                         if ( !N_INCL_indexes.empty() )
2485                                                         {
2486                                                             symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
2487                                                             symbol_ptr->SetByteSize(sym_idx + 1);
2488                                                             symbol_ptr->SetSizeIsSibling(true);
2489                                                             N_INCL_indexes.pop_back();
2490                                                         }
2491                                                         type = eSymbolTypeScopeEnd;
2492                                                         break;
2493 
2494                                                     case N_SOL:
2495                                                         // #included file name: name,,n_sect,0,address
2496                                                         type = eSymbolTypeHeaderFile;
2497 
2498                                                         // We currently don't use the header files on darwin
2499                                                         add_nlist = false;
2500                                                         break;
2501 
2502                                                     case N_PARAMS:
2503                                                         // compiler parameters: name,,NO_SECT,0,0
2504                                                         type = eSymbolTypeCompiler;
2505                                                         break;
2506 
2507                                                     case N_VERSION:
2508                                                         // compiler version: name,,NO_SECT,0,0
2509                                                         type = eSymbolTypeCompiler;
2510                                                         break;
2511 
2512                                                     case N_OLEVEL:
2513                                                         // compiler -O level: name,,NO_SECT,0,0
2514                                                         type = eSymbolTypeCompiler;
2515                                                         break;
2516 
2517                                                     case N_PSYM:
2518                                                         // parameter: name,,NO_SECT,type,offset
2519                                                         type = eSymbolTypeVariable;
2520                                                         break;
2521 
2522                                                     case N_ENTRY:
2523                                                         // alternate entry: name,,n_sect,linenumber,address
2524                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2525                                                         type = eSymbolTypeLineEntry;
2526                                                         break;
2527 
2528                                                         //----------------------------------------------------------------------
2529                                                         // Left and Right Braces
2530                                                         //----------------------------------------------------------------------
2531                                                     case N_LBRAC:
2532                                                         // left bracket: 0,,NO_SECT,nesting level,address
2533                                                         // We use the current number of symbols in the symbol table in lieu of
2534                                                         // using nlist_idx in case we ever start trimming entries out
2535                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2536                                                         N_BRAC_indexes.push_back(sym_idx);
2537                                                         type = eSymbolTypeScopeBegin;
2538                                                         break;
2539 
2540                                                     case N_RBRAC:
2541                                                         // right bracket: 0,,NO_SECT,nesting level,address
2542                                                         // Set the size of the N_LBRAC to the terminating index of this N_RBRAC
2543                                                         // so that we can always skip the entire symbol if we need to navigate
2544                                                         // more quickly at the source level when parsing STABS
2545                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2546                                                         if ( !N_BRAC_indexes.empty() )
2547                                                         {
2548                                                             symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
2549                                                             symbol_ptr->SetByteSize(sym_idx + 1);
2550                                                             symbol_ptr->SetSizeIsSibling(true);
2551                                                             N_BRAC_indexes.pop_back();
2552                                                         }
2553                                                         type = eSymbolTypeScopeEnd;
2554                                                         break;
2555 
2556                                                     case N_EXCL:
2557                                                         // deleted include file: name,,NO_SECT,0,sum
2558                                                         type = eSymbolTypeHeaderFile;
2559                                                         break;
2560 
2561                                                         //----------------------------------------------------------------------
2562                                                         // COMM scopes
2563                                                         //----------------------------------------------------------------------
2564                                                     case N_BCOMM:
2565                                                         // begin common: name,,NO_SECT,0,0
2566                                                         // We use the current number of symbols in the symbol table in lieu of
2567                                                         // using nlist_idx in case we ever start trimming entries out
2568                                                         type = eSymbolTypeScopeBegin;
2569                                                         N_COMM_indexes.push_back(sym_idx);
2570                                                         break;
2571 
2572                                                     case N_ECOML:
2573                                                         // end common (local name): 0,,n_sect,0,address
2574                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2575                                                         // Fall through
2576 
2577                                                     case N_ECOMM:
2578                                                         // end common: name,,n_sect,0,0
2579                                                         // Set the size of the N_BCOMM to the terminating index of this N_ECOMM/N_ECOML
2580                                                         // so that we can always skip the entire symbol if we need to navigate
2581                                                         // more quickly at the source level when parsing STABS
2582                                                         if ( !N_COMM_indexes.empty() )
2583                                                         {
2584                                                             symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
2585                                                             symbol_ptr->SetByteSize(sym_idx + 1);
2586                                                             symbol_ptr->SetSizeIsSibling(true);
2587                                                             N_COMM_indexes.pop_back();
2588                                                         }
2589                                                         type = eSymbolTypeScopeEnd;
2590                                                         break;
2591 
2592                                                     case N_LENG:
2593                                                         // second stab entry with length information
2594                                                         type = eSymbolTypeAdditional;
2595                                                         break;
2596 
2597                                                     default: break;
2598                                                 }
2599                                             }
2600                                             else
2601                                             {
2602                                                 //uint8_t n_pext    = N_PEXT & nlist.n_type;
2603                                                 uint8_t n_type  = N_TYPE & nlist.n_type;
2604                                                 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
2605 
2606                                                 switch (n_type)
2607                                                 {
2608                                                     case N_INDR: // Fall through
2609                                                     case N_PBUD: // Fall through
2610                                                     case N_UNDF:
2611                                                         type = eSymbolTypeUndefined;
2612                                                         break;
2613 
2614                                                     case N_ABS:
2615                                                         type = eSymbolTypeAbsolute;
2616                                                         break;
2617 
2618                                                     case N_SECT:
2619                                                         {
2620                                                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2621 
2622                                                             if (symbol_section == NULL)
2623                                                             {
2624                                                                 // TODO: warn about this?
2625                                                                 add_nlist = false;
2626                                                                 break;
2627                                                             }
2628 
2629                                                             if (TEXT_eh_frame_sectID == nlist.n_sect)
2630                                                             {
2631                                                                 type = eSymbolTypeException;
2632                                                             }
2633                                                             else
2634                                                             {
2635                                                                 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
2636 
2637                                                                 switch (section_type)
2638                                                                 {
2639                                                                     case S_REGULAR:                    break; // regular section
2640                                                                                                                                                   //case S_ZEROFILL:                   type = eSymbolTypeData;    break; // zero fill on demand section
2641                                                                     case S_CSTRING_LITERALS:           type = eSymbolTypeData;    break; // section with only literal C strings
2642                                                                     case S_4BYTE_LITERALS:             type = eSymbolTypeData;    break; // section with only 4 byte literals
2643                                                                     case S_8BYTE_LITERALS:             type = eSymbolTypeData;    break; // section with only 8 byte literals
2644                                                                     case S_LITERAL_POINTERS:           type = eSymbolTypeTrampoline; break; // section with only pointers to literals
2645                                                                     case S_NON_LAZY_SYMBOL_POINTERS:   type = eSymbolTypeTrampoline; break; // section with only non-lazy symbol pointers
2646                                                                     case S_LAZY_SYMBOL_POINTERS:       type = eSymbolTypeTrampoline; break; // section with only lazy symbol pointers
2647                                                                     case S_SYMBOL_STUBS:               type = eSymbolTypeTrampoline; break; // section with only symbol stubs, byte size of stub in the reserved2 field
2648                                                                     case S_MOD_INIT_FUNC_POINTERS:     type = eSymbolTypeCode;    break; // section with only function pointers for initialization
2649                                                                     case S_MOD_TERM_FUNC_POINTERS:     type = eSymbolTypeCode;    break; // section with only function pointers for termination
2650                                                                                                                                                   //case S_COALESCED:                  type = eSymbolType;    break; // section contains symbols that are to be coalesced
2651                                                                                                                                                   //case S_GB_ZEROFILL:                type = eSymbolTypeData;    break; // zero fill on demand section (that can be larger than 4 gigabytes)
2652                                                                     case S_INTERPOSING:                type = eSymbolTypeTrampoline;  break; // section with only pairs of function pointers for interposing
2653                                                                     case S_16BYTE_LITERALS:            type = eSymbolTypeData;    break; // section with only 16 byte literals
2654                                                                     case S_DTRACE_DOF:                 type = eSymbolTypeInstrumentation; break;
2655                                                                     case S_LAZY_DYLIB_SYMBOL_POINTERS: type = eSymbolTypeTrampoline; break;
2656                                                                     default: break;
2657                                                                 }
2658 
2659                                                                 if (type == eSymbolTypeInvalid)
2660                                                                 {
2661                                                                     const char *symbol_sect_name = symbol_section->GetName().AsCString();
2662                                                                     if (symbol_section->IsDescendant (text_section_sp.get()))
2663                                                                     {
2664                                                                         if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
2665                                                                                                     S_ATTR_SELF_MODIFYING_CODE |
2666                                                                                                     S_ATTR_SOME_INSTRUCTIONS))
2667                                                                             type = eSymbolTypeData;
2668                                                                         else
2669                                                                             type = eSymbolTypeCode;
2670                                                                     }
2671                                                                     else if (symbol_section->IsDescendant(data_section_sp.get()))
2672                                                                     {
2673                                                                         if (symbol_sect_name && ::strstr (symbol_sect_name, "__objc") == symbol_sect_name)
2674                                                                         {
2675                                                                             type = eSymbolTypeRuntime;
2676 
2677                                                                             if (symbol_name &&
2678                                                                                 symbol_name[0] == '_' &&
2679                                                                                 symbol_name[1] == 'O' &&
2680                                                                                 symbol_name[2] == 'B')
2681                                                                             {
2682                                                                                 llvm::StringRef symbol_name_ref(symbol_name);
2683                                                                                 static const llvm::StringRef g_objc_v2_prefix_class ("_OBJC_CLASS_$_");
2684                                                                                 static const llvm::StringRef g_objc_v2_prefix_metaclass ("_OBJC_METACLASS_$_");
2685                                                                                 static const llvm::StringRef g_objc_v2_prefix_ivar ("_OBJC_IVAR_$_");
2686                                                                                 if (symbol_name_ref.startswith(g_objc_v2_prefix_class))
2687                                                                                 {
2688                                                                                     symbol_name_non_abi_mangled = symbol_name + 1;
2689                                                                                     symbol_name = symbol_name + g_objc_v2_prefix_class.size();
2690                                                                                     type = eSymbolTypeObjCClass;
2691                                                                                     demangled_is_synthesized = true;
2692                                                                                 }
2693                                                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass))
2694                                                                                 {
2695                                                                                     symbol_name_non_abi_mangled = symbol_name + 1;
2696                                                                                     symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
2697                                                                                     type = eSymbolTypeObjCMetaClass;
2698                                                                                     demangled_is_synthesized = true;
2699                                                                                 }
2700                                                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar))
2701                                                                                 {
2702                                                                                     symbol_name_non_abi_mangled = symbol_name + 1;
2703                                                                                     symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
2704                                                                                     type = eSymbolTypeObjCIVar;
2705                                                                                     demangled_is_synthesized = true;
2706                                                                                 }
2707                                                                             }
2708                                                                         }
2709                                                                         else if (symbol_sect_name && ::strstr (symbol_sect_name, "__gcc_except_tab") == symbol_sect_name)
2710                                                                         {
2711                                                                             type = eSymbolTypeException;
2712                                                                         }
2713                                                                         else
2714                                                                         {
2715                                                                             type = eSymbolTypeData;
2716                                                                         }
2717                                                                     }
2718                                                                     else if (symbol_sect_name && ::strstr (symbol_sect_name, "__IMPORT") == symbol_sect_name)
2719                                                                     {
2720                                                                         type = eSymbolTypeTrampoline;
2721                                                                     }
2722                                                                     else if (symbol_section->IsDescendant(objc_section_sp.get()))
2723                                                                     {
2724                                                                         type = eSymbolTypeRuntime;
2725                                                                         if (symbol_name && symbol_name[0] == '.')
2726                                                                         {
2727                                                                             llvm::StringRef symbol_name_ref(symbol_name);
2728                                                                             static const llvm::StringRef g_objc_v1_prefix_class (".objc_class_name_");
2729                                                                             if (symbol_name_ref.startswith(g_objc_v1_prefix_class))
2730                                                                             {
2731                                                                                 symbol_name_non_abi_mangled = symbol_name;
2732                                                                                 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
2733                                                                                 type = eSymbolTypeObjCClass;
2734                                                                                 demangled_is_synthesized = true;
2735                                                                             }
2736                                                                         }
2737                                                                     }
2738                                                                 }
2739                                                             }
2740                                                         }
2741                                                         break;
2742                                                 }
2743                                             }
2744 
2745                                             if (add_nlist)
2746                                             {
2747                                                 uint64_t symbol_value = nlist.n_value;
2748                                                 if (symbol_name_non_abi_mangled)
2749                                                 {
2750                                                     sym[sym_idx].GetMangled().SetMangledName (ConstString(symbol_name_non_abi_mangled));
2751                                                     sym[sym_idx].GetMangled().SetDemangledName (ConstString(symbol_name));
2752                                                 }
2753                                                 else
2754                                                 {
2755                                                     bool symbol_name_is_mangled = false;
2756 
2757                                                     if (symbol_name && symbol_name[0] == '_')
2758                                                     {
2759                                                         symbol_name_is_mangled = symbol_name[1] == '_';
2760                                                         symbol_name++;  // Skip the leading underscore
2761                                                     }
2762 
2763                                                     if (symbol_name)
2764                                                     {
2765                                                         ConstString const_symbol_name(symbol_name);
2766                                                         sym[sym_idx].GetMangled().SetValue(const_symbol_name, symbol_name_is_mangled);
2767                                                         if (is_gsym && is_debug)
2768                                                             N_GSYM_name_to_sym_idx[sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString()] = sym_idx;
2769                                                     }
2770                                                 }
2771                                                 if (symbol_section)
2772                                                 {
2773                                                     const addr_t section_file_addr = symbol_section->GetFileAddress();
2774                                                     if (symbol_byte_size == 0 && function_starts_count > 0)
2775                                                     {
2776                                                         addr_t symbol_lookup_file_addr = nlist.n_value;
2777                                                         // Do an exact address match for non-ARM addresses, else get the closest since
2778                                                         // the symbol might be a thumb symbol which has an address with bit zero set
2779                                                         FunctionStarts::Entry *func_start_entry = function_starts.FindEntry (symbol_lookup_file_addr, !is_arm);
2780                                                         if (is_arm && func_start_entry)
2781                                                         {
2782                                                             // Verify that the function start address is the symbol address (ARM)
2783                                                             // or the symbol address + 1 (thumb)
2784                                                             if (func_start_entry->addr != symbol_lookup_file_addr &&
2785                                                                 func_start_entry->addr != (symbol_lookup_file_addr + 1))
2786                                                             {
2787                                                                 // Not the right entry, NULL it out...
2788                                                                 func_start_entry = NULL;
2789                                                             }
2790                                                         }
2791                                                         if (func_start_entry)
2792                                                         {
2793                                                             func_start_entry->data = true;
2794 
2795                                                             addr_t symbol_file_addr = func_start_entry->addr;
2796                                                             uint32_t symbol_flags = 0;
2797                                                             if (is_arm)
2798                                                             {
2799                                                                 if (symbol_file_addr & 1)
2800                                                                     symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
2801                                                                 symbol_file_addr &= 0xfffffffffffffffeull;
2802                                                             }
2803 
2804                                                             const FunctionStarts::Entry *next_func_start_entry = function_starts.FindNextEntry (func_start_entry);
2805                                                             const addr_t section_end_file_addr = section_file_addr + symbol_section->GetByteSize();
2806                                                             if (next_func_start_entry)
2807                                                             {
2808                                                                 addr_t next_symbol_file_addr = next_func_start_entry->addr;
2809                                                                 // Be sure the clear the Thumb address bit when we calculate the size
2810                                                                 // from the current and next address
2811                                                                 if (is_arm)
2812                                                                     next_symbol_file_addr &= 0xfffffffffffffffeull;
2813                                                                 symbol_byte_size = std::min<lldb::addr_t>(next_symbol_file_addr - symbol_file_addr, section_end_file_addr - symbol_file_addr);
2814                                                             }
2815                                                             else
2816                                                             {
2817                                                                 symbol_byte_size = section_end_file_addr - symbol_file_addr;
2818                                                             }
2819                                                         }
2820                                                     }
2821                                                     symbol_value -= section_file_addr;
2822                                                 }
2823 
2824                                                 if (is_debug == false)
2825                                                 {
2826                                                     if (type == eSymbolTypeCode)
2827                                                     {
2828                                                         // See if we can find a N_FUN entry for any code symbols.
2829                                                         // If we do find a match, and the name matches, then we
2830                                                         // can merge the two into just the function symbol to avoid
2831                                                         // duplicate entries in the symbol table
2832                                                         ValueToSymbolIndexMap::const_iterator pos = N_FUN_addr_to_sym_idx.find (nlist.n_value);
2833                                                         if (pos != N_FUN_addr_to_sym_idx.end())
2834                                                         {
2835                                                             if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled))
2836                                                             {
2837                                                                 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
2838                                                                 // We just need the flags from the linker symbol, so put these flags
2839                                                                 // into the N_FUN flags to avoid duplicate symbols in the symbol table
2840                                                                 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
2841                                                                 sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
2842                                                                 sym[sym_idx].Clear();
2843                                                                 continue;
2844                                                             }
2845                                                         }
2846                                                     }
2847                                                     else if (type == eSymbolTypeData)
2848                                                     {
2849                                                         // See if we can find a N_STSYM entry for any data symbols.
2850                                                         // If we do find a match, and the name matches, then we
2851                                                         // can merge the two into just the Static symbol to avoid
2852                                                         // duplicate entries in the symbol table
2853                                                         ValueToSymbolIndexMap::const_iterator pos = N_STSYM_addr_to_sym_idx.find (nlist.n_value);
2854                                                         if (pos != N_STSYM_addr_to_sym_idx.end())
2855                                                         {
2856                                                             if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled))
2857                                                             {
2858                                                                 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
2859                                                                 // We just need the flags from the linker symbol, so put these flags
2860                                                                 // into the N_STSYM flags to avoid duplicate symbols in the symbol table
2861                                                                 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
2862                                                                 sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
2863                                                                 sym[sym_idx].Clear();
2864                                                                 continue;
2865                                                             }
2866                                                         }
2867                                                         else
2868                                                         {
2869                                                             // Combine N_GSYM stab entries with the non stab symbol
2870                                                             ConstNameToSymbolIndexMap::const_iterator pos = N_GSYM_name_to_sym_idx.find(sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString());
2871                                                             if (pos != N_GSYM_name_to_sym_idx.end())
2872                                                             {
2873                                                                 const uint32_t GSYM_sym_idx = pos->second;
2874                                                                 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
2875                                                                 // Copy the address, because often the N_GSYM address has an invalid address of zero
2876                                                                 // when the global is a common symbol
2877                                                                 sym[GSYM_sym_idx].GetAddress().SetSection (symbol_section);
2878                                                                 sym[GSYM_sym_idx].GetAddress().SetOffset (symbol_value);
2879                                                                 // We just need the flags from the linker symbol, so put these flags
2880                                                                 // into the N_STSYM flags to avoid duplicate symbols in the symbol table
2881                                                                 sym[GSYM_sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
2882                                                                 sym[sym_idx].Clear();
2883                                                                 continue;
2884                                                             }
2885                                                         }
2886                                                     }
2887                                                 }
2888 
2889                                                 sym[sym_idx].SetID (nlist_idx);
2890                                                 sym[sym_idx].SetType (type);
2891                                                 sym[sym_idx].GetAddress().SetSection (symbol_section);
2892                                                 sym[sym_idx].GetAddress().SetOffset (symbol_value);
2893                                                 sym[sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
2894 
2895                                                 if (symbol_byte_size > 0)
2896                                                     sym[sym_idx].SetByteSize(symbol_byte_size);
2897 
2898                                                 if (demangled_is_synthesized)
2899                                                     sym[sym_idx].SetDemangledNameIsSynthesized(true);
2900                                                 ++sym_idx;
2901                                             }
2902                                             else
2903                                             {
2904                                                 sym[sym_idx].Clear();
2905                                             }
2906 
2907                                         }
2908                                         /////////////////////////////
2909                                     }
2910                                     break; // No more entries to consider
2911                                 }
2912                             }
2913                         }
2914                     }
2915                 }
2916             }
2917         }
2918 
2919         // Must reset this in case it was mutated above!
2920         nlist_data_offset = 0;
2921 #endif
2922 
2923         if (nlist_data.GetByteSize() > 0)
2924         {
2925 
2926             // If the sym array was not created while parsing the DSC unmapped
2927             // symbols, create it now.
2928             if (sym == NULL)
2929             {
2930                 sym = symtab->Resize (symtab_load_command.nsyms + m_dysymtab.nindirectsyms);
2931                 num_syms = symtab->GetNumSymbols();
2932             }
2933 
2934             if (unmapped_local_symbols_found)
2935             {
2936                 assert(m_dysymtab.ilocalsym == 0);
2937                 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
2938                 nlist_idx = m_dysymtab.nlocalsym;
2939             }
2940             else
2941             {
2942                 nlist_idx = 0;
2943             }
2944 
2945             for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx)
2946             {
2947                 struct nlist_64 nlist;
2948                 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size))
2949                     break;
2950 
2951                 nlist.n_strx  = nlist_data.GetU32_unchecked(&nlist_data_offset);
2952                 nlist.n_type  = nlist_data.GetU8_unchecked (&nlist_data_offset);
2953                 nlist.n_sect  = nlist_data.GetU8_unchecked (&nlist_data_offset);
2954                 nlist.n_desc  = nlist_data.GetU16_unchecked (&nlist_data_offset);
2955                 nlist.n_value = nlist_data.GetAddress_unchecked (&nlist_data_offset);
2956 
2957                 SymbolType type = eSymbolTypeInvalid;
2958                 const char *symbol_name = NULL;
2959 
2960                 if (have_strtab_data)
2961                 {
2962                     symbol_name = strtab_data.PeekCStr(nlist.n_strx);
2963 
2964                     if (symbol_name == NULL)
2965                     {
2966                         // No symbol should be NULL, even the symbols with no
2967                         // string values should have an offset zero which points
2968                         // to an empty C-string
2969                         Host::SystemLog (Host::eSystemLogError,
2970                                          "error: symbol[%u] has invalid string table offset 0x%x in %s, ignoring symbol\n",
2971                                          nlist_idx,
2972                                          nlist.n_strx,
2973                                          module_sp->GetFileSpec().GetPath().c_str());
2974                         continue;
2975                     }
2976                     if (symbol_name[0] == '\0')
2977                         symbol_name = NULL;
2978                 }
2979                 else
2980                 {
2981                     const addr_t str_addr = strtab_addr + nlist.n_strx;
2982                     Error str_error;
2983                     if (process->ReadCStringFromMemory(str_addr, memory_symbol_name, str_error))
2984                         symbol_name = memory_symbol_name.c_str();
2985                 }
2986                 const char *symbol_name_non_abi_mangled = NULL;
2987 
2988                 SectionSP symbol_section;
2989                 lldb::addr_t symbol_byte_size = 0;
2990                 bool add_nlist = true;
2991                 bool is_gsym = false;
2992                 bool is_debug = ((nlist.n_type & N_STAB) != 0);
2993                 bool demangled_is_synthesized = false;
2994 
2995                 assert (sym_idx < num_syms);
2996 
2997                 sym[sym_idx].SetDebug (is_debug);
2998 
2999                 if (is_debug)
3000                 {
3001                     switch (nlist.n_type)
3002                     {
3003                     case N_GSYM:
3004                         // global symbol: name,,NO_SECT,type,0
3005                         // Sometimes the N_GSYM value contains the address.
3006 
3007                         // FIXME: In the .o files, we have a GSYM and a debug symbol for all the ObjC data.  They
3008                         // have the same address, but we want to ensure that we always find only the real symbol,
3009                         // 'cause we don't currently correctly attribute the GSYM one to the ObjCClass/Ivar/MetaClass
3010                         // symbol type.  This is a temporary hack to make sure the ObjectiveC symbols get treated
3011                         // correctly.  To do this right, we should coalesce all the GSYM & global symbols that have the
3012                         // same address.
3013 
3014                         if (symbol_name && symbol_name[0] == '_' && symbol_name[1] ==  'O'
3015                             && (strncmp (symbol_name, "_OBJC_IVAR_$_", strlen ("_OBJC_IVAR_$_")) == 0
3016                                 || strncmp (symbol_name, "_OBJC_CLASS_$_", strlen ("_OBJC_CLASS_$_")) == 0
3017                                 || strncmp (symbol_name, "_OBJC_METACLASS_$_", strlen ("_OBJC_METACLASS_$_")) == 0))
3018                             add_nlist = false;
3019                         else
3020                         {
3021                             is_gsym = true;
3022                             sym[sym_idx].SetExternal(true);
3023                             if (nlist.n_value != 0)
3024                                 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3025                             type = eSymbolTypeData;
3026                         }
3027                         break;
3028 
3029                     case N_FNAME:
3030                         // procedure name (f77 kludge): name,,NO_SECT,0,0
3031                         type = eSymbolTypeCompiler;
3032                         break;
3033 
3034                     case N_FUN:
3035                         // procedure: name,,n_sect,linenumber,address
3036                         if (symbol_name)
3037                         {
3038                             type = eSymbolTypeCode;
3039                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3040 
3041                             N_FUN_addr_to_sym_idx[nlist.n_value] = sym_idx;
3042                             // We use the current number of symbols in the symbol table in lieu of
3043                             // using nlist_idx in case we ever start trimming entries out
3044                             N_FUN_indexes.push_back(sym_idx);
3045                         }
3046                         else
3047                         {
3048                             type = eSymbolTypeCompiler;
3049 
3050                             if ( !N_FUN_indexes.empty() )
3051                             {
3052                                 // Copy the size of the function into the original STAB entry so we don't have
3053                                 // to hunt for it later
3054                                 symtab->SymbolAtIndex(N_FUN_indexes.back())->SetByteSize(nlist.n_value);
3055                                 N_FUN_indexes.pop_back();
3056                                 // We don't really need the end function STAB as it contains the size which
3057                                 // we already placed with the original symbol, so don't add it if we want a
3058                                 // minimal symbol table
3059                                 add_nlist = false;
3060                             }
3061                         }
3062                         break;
3063 
3064                     case N_STSYM:
3065                         // static symbol: name,,n_sect,type,address
3066                         N_STSYM_addr_to_sym_idx[nlist.n_value] = sym_idx;
3067                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3068                         type = eSymbolTypeData;
3069                         break;
3070 
3071                     case N_LCSYM:
3072                         // .lcomm symbol: name,,n_sect,type,address
3073                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3074                         type = eSymbolTypeCommonBlock;
3075                         break;
3076 
3077                     case N_BNSYM:
3078                         // We use the current number of symbols in the symbol table in lieu of
3079                         // using nlist_idx in case we ever start trimming entries out
3080                         // Skip these if we want minimal symbol tables
3081                         add_nlist = false;
3082                         break;
3083 
3084                     case N_ENSYM:
3085                         // Set the size of the N_BNSYM to the terminating index of this N_ENSYM
3086                         // so that we can always skip the entire symbol if we need to navigate
3087                         // more quickly at the source level when parsing STABS
3088                         // Skip these if we want minimal symbol tables
3089                         add_nlist = false;
3090                         break;
3091 
3092 
3093                     case N_OPT:
3094                         // emitted with gcc2_compiled and in gcc source
3095                         type = eSymbolTypeCompiler;
3096                         break;
3097 
3098                     case N_RSYM:
3099                         // register sym: name,,NO_SECT,type,register
3100                         type = eSymbolTypeVariable;
3101                         break;
3102 
3103                     case N_SLINE:
3104                         // src line: 0,,n_sect,linenumber,address
3105                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3106                         type = eSymbolTypeLineEntry;
3107                         break;
3108 
3109                     case N_SSYM:
3110                         // structure elt: name,,NO_SECT,type,struct_offset
3111                         type = eSymbolTypeVariableType;
3112                         break;
3113 
3114                     case N_SO:
3115                         // source file name
3116                         type = eSymbolTypeSourceFile;
3117                         if (symbol_name == NULL)
3118                         {
3119                             add_nlist = false;
3120                             if (N_SO_index != UINT32_MAX)
3121                             {
3122                                 // Set the size of the N_SO to the terminating index of this N_SO
3123                                 // so that we can always skip the entire N_SO if we need to navigate
3124                                 // more quickly at the source level when parsing STABS
3125                                 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3126                                 symbol_ptr->SetByteSize(sym_idx);
3127                                 symbol_ptr->SetSizeIsSibling(true);
3128                             }
3129                             N_NSYM_indexes.clear();
3130                             N_INCL_indexes.clear();
3131                             N_BRAC_indexes.clear();
3132                             N_COMM_indexes.clear();
3133                             N_FUN_indexes.clear();
3134                             N_SO_index = UINT32_MAX;
3135                         }
3136                         else
3137                         {
3138                             // We use the current number of symbols in the symbol table in lieu of
3139                             // using nlist_idx in case we ever start trimming entries out
3140                             const bool N_SO_has_full_path = symbol_name[0] == '/';
3141                             if (N_SO_has_full_path)
3142                             {
3143                                 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
3144                                 {
3145                                     // We have two consecutive N_SO entries where the first contains a directory
3146                                     // and the second contains a full path.
3147                                     sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name), false);
3148                                     m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3149                                     add_nlist = false;
3150                                 }
3151                                 else
3152                                 {
3153                                     // This is the first entry in a N_SO that contains a directory or
3154                                     // a full path to the source file
3155                                     N_SO_index = sym_idx;
3156                                 }
3157                             }
3158                             else if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
3159                             {
3160                                 // This is usually the second N_SO entry that contains just the filename,
3161                                 // so here we combine it with the first one if we are minimizing the symbol table
3162                                 const char *so_path = sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString();
3163                                 if (so_path && so_path[0])
3164                                 {
3165                                     std::string full_so_path (so_path);
3166                                     const size_t double_slash_pos = full_so_path.find("//");
3167                                     if (double_slash_pos != std::string::npos)
3168                                     {
3169                                         // The linker has been generating bad N_SO entries with doubled up paths
3170                                         // in the format "%s%s" where the first string in the DW_AT_comp_dir,
3171                                         // and the second is the directory for the source file so you end up with
3172                                         // a path that looks like "/tmp/src//tmp/src/"
3173                                         FileSpec so_dir(so_path, false);
3174                                         if (!so_dir.Exists())
3175                                         {
3176                                             so_dir.SetFile(&full_so_path[double_slash_pos + 1], false);
3177                                             if (so_dir.Exists())
3178                                             {
3179                                                 // Trim off the incorrect path
3180                                                 full_so_path.erase(0, double_slash_pos + 1);
3181                                             }
3182                                         }
3183                                     }
3184                                     if (*full_so_path.rbegin() != '/')
3185                                         full_so_path += '/';
3186                                     full_so_path += symbol_name;
3187                                     sym[sym_idx - 1].GetMangled().SetValue(ConstString(full_so_path.c_str()), false);
3188                                     add_nlist = false;
3189                                     m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3190                                 }
3191                             }
3192                             else
3193                             {
3194                                 // This could be a relative path to a N_SO
3195                                 N_SO_index = sym_idx;
3196                             }
3197                         }
3198 
3199                         break;
3200 
3201                     case N_OSO:
3202                         // object file name: name,,0,0,st_mtime
3203                         type = eSymbolTypeObjectFile;
3204                         break;
3205 
3206                     case N_LSYM:
3207                         // local sym: name,,NO_SECT,type,offset
3208                         type = eSymbolTypeLocal;
3209                         break;
3210 
3211                     //----------------------------------------------------------------------
3212                     // INCL scopes
3213                     //----------------------------------------------------------------------
3214                     case N_BINCL:
3215                         // include file beginning: name,,NO_SECT,0,sum
3216                         // We use the current number of symbols in the symbol table in lieu of
3217                         // using nlist_idx in case we ever start trimming entries out
3218                         N_INCL_indexes.push_back(sym_idx);
3219                         type = eSymbolTypeScopeBegin;
3220                         break;
3221 
3222                     case N_EINCL:
3223                         // include file end: name,,NO_SECT,0,0
3224                         // Set the size of the N_BINCL to the terminating index of this N_EINCL
3225                         // so that we can always skip the entire symbol if we need to navigate
3226                         // more quickly at the source level when parsing STABS
3227                         if ( !N_INCL_indexes.empty() )
3228                         {
3229                             symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
3230                             symbol_ptr->SetByteSize(sym_idx + 1);
3231                             symbol_ptr->SetSizeIsSibling(true);
3232                             N_INCL_indexes.pop_back();
3233                         }
3234                         type = eSymbolTypeScopeEnd;
3235                         break;
3236 
3237                     case N_SOL:
3238                         // #included file name: name,,n_sect,0,address
3239                         type = eSymbolTypeHeaderFile;
3240 
3241                         // We currently don't use the header files on darwin
3242                         add_nlist = false;
3243                         break;
3244 
3245                     case N_PARAMS:
3246                         // compiler parameters: name,,NO_SECT,0,0
3247                         type = eSymbolTypeCompiler;
3248                         break;
3249 
3250                     case N_VERSION:
3251                         // compiler version: name,,NO_SECT,0,0
3252                         type = eSymbolTypeCompiler;
3253                         break;
3254 
3255                     case N_OLEVEL:
3256                         // compiler -O level: name,,NO_SECT,0,0
3257                         type = eSymbolTypeCompiler;
3258                         break;
3259 
3260                     case N_PSYM:
3261                         // parameter: name,,NO_SECT,type,offset
3262                         type = eSymbolTypeVariable;
3263                         break;
3264 
3265                     case N_ENTRY:
3266                         // alternate entry: name,,n_sect,linenumber,address
3267                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3268                         type = eSymbolTypeLineEntry;
3269                         break;
3270 
3271                     //----------------------------------------------------------------------
3272                     // Left and Right Braces
3273                     //----------------------------------------------------------------------
3274                     case N_LBRAC:
3275                         // left bracket: 0,,NO_SECT,nesting level,address
3276                         // We use the current number of symbols in the symbol table in lieu of
3277                         // using nlist_idx in case we ever start trimming entries out
3278                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3279                         N_BRAC_indexes.push_back(sym_idx);
3280                         type = eSymbolTypeScopeBegin;
3281                         break;
3282 
3283                     case N_RBRAC:
3284                         // right bracket: 0,,NO_SECT,nesting level,address
3285                         // Set the size of the N_LBRAC to the terminating index of this N_RBRAC
3286                         // so that we can always skip the entire symbol if we need to navigate
3287                         // more quickly at the source level when parsing STABS
3288                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3289                         if ( !N_BRAC_indexes.empty() )
3290                         {
3291                             symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
3292                             symbol_ptr->SetByteSize(sym_idx + 1);
3293                             symbol_ptr->SetSizeIsSibling(true);
3294                             N_BRAC_indexes.pop_back();
3295                         }
3296                         type = eSymbolTypeScopeEnd;
3297                         break;
3298 
3299                     case N_EXCL:
3300                         // deleted include file: name,,NO_SECT,0,sum
3301                         type = eSymbolTypeHeaderFile;
3302                         break;
3303 
3304                     //----------------------------------------------------------------------
3305                     // COMM scopes
3306                     //----------------------------------------------------------------------
3307                     case N_BCOMM:
3308                         // begin common: name,,NO_SECT,0,0
3309                         // We use the current number of symbols in the symbol table in lieu of
3310                         // using nlist_idx in case we ever start trimming entries out
3311                         type = eSymbolTypeScopeBegin;
3312                         N_COMM_indexes.push_back(sym_idx);
3313                         break;
3314 
3315                     case N_ECOML:
3316                         // end common (local name): 0,,n_sect,0,address
3317                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3318                         // Fall through
3319 
3320                     case N_ECOMM:
3321                         // end common: name,,n_sect,0,0
3322                         // Set the size of the N_BCOMM to the terminating index of this N_ECOMM/N_ECOML
3323                         // so that we can always skip the entire symbol if we need to navigate
3324                         // more quickly at the source level when parsing STABS
3325                         if ( !N_COMM_indexes.empty() )
3326                         {
3327                             symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
3328                             symbol_ptr->SetByteSize(sym_idx + 1);
3329                             symbol_ptr->SetSizeIsSibling(true);
3330                             N_COMM_indexes.pop_back();
3331                         }
3332                         type = eSymbolTypeScopeEnd;
3333                         break;
3334 
3335                     case N_LENG:
3336                         // second stab entry with length information
3337                         type = eSymbolTypeAdditional;
3338                         break;
3339 
3340                     default: break;
3341                     }
3342                 }
3343                 else
3344                 {
3345                     //uint8_t n_pext    = N_PEXT & nlist.n_type;
3346                     uint8_t n_type  = N_TYPE & nlist.n_type;
3347                     sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
3348 
3349                     switch (n_type)
3350                     {
3351                     case N_INDR:// Fall through
3352                     case N_PBUD:// Fall through
3353                     case N_UNDF:
3354                         type = eSymbolTypeUndefined;
3355                         break;
3356 
3357                     case N_ABS:
3358                         type = eSymbolTypeAbsolute;
3359                         break;
3360 
3361                     case N_SECT:
3362                         {
3363                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3364 
3365                             if (!symbol_section)
3366                             {
3367                                 // TODO: warn about this?
3368                                 add_nlist = false;
3369                                 break;
3370                             }
3371 
3372                             if (TEXT_eh_frame_sectID == nlist.n_sect)
3373                             {
3374                                 type = eSymbolTypeException;
3375                             }
3376                             else
3377                             {
3378                                 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
3379 
3380                                 switch (section_type)
3381                                 {
3382                                 case S_REGULAR:                    break; // regular section
3383                                 //case S_ZEROFILL:                 type = eSymbolTypeData;    break; // zero fill on demand section
3384                                 case S_CSTRING_LITERALS:           type = eSymbolTypeData;    break; // section with only literal C strings
3385                                 case S_4BYTE_LITERALS:             type = eSymbolTypeData;    break; // section with only 4 byte literals
3386                                 case S_8BYTE_LITERALS:             type = eSymbolTypeData;    break; // section with only 8 byte literals
3387                                 case S_LITERAL_POINTERS:           type = eSymbolTypeTrampoline; break; // section with only pointers to literals
3388                                 case S_NON_LAZY_SYMBOL_POINTERS:   type = eSymbolTypeTrampoline; break; // section with only non-lazy symbol pointers
3389                                 case S_LAZY_SYMBOL_POINTERS:       type = eSymbolTypeTrampoline; break; // section with only lazy symbol pointers
3390                                 case S_SYMBOL_STUBS:               type = eSymbolTypeTrampoline; break; // section with only symbol stubs, byte size of stub in the reserved2 field
3391                                 case S_MOD_INIT_FUNC_POINTERS:     type = eSymbolTypeCode;    break; // section with only function pointers for initialization
3392                                 case S_MOD_TERM_FUNC_POINTERS:     type = eSymbolTypeCode;    break; // section with only function pointers for termination
3393                                 //case S_COALESCED:                type = eSymbolType;    break; // section contains symbols that are to be coalesced
3394                                 //case S_GB_ZEROFILL:              type = eSymbolTypeData;    break; // zero fill on demand section (that can be larger than 4 gigabytes)
3395                                 case S_INTERPOSING:                type = eSymbolTypeTrampoline;  break; // section with only pairs of function pointers for interposing
3396                                 case S_16BYTE_LITERALS:            type = eSymbolTypeData;    break; // section with only 16 byte literals
3397                                 case S_DTRACE_DOF:                 type = eSymbolTypeInstrumentation; break;
3398                                 case S_LAZY_DYLIB_SYMBOL_POINTERS: type = eSymbolTypeTrampoline; break;
3399                                 default: break;
3400                                 }
3401 
3402                                 if (type == eSymbolTypeInvalid)
3403                                 {
3404                                     const char *symbol_sect_name = symbol_section->GetName().AsCString();
3405                                     if (symbol_section->IsDescendant (text_section_sp.get()))
3406                                     {
3407                                         if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
3408                                                                     S_ATTR_SELF_MODIFYING_CODE |
3409                                                                     S_ATTR_SOME_INSTRUCTIONS))
3410                                             type = eSymbolTypeData;
3411                                         else
3412                                             type = eSymbolTypeCode;
3413                                     }
3414                                     else
3415                                     if (symbol_section->IsDescendant(data_section_sp.get()))
3416                                     {
3417                                         if (symbol_sect_name && ::strstr (symbol_sect_name, "__objc") == symbol_sect_name)
3418                                         {
3419                                             type = eSymbolTypeRuntime;
3420 
3421                                             if (symbol_name &&
3422                                                 symbol_name[0] == '_' &&
3423                                                 symbol_name[1] == 'O' &&
3424                                                 symbol_name[2] == 'B')
3425                                             {
3426                                                 llvm::StringRef symbol_name_ref(symbol_name);
3427                                                 static const llvm::StringRef g_objc_v2_prefix_class ("_OBJC_CLASS_$_");
3428                                                 static const llvm::StringRef g_objc_v2_prefix_metaclass ("_OBJC_METACLASS_$_");
3429                                                 static const llvm::StringRef g_objc_v2_prefix_ivar ("_OBJC_IVAR_$_");
3430                                                 if (symbol_name_ref.startswith(g_objc_v2_prefix_class))
3431                                                 {
3432                                                     symbol_name_non_abi_mangled = symbol_name + 1;
3433                                                     symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3434                                                     type = eSymbolTypeObjCClass;
3435                                                     demangled_is_synthesized = true;
3436                                                 }
3437                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass))
3438                                                 {
3439                                                     symbol_name_non_abi_mangled = symbol_name + 1;
3440                                                     symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3441                                                     type = eSymbolTypeObjCMetaClass;
3442                                                     demangled_is_synthesized = true;
3443                                                 }
3444                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar))
3445                                                 {
3446                                                     symbol_name_non_abi_mangled = symbol_name + 1;
3447                                                     symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3448                                                     type = eSymbolTypeObjCIVar;
3449                                                     demangled_is_synthesized = true;
3450                                                 }
3451                                             }
3452                                         }
3453                                         else
3454                                         if (symbol_sect_name && ::strstr (symbol_sect_name, "__gcc_except_tab") == symbol_sect_name)
3455                                         {
3456                                             type = eSymbolTypeException;
3457                                         }
3458                                         else
3459                                         {
3460                                             type = eSymbolTypeData;
3461                                         }
3462                                     }
3463                                     else
3464                                     if (symbol_sect_name && ::strstr (symbol_sect_name, "__IMPORT") == symbol_sect_name)
3465                                     {
3466                                         type = eSymbolTypeTrampoline;
3467                                     }
3468                                     else
3469                                     if (symbol_section->IsDescendant(objc_section_sp.get()))
3470                                     {
3471                                         type = eSymbolTypeRuntime;
3472                                         if (symbol_name && symbol_name[0] == '.')
3473                                         {
3474                                             llvm::StringRef symbol_name_ref(symbol_name);
3475                                             static const llvm::StringRef g_objc_v1_prefix_class (".objc_class_name_");
3476                                             if (symbol_name_ref.startswith(g_objc_v1_prefix_class))
3477                                             {
3478                                                 symbol_name_non_abi_mangled = symbol_name;
3479                                                 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
3480                                                 type = eSymbolTypeObjCClass;
3481                                                 demangled_is_synthesized = true;
3482                                             }
3483                                         }
3484                                     }
3485                                 }
3486                             }
3487                         }
3488                         break;
3489                     }
3490                 }
3491 
3492                 if (add_nlist)
3493                 {
3494                     uint64_t symbol_value = nlist.n_value;
3495 
3496                     if (symbol_name_non_abi_mangled)
3497                     {
3498                         sym[sym_idx].GetMangled().SetMangledName (ConstString(symbol_name_non_abi_mangled));
3499                         sym[sym_idx].GetMangled().SetDemangledName (ConstString(symbol_name));
3500                     }
3501                     else
3502                     {
3503                         bool symbol_name_is_mangled = false;
3504 
3505                         if (symbol_name && symbol_name[0] == '_')
3506                         {
3507                             symbol_name_is_mangled = symbol_name[1] == '_';
3508                             symbol_name++;  // Skip the leading underscore
3509                         }
3510 
3511                         if (symbol_name)
3512                         {
3513                             ConstString const_symbol_name(symbol_name);
3514                             sym[sym_idx].GetMangled().SetValue(const_symbol_name, symbol_name_is_mangled);
3515                             if (is_gsym && is_debug)
3516                             {
3517                                 N_GSYM_name_to_sym_idx[sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString()] = sym_idx;
3518                             }
3519                         }
3520                     }
3521                     if (symbol_section)
3522                     {
3523                         const addr_t section_file_addr = symbol_section->GetFileAddress();
3524                         if (symbol_byte_size == 0 && function_starts_count > 0)
3525                         {
3526                             addr_t symbol_lookup_file_addr = nlist.n_value;
3527                             // Do an exact address match for non-ARM addresses, else get the closest since
3528                             // the symbol might be a thumb symbol which has an address with bit zero set
3529                             FunctionStarts::Entry *func_start_entry = function_starts.FindEntry (symbol_lookup_file_addr, !is_arm);
3530                             if (is_arm && func_start_entry)
3531                             {
3532                                 // Verify that the function start address is the symbol address (ARM)
3533                                 // or the symbol address + 1 (thumb)
3534                                 if (func_start_entry->addr != symbol_lookup_file_addr &&
3535                                     func_start_entry->addr != (symbol_lookup_file_addr + 1))
3536                                 {
3537                                     // Not the right entry, NULL it out...
3538                                     func_start_entry = NULL;
3539                                 }
3540                             }
3541                             if (func_start_entry)
3542                             {
3543                                 func_start_entry->data = true;
3544 
3545                                 addr_t symbol_file_addr = func_start_entry->addr;
3546                                 if (is_arm)
3547                                     symbol_file_addr &= 0xfffffffffffffffeull;
3548 
3549                                 const FunctionStarts::Entry *next_func_start_entry = function_starts.FindNextEntry (func_start_entry);
3550                                 const addr_t section_end_file_addr = section_file_addr + symbol_section->GetByteSize();
3551                                 if (next_func_start_entry)
3552                                 {
3553                                     addr_t next_symbol_file_addr = next_func_start_entry->addr;
3554                                     // Be sure the clear the Thumb address bit when we calculate the size
3555                                     // from the current and next address
3556                                     if (is_arm)
3557                                         next_symbol_file_addr &= 0xfffffffffffffffeull;
3558                                     symbol_byte_size = std::min<lldb::addr_t>(next_symbol_file_addr - symbol_file_addr, section_end_file_addr - symbol_file_addr);
3559                                 }
3560                                 else
3561                                 {
3562                                     symbol_byte_size = section_end_file_addr - symbol_file_addr;
3563                                 }
3564                             }
3565                         }
3566                         symbol_value -= section_file_addr;
3567                     }
3568 
3569                     if (is_debug == false)
3570                     {
3571                         if (type == eSymbolTypeCode)
3572                         {
3573                             // See if we can find a N_FUN entry for any code symbols.
3574                             // If we do find a match, and the name matches, then we
3575                             // can merge the two into just the function symbol to avoid
3576                             // duplicate entries in the symbol table
3577                             ValueToSymbolIndexMap::const_iterator pos = N_FUN_addr_to_sym_idx.find (nlist.n_value);
3578                             if (pos != N_FUN_addr_to_sym_idx.end())
3579                             {
3580                                 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled))
3581                                 {
3582                                     m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3583                                     // We just need the flags from the linker symbol, so put these flags
3584                                     // into the N_FUN flags to avoid duplicate symbols in the symbol table
3585                                     sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
3586                                     sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3587                                     sym[sym_idx].Clear();
3588                                     continue;
3589                                 }
3590                             }
3591                         }
3592                         else if (type == eSymbolTypeData)
3593                         {
3594                             // See if we can find a N_STSYM entry for any data symbols.
3595                             // If we do find a match, and the name matches, then we
3596                             // can merge the two into just the Static symbol to avoid
3597                             // duplicate entries in the symbol table
3598                             ValueToSymbolIndexMap::const_iterator pos = N_STSYM_addr_to_sym_idx.find (nlist.n_value);
3599                             if (pos != N_STSYM_addr_to_sym_idx.end())
3600                             {
3601                                 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled))
3602                                 {
3603                                     m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3604                                     // We just need the flags from the linker symbol, so put these flags
3605                                     // into the N_STSYM flags to avoid duplicate symbols in the symbol table
3606                                     sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
3607                                     sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3608                                     sym[sym_idx].Clear();
3609                                     continue;
3610                                 }
3611                             }
3612                             else
3613                             {
3614                                 // Combine N_GSYM stab entries with the non stab symbol
3615                                 ConstNameToSymbolIndexMap::const_iterator pos = N_GSYM_name_to_sym_idx.find(sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString());
3616                                 if (pos != N_GSYM_name_to_sym_idx.end())
3617                                 {
3618                                     const uint32_t GSYM_sym_idx = pos->second;
3619                                     m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
3620                                     // Copy the address, because often the N_GSYM address has an invalid address of zero
3621                                     // when the global is a common symbol
3622                                     sym[GSYM_sym_idx].GetAddress().SetSection (symbol_section);
3623                                     sym[GSYM_sym_idx].GetAddress().SetOffset (symbol_value);
3624                                     // We just need the flags from the linker symbol, so put these flags
3625                                     // into the N_STSYM flags to avoid duplicate symbols in the symbol table
3626                                     sym[GSYM_sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3627                                     sym[sym_idx].Clear();
3628                                     continue;
3629                                 }
3630                             }
3631                         }
3632                     }
3633 
3634                     sym[sym_idx].SetID (nlist_idx);
3635                     sym[sym_idx].SetType (type);
3636                     sym[sym_idx].GetAddress().SetSection (symbol_section);
3637                     sym[sym_idx].GetAddress().SetOffset (symbol_value);
3638                     sym[sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3639 
3640                     if (symbol_byte_size > 0)
3641                         sym[sym_idx].SetByteSize(symbol_byte_size);
3642 
3643                     if (demangled_is_synthesized)
3644                         sym[sym_idx].SetDemangledNameIsSynthesized(true);
3645 
3646                     ++sym_idx;
3647                 }
3648                 else
3649                 {
3650                     sym[sym_idx].Clear();
3651                 }
3652             }
3653         }
3654 
3655         uint32_t synthetic_sym_id = symtab_load_command.nsyms;
3656 
3657         if (function_starts_count > 0)
3658         {
3659             char synthetic_function_symbol[PATH_MAX];
3660             uint32_t num_synthetic_function_symbols = 0;
3661             for (i=0; i<function_starts_count; ++i)
3662             {
3663                 if (function_starts.GetEntryRef (i).data == false)
3664                     ++num_synthetic_function_symbols;
3665             }
3666 
3667             if (num_synthetic_function_symbols > 0)
3668             {
3669                 if (num_syms < sym_idx + num_synthetic_function_symbols)
3670                 {
3671                     num_syms = sym_idx + num_synthetic_function_symbols;
3672                     sym = symtab->Resize (num_syms);
3673                 }
3674                 uint32_t synthetic_function_symbol_idx = 0;
3675                 for (i=0; i<function_starts_count; ++i)
3676                 {
3677                     const FunctionStarts::Entry *func_start_entry = function_starts.GetEntryAtIndex (i);
3678                     if (func_start_entry->data == false)
3679                     {
3680                         addr_t symbol_file_addr = func_start_entry->addr;
3681                         uint32_t symbol_flags = 0;
3682                         if (is_arm)
3683                         {
3684                             if (symbol_file_addr & 1)
3685                                 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3686                             symbol_file_addr &= 0xfffffffffffffffeull;
3687                         }
3688                         Address symbol_addr;
3689                         if (module_sp->ResolveFileAddress (symbol_file_addr, symbol_addr))
3690                         {
3691                             SectionSP symbol_section (symbol_addr.GetSection());
3692                             uint32_t symbol_byte_size = 0;
3693                             if (symbol_section)
3694                             {
3695                                 const addr_t section_file_addr = symbol_section->GetFileAddress();
3696                                 const FunctionStarts::Entry *next_func_start_entry = function_starts.FindNextEntry (func_start_entry);
3697                                 const addr_t section_end_file_addr = section_file_addr + symbol_section->GetByteSize();
3698                                 if (next_func_start_entry)
3699                                 {
3700                                     addr_t next_symbol_file_addr = next_func_start_entry->addr;
3701                                     if (is_arm)
3702                                         next_symbol_file_addr &= 0xfffffffffffffffeull;
3703                                     symbol_byte_size = std::min<lldb::addr_t>(next_symbol_file_addr - symbol_file_addr, section_end_file_addr - symbol_file_addr);
3704                                 }
3705                                 else
3706                                 {
3707                                     symbol_byte_size = section_end_file_addr - symbol_file_addr;
3708                                 }
3709                                 snprintf (synthetic_function_symbol,
3710                                           sizeof(synthetic_function_symbol),
3711                                           "___lldb_unnamed_function%u$$%s",
3712                                           ++synthetic_function_symbol_idx,
3713                                           module_sp->GetFileSpec().GetFilename().GetCString());
3714                                 sym[sym_idx].SetID (synthetic_sym_id++);
3715                                 sym[sym_idx].GetMangled().SetDemangledName(ConstString(synthetic_function_symbol));
3716                                 sym[sym_idx].SetType (eSymbolTypeCode);
3717                                 sym[sym_idx].SetIsSynthetic (true);
3718                                 sym[sym_idx].GetAddress() = symbol_addr;
3719                                 if (symbol_flags)
3720                                     sym[sym_idx].SetFlags (symbol_flags);
3721                                 if (symbol_byte_size)
3722                                     sym[sym_idx].SetByteSize (symbol_byte_size);
3723                                 ++sym_idx;
3724                             }
3725                         }
3726                     }
3727                 }
3728             }
3729         }
3730 
3731         // Trim our symbols down to just what we ended up with after
3732         // removing any symbols.
3733         if (sym_idx < num_syms)
3734         {
3735             num_syms = sym_idx;
3736             sym = symtab->Resize (num_syms);
3737         }
3738 
3739         std::vector<TrieEntryWithOffset> trie_entries;
3740         std::set<lldb::addr_t> resolver_addresses;
3741 
3742         if (dyld_trie_data.GetByteSize() > 0)
3743         {
3744             std::vector<llvm::StringRef> nameSlices;
3745             ParseTrieEntries (dyld_trie_data,
3746                               0,
3747                               nameSlices,
3748                               resolver_addresses,
3749                               trie_entries);
3750 
3751             ConstString text_segment_name ("__TEXT");
3752             SectionSP text_segment_sp = GetSectionList()->FindSectionByName(text_segment_name);
3753             if (text_segment_sp)
3754             {
3755                 const lldb::addr_t text_segment_file_addr = text_segment_sp->GetFileAddress();
3756                 if (text_segment_file_addr != LLDB_INVALID_ADDRESS)
3757                 {
3758                     for (auto &e : trie_entries)
3759                         e.entry.address += text_segment_file_addr;
3760                 }
3761             }
3762         }
3763 
3764         // Now synthesize indirect symbols
3765         if (m_dysymtab.nindirectsyms != 0)
3766         {
3767             if (indirect_symbol_index_data.GetByteSize())
3768             {
3769                 NListIndexToSymbolIndexMap::const_iterator end_index_pos = m_nlist_idx_to_sym_idx.end();
3770 
3771                 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size(); ++sect_idx)
3772                 {
3773                     if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) == S_SYMBOL_STUBS)
3774                     {
3775                         uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2;
3776                         if (symbol_stub_byte_size == 0)
3777                             continue;
3778 
3779                         const uint32_t num_symbol_stubs = m_mach_sections[sect_idx].size / symbol_stub_byte_size;
3780 
3781                         if (num_symbol_stubs == 0)
3782                             continue;
3783 
3784                         const uint32_t symbol_stub_index_offset = m_mach_sections[sect_idx].reserved1;
3785                         for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx)
3786                         {
3787                             const uint32_t symbol_stub_index = symbol_stub_index_offset + stub_idx;
3788                             const lldb::addr_t symbol_stub_addr = m_mach_sections[sect_idx].addr + (stub_idx * symbol_stub_byte_size);
3789                             lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
3790                             if (indirect_symbol_index_data.ValidOffsetForDataOfSize(symbol_stub_offset, 4))
3791                             {
3792                                 const uint32_t stub_sym_id = indirect_symbol_index_data.GetU32 (&symbol_stub_offset);
3793                                 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
3794                                     continue;
3795 
3796                                 NListIndexToSymbolIndexMap::const_iterator index_pos = m_nlist_idx_to_sym_idx.find (stub_sym_id);
3797                                 Symbol *stub_symbol = NULL;
3798                                 if (index_pos != end_index_pos)
3799                                 {
3800                                     // We have a remapping from the original nlist index to
3801                                     // a current symbol index, so just look this up by index
3802                                     stub_symbol = symtab->SymbolAtIndex (index_pos->second);
3803                                 }
3804                                 else
3805                                 {
3806                                     // We need to lookup a symbol using the original nlist
3807                                     // symbol index since this index is coming from the
3808                                     // S_SYMBOL_STUBS
3809                                     stub_symbol = symtab->FindSymbolByID (stub_sym_id);
3810                                 }
3811 
3812                                 if (stub_symbol)
3813                                 {
3814                                     Address so_addr(symbol_stub_addr, section_list);
3815 
3816                                     if (stub_symbol->GetType() == eSymbolTypeUndefined)
3817                                     {
3818                                         // Change the external symbol into a trampoline that makes sense
3819                                         // These symbols were N_UNDF N_EXT, and are useless to us, so we
3820                                         // can re-use them so we don't have to make up a synthetic symbol
3821                                         // for no good reason.
3822                                         if (resolver_addresses.find(symbol_stub_addr) == resolver_addresses.end())
3823                                             stub_symbol->SetType (eSymbolTypeTrampoline);
3824                                         else
3825                                             stub_symbol->SetType (eSymbolTypeResolver);
3826                                         stub_symbol->SetExternal (false);
3827                                         stub_symbol->GetAddress() = so_addr;
3828                                         stub_symbol->SetByteSize (symbol_stub_byte_size);
3829                                     }
3830                                     else
3831                                     {
3832                                         // Make a synthetic symbol to describe the trampoline stub
3833                                         Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
3834                                         if (sym_idx >= num_syms)
3835                                         {
3836                                             sym = symtab->Resize (++num_syms);
3837                                             stub_symbol = NULL;  // this pointer no longer valid
3838                                         }
3839                                         sym[sym_idx].SetID (synthetic_sym_id++);
3840                                         sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
3841                                         if (resolver_addresses.find(symbol_stub_addr) == resolver_addresses.end())
3842                                             sym[sym_idx].SetType (eSymbolTypeTrampoline);
3843                                         else
3844                                             sym[sym_idx].SetType (eSymbolTypeResolver);
3845                                         sym[sym_idx].SetIsSynthetic (true);
3846                                         sym[sym_idx].GetAddress() = so_addr;
3847                                         sym[sym_idx].SetByteSize (symbol_stub_byte_size);
3848                                         ++sym_idx;
3849                                     }
3850                                 }
3851                                 else
3852                                 {
3853                                     if (log)
3854                                         log->Warning ("symbol stub referencing symbol table symbol %u that isn't in our minimal symbol table, fix this!!!", stub_sym_id);
3855                                 }
3856                             }
3857                         }
3858                     }
3859                 }
3860             }
3861         }
3862 
3863 
3864         if (!trie_entries.empty())
3865         {
3866             for (const auto &e : trie_entries)
3867             {
3868                 if (e.entry.import_name)
3869                 {
3870                     // Make a synthetic symbol to describe re-exported symbol.
3871                     if (sym_idx >= num_syms)
3872                         sym = symtab->Resize (++num_syms);
3873                     sym[sym_idx].SetID (synthetic_sym_id++);
3874                     sym[sym_idx].GetMangled() = Mangled(e.entry.name);
3875                     sym[sym_idx].SetType (eSymbolTypeReExported);
3876                     sym[sym_idx].SetIsSynthetic (true);
3877                     sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
3878                     if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize())
3879                     {
3880                         sym[sym_idx].SetReExportedSymbolSharedLibrary(dylib_files.GetFileSpecAtIndex(e.entry.other-1));
3881                     }
3882                     ++sym_idx;
3883                 }
3884             }
3885         }
3886 
3887 
3888 
3889 //        StreamFile s(stdout, false);
3890 //        s.Printf ("Symbol table before CalculateSymbolSizes():\n");
3891 //        symtab->Dump(&s, NULL, eSortOrderNone);
3892         // Set symbol byte sizes correctly since mach-o nlist entries don't have sizes
3893         symtab->CalculateSymbolSizes();
3894 
3895 //        s.Printf ("Symbol table after CalculateSymbolSizes():\n");
3896 //        symtab->Dump(&s, NULL, eSortOrderNone);
3897 
3898         return symtab->GetNumSymbols();
3899     }
3900     return 0;
3901 }
3902 
3903 
3904 void
3905 ObjectFileMachO::Dump (Stream *s)
3906 {
3907     ModuleSP module_sp(GetModule());
3908     if (module_sp)
3909     {
3910         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
3911         s->Printf("%p: ", this);
3912         s->Indent();
3913         if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
3914             s->PutCString("ObjectFileMachO64");
3915         else
3916             s->PutCString("ObjectFileMachO32");
3917 
3918         ArchSpec header_arch(eArchTypeMachO, m_header.cputype, m_header.cpusubtype);
3919 
3920         *s << ", file = '" << m_file << "', arch = " << header_arch.GetArchitectureName() << "\n";
3921 
3922         SectionList *sections = GetSectionList();
3923         if (sections)
3924             sections->Dump(s, NULL, true, UINT32_MAX);
3925 
3926         if (m_symtab_ap.get())
3927             m_symtab_ap->Dump(s, NULL, eSortOrderNone);
3928     }
3929 }
3930 
3931 bool
3932 ObjectFileMachO::GetUUID (const llvm::MachO::mach_header &header,
3933                           const lldb_private::DataExtractor &data,
3934                           lldb::offset_t lc_offset,
3935                           lldb_private::UUID& uuid)
3936 {
3937     uint32_t i;
3938     struct uuid_command load_cmd;
3939 
3940     lldb::offset_t offset = lc_offset;
3941     for (i=0; i<header.ncmds; ++i)
3942     {
3943         const lldb::offset_t cmd_offset = offset;
3944         if (data.GetU32(&offset, &load_cmd, 2) == NULL)
3945             break;
3946 
3947         if (load_cmd.cmd == LC_UUID)
3948         {
3949             const uint8_t *uuid_bytes = data.PeekData(offset, 16);
3950 
3951             if (uuid_bytes)
3952             {
3953                 // OpenCL on Mac OS X uses the same UUID for each of its object files.
3954                 // We pretend these object files have no UUID to prevent crashing.
3955 
3956                 const uint8_t opencl_uuid[] = { 0x8c, 0x8e, 0xb3, 0x9b,
3957                     0x3b, 0xa8,
3958                     0x4b, 0x16,
3959                     0xb6, 0xa4,
3960                     0x27, 0x63, 0xbb, 0x14, 0xf0, 0x0d };
3961 
3962                 if (!memcmp(uuid_bytes, opencl_uuid, 16))
3963                     return false;
3964 
3965                 uuid.SetBytes (uuid_bytes);
3966                 return true;
3967             }
3968             return false;
3969         }
3970         offset = cmd_offset + load_cmd.cmdsize;
3971     }
3972     return false;
3973 }
3974 
3975 bool
3976 ObjectFileMachO::GetUUID (lldb_private::UUID* uuid)
3977 {
3978     ModuleSP module_sp(GetModule());
3979     if (module_sp)
3980     {
3981         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
3982         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
3983         return GetUUID (m_header, m_data, offset, *uuid);
3984     }
3985     return false;
3986 }
3987 
3988 
3989 uint32_t
3990 ObjectFileMachO::GetDependentModules (FileSpecList& files)
3991 {
3992     uint32_t count = 0;
3993     ModuleSP module_sp(GetModule());
3994     if (module_sp)
3995     {
3996         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
3997         struct load_command load_cmd;
3998         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
3999         const bool resolve_path = false; // Don't resolve the dependend file paths since they may not reside on this system
4000         uint32_t i;
4001         for (i=0; i<m_header.ncmds; ++i)
4002         {
4003             const uint32_t cmd_offset = offset;
4004             if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
4005                 break;
4006 
4007             switch (load_cmd.cmd)
4008             {
4009             case LC_LOAD_DYLIB:
4010             case LC_LOAD_WEAK_DYLIB:
4011             case LC_REEXPORT_DYLIB:
4012             case LC_LOAD_DYLINKER:
4013             case LC_LOADFVMLIB:
4014             case LC_LOAD_UPWARD_DYLIB:
4015                 {
4016                     uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
4017                     const char *path = m_data.PeekCStr(name_offset);
4018                     // Skip any path that starts with '@' since these are usually:
4019                     // @executable_path/.../file
4020                     // @rpath/.../file
4021                     if (path && path[0] != '@')
4022                     {
4023                         FileSpec file_spec(path, resolve_path);
4024                         if (files.AppendIfUnique(file_spec))
4025                             count++;
4026                     }
4027                 }
4028                 break;
4029 
4030             default:
4031                 break;
4032             }
4033             offset = cmd_offset + load_cmd.cmdsize;
4034         }
4035     }
4036     return count;
4037 }
4038 
4039 lldb_private::Address
4040 ObjectFileMachO::GetEntryPointAddress ()
4041 {
4042     // If the object file is not an executable it can't hold the entry point.  m_entry_point_address
4043     // is initialized to an invalid address, so we can just return that.
4044     // If m_entry_point_address is valid it means we've found it already, so return the cached value.
4045 
4046     if (!IsExecutable() || m_entry_point_address.IsValid())
4047         return m_entry_point_address;
4048 
4049     // Otherwise, look for the UnixThread or Thread command.  The data for the Thread command is given in
4050     // /usr/include/mach-o.h, but it is basically:
4051     //
4052     //  uint32_t flavor  - this is the flavor argument you would pass to thread_get_state
4053     //  uint32_t count   - this is the count of longs in the thread state data
4054     //  struct XXX_thread_state state - this is the structure from <machine/thread_status.h> corresponding to the flavor.
4055     //  <repeat this trio>
4056     //
4057     // So we just keep reading the various register flavors till we find the GPR one, then read the PC out of there.
4058     // FIXME: We will need to have a "RegisterContext data provider" class at some point that can get all the registers
4059     // out of data in this form & attach them to a given thread.  That should underlie the MacOS X User process plugin,
4060     // and we'll also need it for the MacOS X Core File process plugin.  When we have that we can also use it here.
4061     //
4062     // For now we hard-code the offsets and flavors we need:
4063     //
4064     //
4065 
4066     ModuleSP module_sp(GetModule());
4067     if (module_sp)
4068     {
4069         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4070         struct load_command load_cmd;
4071         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4072         uint32_t i;
4073         lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
4074         bool done = false;
4075 
4076         for (i=0; i<m_header.ncmds; ++i)
4077         {
4078             const lldb::offset_t cmd_offset = offset;
4079             if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
4080                 break;
4081 
4082             switch (load_cmd.cmd)
4083             {
4084             case LC_UNIXTHREAD:
4085             case LC_THREAD:
4086                 {
4087                     while (offset < cmd_offset + load_cmd.cmdsize)
4088                     {
4089                         uint32_t flavor = m_data.GetU32(&offset);
4090                         uint32_t count = m_data.GetU32(&offset);
4091                         if (count == 0)
4092                         {
4093                             // We've gotten off somehow, log and exit;
4094                             return m_entry_point_address;
4095                         }
4096 
4097                         switch (m_header.cputype)
4098                         {
4099                         case llvm::MachO::CPU_TYPE_ARM:
4100                            if (flavor == 1) // ARM_THREAD_STATE from mach/arm/thread_status.h
4101                            {
4102                                offset += 60;  // This is the offset of pc in the GPR thread state data structure.
4103                                start_address = m_data.GetU32(&offset);
4104                                done = true;
4105                             }
4106                         break;
4107                         case llvm::MachO::CPU_TYPE_I386:
4108                            if (flavor == 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
4109                            {
4110                                offset += 40;  // This is the offset of eip in the GPR thread state data structure.
4111                                start_address = m_data.GetU32(&offset);
4112                                done = true;
4113                             }
4114                         break;
4115                         case llvm::MachO::CPU_TYPE_X86_64:
4116                            if (flavor == 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
4117                            {
4118                                offset += 16 * 8;  // This is the offset of rip in the GPR thread state data structure.
4119                                start_address = m_data.GetU64(&offset);
4120                                done = true;
4121                             }
4122                         break;
4123                         default:
4124                             return m_entry_point_address;
4125                         }
4126                         // Haven't found the GPR flavor yet, skip over the data for this flavor:
4127                         if (done)
4128                             break;
4129                         offset += count * 4;
4130                     }
4131                 }
4132                 break;
4133             case LC_MAIN:
4134                 {
4135                     ConstString text_segment_name ("__TEXT");
4136                     uint64_t entryoffset = m_data.GetU64(&offset);
4137                     SectionSP text_segment_sp = GetSectionList()->FindSectionByName(text_segment_name);
4138                     if (text_segment_sp)
4139                     {
4140                         done = true;
4141                         start_address = text_segment_sp->GetFileAddress() + entryoffset;
4142                     }
4143                 }
4144 
4145             default:
4146                 break;
4147             }
4148             if (done)
4149                 break;
4150 
4151             // Go to the next load command:
4152             offset = cmd_offset + load_cmd.cmdsize;
4153         }
4154 
4155         if (start_address != LLDB_INVALID_ADDRESS)
4156         {
4157             // We got the start address from the load commands, so now resolve that address in the sections
4158             // of this ObjectFile:
4159             if (!m_entry_point_address.ResolveAddressUsingFileSections (start_address, GetSectionList()))
4160             {
4161                 m_entry_point_address.Clear();
4162             }
4163         }
4164         else
4165         {
4166             // We couldn't read the UnixThread load command - maybe it wasn't there.  As a fallback look for the
4167             // "start" symbol in the main executable.
4168 
4169             ModuleSP module_sp (GetModule());
4170 
4171             if (module_sp)
4172             {
4173                 SymbolContextList contexts;
4174                 SymbolContext context;
4175                 if (module_sp->FindSymbolsWithNameAndType(ConstString ("start"), eSymbolTypeCode, contexts))
4176                 {
4177                     if (contexts.GetContextAtIndex(0, context))
4178                         m_entry_point_address = context.symbol->GetAddress();
4179                 }
4180             }
4181         }
4182     }
4183 
4184     return m_entry_point_address;
4185 
4186 }
4187 
4188 lldb_private::Address
4189 ObjectFileMachO::GetHeaderAddress ()
4190 {
4191     lldb_private::Address header_addr;
4192     SectionList *section_list = GetSectionList();
4193     if (section_list)
4194     {
4195         SectionSP text_segment_sp (section_list->FindSectionByName (GetSegmentNameTEXT()));
4196         if (text_segment_sp)
4197         {
4198             header_addr.SetSection (text_segment_sp);
4199             header_addr.SetOffset (0);
4200         }
4201     }
4202     return header_addr;
4203 }
4204 
4205 uint32_t
4206 ObjectFileMachO::GetNumThreadContexts ()
4207 {
4208     ModuleSP module_sp(GetModule());
4209     if (module_sp)
4210     {
4211         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4212         if (!m_thread_context_offsets_valid)
4213         {
4214             m_thread_context_offsets_valid = true;
4215             lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4216             FileRangeArray::Entry file_range;
4217             thread_command thread_cmd;
4218             for (uint32_t i=0; i<m_header.ncmds; ++i)
4219             {
4220                 const uint32_t cmd_offset = offset;
4221                 if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL)
4222                     break;
4223 
4224                 if (thread_cmd.cmd == LC_THREAD)
4225                 {
4226                     file_range.SetRangeBase (offset);
4227                     file_range.SetByteSize (thread_cmd.cmdsize - 8);
4228                     m_thread_context_offsets.Append (file_range);
4229                 }
4230                 offset = cmd_offset + thread_cmd.cmdsize;
4231             }
4232         }
4233     }
4234     return m_thread_context_offsets.GetSize();
4235 }
4236 
4237 lldb::RegisterContextSP
4238 ObjectFileMachO::GetThreadContextAtIndex (uint32_t idx, lldb_private::Thread &thread)
4239 {
4240     lldb::RegisterContextSP reg_ctx_sp;
4241 
4242     ModuleSP module_sp(GetModule());
4243     if (module_sp)
4244     {
4245         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4246         if (!m_thread_context_offsets_valid)
4247             GetNumThreadContexts ();
4248 
4249         const FileRangeArray::Entry *thread_context_file_range = m_thread_context_offsets.GetEntryAtIndex (idx);
4250         if (thread_context_file_range)
4251         {
4252 
4253             DataExtractor data (m_data,
4254                                 thread_context_file_range->GetRangeBase(),
4255                                 thread_context_file_range->GetByteSize());
4256 
4257             switch (m_header.cputype)
4258             {
4259                 case llvm::MachO::CPU_TYPE_ARM:
4260                     reg_ctx_sp.reset (new RegisterContextDarwin_arm_Mach (thread, data));
4261                     break;
4262 
4263                 case llvm::MachO::CPU_TYPE_I386:
4264                     reg_ctx_sp.reset (new RegisterContextDarwin_i386_Mach (thread, data));
4265                     break;
4266 
4267                 case llvm::MachO::CPU_TYPE_X86_64:
4268                     reg_ctx_sp.reset (new RegisterContextDarwin_x86_64_Mach (thread, data));
4269                     break;
4270             }
4271         }
4272     }
4273     return reg_ctx_sp;
4274 }
4275 
4276 
4277 ObjectFile::Type
4278 ObjectFileMachO::CalculateType()
4279 {
4280     switch (m_header.filetype)
4281     {
4282         case MH_OBJECT:                                         // 0x1u
4283             if (GetAddressByteSize () == 4)
4284             {
4285                 // 32 bit kexts are just object files, but they do have a valid
4286                 // UUID load command.
4287                 UUID uuid;
4288                 if (GetUUID(&uuid))
4289                 {
4290                     // this checking for the UUID load command is not enough
4291                     // we could eventually look for the symbol named
4292                     // "OSKextGetCurrentIdentifier" as this is required of kexts
4293                     if (m_strata == eStrataInvalid)
4294                         m_strata = eStrataKernel;
4295                     return eTypeSharedLibrary;
4296                 }
4297             }
4298             return eTypeObjectFile;
4299 
4300         case MH_EXECUTE:            return eTypeExecutable;     // 0x2u
4301         case MH_FVMLIB:             return eTypeSharedLibrary;  // 0x3u
4302         case MH_CORE:               return eTypeCoreFile;       // 0x4u
4303         case MH_PRELOAD:            return eTypeSharedLibrary;  // 0x5u
4304         case MH_DYLIB:              return eTypeSharedLibrary;  // 0x6u
4305         case MH_DYLINKER:           return eTypeDynamicLinker;  // 0x7u
4306         case MH_BUNDLE:             return eTypeSharedLibrary;  // 0x8u
4307         case MH_DYLIB_STUB:         return eTypeStubLibrary;    // 0x9u
4308         case MH_DSYM:               return eTypeDebugInfo;      // 0xAu
4309         case MH_KEXT_BUNDLE:        return eTypeSharedLibrary;  // 0xBu
4310         default:
4311             break;
4312     }
4313     return eTypeUnknown;
4314 }
4315 
4316 ObjectFile::Strata
4317 ObjectFileMachO::CalculateStrata()
4318 {
4319     switch (m_header.filetype)
4320     {
4321         case MH_OBJECT:                                  // 0x1u
4322             {
4323                 // 32 bit kexts are just object files, but they do have a valid
4324                 // UUID load command.
4325                 UUID uuid;
4326                 if (GetUUID(&uuid))
4327                 {
4328                     // this checking for the UUID load command is not enough
4329                     // we could eventually look for the symbol named
4330                     // "OSKextGetCurrentIdentifier" as this is required of kexts
4331                     if (m_type == eTypeInvalid)
4332                         m_type = eTypeSharedLibrary;
4333 
4334                     return eStrataKernel;
4335                 }
4336             }
4337             return eStrataUnknown;
4338 
4339         case MH_EXECUTE:                                 // 0x2u
4340             // Check for the MH_DYLDLINK bit in the flags
4341             if (m_header.flags & MH_DYLDLINK)
4342             {
4343                 return eStrataUser;
4344             }
4345             else
4346             {
4347                 SectionList *section_list = GetSectionList();
4348                 if (section_list)
4349                 {
4350                     static ConstString g_kld_section_name ("__KLD");
4351                     if (section_list->FindSectionByName(g_kld_section_name))
4352                         return eStrataKernel;
4353                 }
4354             }
4355             return eStrataRawImage;
4356 
4357         case MH_FVMLIB:      return eStrataUser;         // 0x3u
4358         case MH_CORE:        return eStrataUnknown;      // 0x4u
4359         case MH_PRELOAD:     return eStrataRawImage;     // 0x5u
4360         case MH_DYLIB:       return eStrataUser;         // 0x6u
4361         case MH_DYLINKER:    return eStrataUser;         // 0x7u
4362         case MH_BUNDLE:      return eStrataUser;         // 0x8u
4363         case MH_DYLIB_STUB:  return eStrataUser;         // 0x9u
4364         case MH_DSYM:        return eStrataUnknown;      // 0xAu
4365         case MH_KEXT_BUNDLE: return eStrataKernel;       // 0xBu
4366         default:
4367             break;
4368     }
4369     return eStrataUnknown;
4370 }
4371 
4372 
4373 uint32_t
4374 ObjectFileMachO::GetVersion (uint32_t *versions, uint32_t num_versions)
4375 {
4376     ModuleSP module_sp(GetModule());
4377     if (module_sp)
4378     {
4379         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4380         struct dylib_command load_cmd;
4381         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4382         uint32_t version_cmd = 0;
4383         uint64_t version = 0;
4384         uint32_t i;
4385         for (i=0; i<m_header.ncmds; ++i)
4386         {
4387             const lldb::offset_t cmd_offset = offset;
4388             if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
4389                 break;
4390 
4391             if (load_cmd.cmd == LC_ID_DYLIB)
4392             {
4393                 if (version_cmd == 0)
4394                 {
4395                     version_cmd = load_cmd.cmd;
4396                     if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL)
4397                         break;
4398                     version = load_cmd.dylib.current_version;
4399                 }
4400                 break; // Break for now unless there is another more complete version
4401                        // number load command in the future.
4402             }
4403             offset = cmd_offset + load_cmd.cmdsize;
4404         }
4405 
4406         if (version_cmd == LC_ID_DYLIB)
4407         {
4408             if (versions != NULL && num_versions > 0)
4409             {
4410                 if (num_versions > 0)
4411                     versions[0] = (version & 0xFFFF0000ull) >> 16;
4412                 if (num_versions > 1)
4413                     versions[1] = (version & 0x0000FF00ull) >> 8;
4414                 if (num_versions > 2)
4415                     versions[2] = (version & 0x000000FFull);
4416                 // Fill in an remaining version numbers with invalid values
4417                 for (i=3; i<num_versions; ++i)
4418                     versions[i] = UINT32_MAX;
4419             }
4420             // The LC_ID_DYLIB load command has a version with 3 version numbers
4421             // in it, so always return 3
4422             return 3;
4423         }
4424     }
4425     return false;
4426 }
4427 
4428 bool
4429 ObjectFileMachO::GetArchitecture (ArchSpec &arch)
4430 {
4431     ModuleSP module_sp(GetModule());
4432     if (module_sp)
4433     {
4434         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4435         arch.SetArchitecture (eArchTypeMachO, m_header.cputype, m_header.cpusubtype);
4436 
4437         // Files with type MH_PRELOAD are currently used in cases where the image
4438         // debugs at the addresses in the file itself. Below we set the OS to
4439         // unknown to make sure we use the DynamicLoaderStatic()...
4440         if (m_header.filetype == MH_PRELOAD)
4441         {
4442             arch.GetTriple().setOS (llvm::Triple::UnknownOS);
4443         }
4444         return true;
4445     }
4446     return false;
4447 }
4448 
4449 
4450 UUID
4451 ObjectFileMachO::GetProcessSharedCacheUUID (Process *process)
4452 {
4453     UUID uuid;
4454     if (process)
4455     {
4456         addr_t all_image_infos = process->GetImageInfoAddress();
4457 
4458         // The address returned by GetImageInfoAddress may be the address of dyld (don't want)
4459         // or it may be the address of the dyld_all_image_infos structure (want).  The first four
4460         // bytes will be either the version field (all_image_infos) or a Mach-O file magic constant.
4461         // Version 13 and higher of dyld_all_image_infos is required to get the sharedCacheUUID field.
4462 
4463         Error err;
4464         uint32_t version_or_magic = process->ReadUnsignedIntegerFromMemory (all_image_infos, 4, -1, err);
4465         if (version_or_magic != -1
4466             && version_or_magic != MH_MAGIC
4467             && version_or_magic != MH_CIGAM
4468             && version_or_magic != MH_MAGIC_64
4469             && version_or_magic != MH_CIGAM_64
4470             && version_or_magic >= 13)
4471         {
4472             addr_t sharedCacheUUID_address = LLDB_INVALID_ADDRESS;
4473             int wordsize = process->GetAddressByteSize();
4474             if (wordsize == 8)
4475             {
4476                 sharedCacheUUID_address = all_image_infos + 160;  // sharedCacheUUID <mach-o/dyld_images.h>
4477             }
4478             if (wordsize == 4)
4479             {
4480                 sharedCacheUUID_address = all_image_infos + 84;   // sharedCacheUUID <mach-o/dyld_images.h>
4481             }
4482             if (sharedCacheUUID_address != LLDB_INVALID_ADDRESS)
4483             {
4484                 uuid_t shared_cache_uuid;
4485                 if (process->ReadMemory (sharedCacheUUID_address, shared_cache_uuid, sizeof (uuid_t), err) == sizeof (uuid_t))
4486                 {
4487                     uuid.SetBytes (shared_cache_uuid);
4488                 }
4489             }
4490         }
4491     }
4492     return uuid;
4493 }
4494 
4495 UUID
4496 ObjectFileMachO::GetLLDBSharedCacheUUID ()
4497 {
4498     UUID uuid;
4499 #if defined (__APPLE__) && defined (__arm__)
4500     uint8_t *(*dyld_get_all_image_infos)(void);
4501     dyld_get_all_image_infos = (uint8_t*(*)()) dlsym (RTLD_DEFAULT, "_dyld_get_all_image_infos");
4502     if (dyld_get_all_image_infos)
4503     {
4504         uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
4505         if (dyld_all_image_infos_address)
4506         {
4507             uint32_t *version = (uint32_t*) dyld_all_image_infos_address;              // version <mach-o/dyld_images.h>
4508             if (*version >= 13)
4509             {
4510                 uuid_t *sharedCacheUUID_address = (uuid_t*) ((uint8_t*) dyld_all_image_infos_address + 84);  // sharedCacheUUID <mach-o/dyld_images.h>
4511                 uuid.SetBytes (sharedCacheUUID_address);
4512             }
4513         }
4514     }
4515 #endif
4516     return uuid;
4517 }
4518 
4519 uint32_t
4520 ObjectFileMachO::GetMinimumOSVersion (uint32_t *versions, uint32_t num_versions)
4521 {
4522     if (m_min_os_versions.empty())
4523     {
4524         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4525         bool success = false;
4526         for (uint32_t i=0; success == false && i < m_header.ncmds; ++i)
4527         {
4528             const lldb::offset_t load_cmd_offset = offset;
4529 
4530             version_min_command lc;
4531             if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
4532                 break;
4533             if (lc.cmd == LC_VERSION_MIN_MACOSX || lc.cmd == LC_VERSION_MIN_IPHONEOS)
4534             {
4535                 if (m_data.GetU32 (&offset, &lc.version, (sizeof(lc) / sizeof(uint32_t)) - 2))
4536                 {
4537                     const uint32_t xxxx = lc.version >> 16;
4538                     const uint32_t yy = (lc.version >> 8) & 0xffu;
4539                     const uint32_t zz = lc.version  & 0xffu;
4540                     if (xxxx)
4541                     {
4542                         m_min_os_versions.push_back(xxxx);
4543                         if (yy)
4544                         {
4545                             m_min_os_versions.push_back(yy);
4546                             if (zz)
4547                                 m_min_os_versions.push_back(zz);
4548                         }
4549                     }
4550                     success = true;
4551                 }
4552             }
4553             offset = load_cmd_offset + lc.cmdsize;
4554         }
4555 
4556         if (success == false)
4557         {
4558             // Push an invalid value so we don't keep trying to
4559             m_min_os_versions.push_back(UINT32_MAX);
4560         }
4561     }
4562 
4563     if (m_min_os_versions.size() > 1 || m_min_os_versions[0] != UINT32_MAX)
4564     {
4565         if (versions != NULL && num_versions > 0)
4566         {
4567             for (size_t i=0; i<num_versions; ++i)
4568             {
4569                 if (i < m_min_os_versions.size())
4570                     versions[i] = m_min_os_versions[i];
4571                 else
4572                     versions[i] = 0;
4573             }
4574         }
4575         return m_min_os_versions.size();
4576     }
4577     // Call the superclasses version that will empty out the data
4578     return ObjectFile::GetMinimumOSVersion (versions, num_versions);
4579 }
4580 
4581 uint32_t
4582 ObjectFileMachO::GetSDKVersion(uint32_t *versions, uint32_t num_versions)
4583 {
4584     if (m_sdk_versions.empty())
4585     {
4586         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4587         bool success = false;
4588         for (uint32_t i=0; success == false && i < m_header.ncmds; ++i)
4589         {
4590             const lldb::offset_t load_cmd_offset = offset;
4591 
4592             version_min_command lc;
4593             if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
4594                 break;
4595             if (lc.cmd == LC_VERSION_MIN_MACOSX || lc.cmd == LC_VERSION_MIN_IPHONEOS)
4596             {
4597                 if (m_data.GetU32 (&offset, &lc.version, (sizeof(lc) / sizeof(uint32_t)) - 2))
4598                 {
4599                     const uint32_t xxxx = lc.reserved >> 16;
4600                     const uint32_t yy = (lc.reserved >> 8) & 0xffu;
4601                     const uint32_t zz = lc.reserved  & 0xffu;
4602                     if (xxxx)
4603                     {
4604                         m_sdk_versions.push_back(xxxx);
4605                         if (yy)
4606                         {
4607                             m_sdk_versions.push_back(yy);
4608                             if (zz)
4609                                 m_sdk_versions.push_back(zz);
4610                         }
4611                     }
4612                     success = true;
4613                 }
4614             }
4615             offset = load_cmd_offset + lc.cmdsize;
4616         }
4617 
4618         if (success == false)
4619         {
4620             // Push an invalid value so we don't keep trying to
4621             m_sdk_versions.push_back(UINT32_MAX);
4622         }
4623     }
4624 
4625     if (m_sdk_versions.size() > 1 || m_sdk_versions[0] != UINT32_MAX)
4626     {
4627         if (versions != NULL && num_versions > 0)
4628         {
4629             for (size_t i=0; i<num_versions; ++i)
4630             {
4631                 if (i < m_sdk_versions.size())
4632                     versions[i] = m_sdk_versions[i];
4633                 else
4634                     versions[i] = 0;
4635             }
4636         }
4637         return m_sdk_versions.size();
4638     }
4639     // Call the superclasses version that will empty out the data
4640     return ObjectFile::GetSDKVersion (versions, num_versions);
4641 }
4642 
4643 
4644 //------------------------------------------------------------------
4645 // PluginInterface protocol
4646 //------------------------------------------------------------------
4647 lldb_private::ConstString
4648 ObjectFileMachO::GetPluginName()
4649 {
4650     return GetPluginNameStatic();
4651 }
4652 
4653 uint32_t
4654 ObjectFileMachO::GetPluginVersion()
4655 {
4656     return 1;
4657 }
4658 
4659