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