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