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