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                     if (lc.cmd == LC_REEXPORT_DYLIB)
1843                     {
1844                         m_reexported_dylibs.AppendIfUnique(file_spec);
1845                     }
1846 
1847                     dylib_files.Append(file_spec);
1848                 }
1849             }
1850             break;
1851 
1852         case LC_FUNCTION_STARTS:
1853             function_starts_load_command.cmd = lc.cmd;
1854             function_starts_load_command.cmdsize = lc.cmdsize;
1855             if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) == NULL) // fill in symoff, nsyms, stroff, strsize fields
1856                 memset (&function_starts_load_command, 0, sizeof(function_starts_load_command));
1857             break;
1858 
1859         default:
1860             break;
1861         }
1862         offset = cmd_offset + lc.cmdsize;
1863     }
1864 
1865     if (symtab_load_command.cmd)
1866     {
1867         Symtab *symtab = m_symtab_ap.get();
1868         SectionList *section_list = GetSectionList();
1869         if (section_list == NULL)
1870             return 0;
1871 
1872         const uint32_t addr_byte_size = m_data.GetAddressByteSize();
1873         const ByteOrder byte_order = m_data.GetByteOrder();
1874         bool bit_width_32 = addr_byte_size == 4;
1875         const size_t nlist_byte_size = bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
1876 
1877         DataExtractor nlist_data (NULL, 0, byte_order, addr_byte_size);
1878         DataExtractor strtab_data (NULL, 0, byte_order, addr_byte_size);
1879         DataExtractor function_starts_data (NULL, 0, byte_order, addr_byte_size);
1880         DataExtractor indirect_symbol_index_data (NULL, 0, byte_order, addr_byte_size);
1881         DataExtractor dyld_trie_data (NULL, 0, byte_order, addr_byte_size);
1882 
1883         const addr_t nlist_data_byte_size = symtab_load_command.nsyms * nlist_byte_size;
1884         const addr_t strtab_data_byte_size = symtab_load_command.strsize;
1885         addr_t strtab_addr = LLDB_INVALID_ADDRESS;
1886 
1887         ProcessSP process_sp (m_process_wp.lock());
1888         Process *process = process_sp.get();
1889 
1890         uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
1891 
1892         if (process)
1893         {
1894             Target &target = process->GetTarget();
1895 
1896             memory_module_load_level = target.GetMemoryModuleLoadLevel();
1897 
1898             SectionSP linkedit_section_sp(section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
1899             // Reading mach file from memory in a process or core file...
1900 
1901             if (linkedit_section_sp)
1902             {
1903                 const addr_t linkedit_load_addr = linkedit_section_sp->GetLoadBaseAddress(&target);
1904                 const addr_t linkedit_file_offset = linkedit_section_sp->GetFileOffset();
1905                 const addr_t symoff_addr = linkedit_load_addr + symtab_load_command.symoff - linkedit_file_offset;
1906                 strtab_addr = linkedit_load_addr + symtab_load_command.stroff - linkedit_file_offset;
1907 
1908                 bool data_was_read = false;
1909 
1910 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__))
1911                 if (m_header.flags & 0x80000000u && process->GetAddressByteSize() == sizeof (void*))
1912                 {
1913                     // This mach-o memory file is in the dyld shared cache. If this
1914                     // program is not remote and this is iOS, then this process will
1915                     // share the same shared cache as the process we are debugging and
1916                     // we can read the entire __LINKEDIT from the address space in this
1917                     // process. This is a needed optimization that is used for local iOS
1918                     // debugging only since all shared libraries in the shared cache do
1919                     // not have corresponding files that exist in the file system of the
1920                     // device. They have been combined into a single file. This means we
1921                     // always have to load these files from memory. All of the symbol and
1922                     // string tables from all of the __LINKEDIT sections from the shared
1923                     // libraries in the shared cache have been merged into a single large
1924                     // symbol and string table. Reading all of this symbol and string table
1925                     // data across can slow down debug launch times, so we optimize this by
1926                     // reading the memory for the __LINKEDIT section from this process.
1927 
1928                     UUID lldb_shared_cache(GetLLDBSharedCacheUUID());
1929                     UUID process_shared_cache(GetProcessSharedCacheUUID(process));
1930                     bool use_lldb_cache = true;
1931                     if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() && lldb_shared_cache != process_shared_cache)
1932                     {
1933                             use_lldb_cache = false;
1934                             ModuleSP module_sp (GetModule());
1935                             if (module_sp)
1936                                 module_sp->ReportWarning ("shared cache in process does not match lldb's own shared cache, startup will be slow.");
1937 
1938                     }
1939 
1940                     PlatformSP platform_sp (target.GetPlatform());
1941                     if (platform_sp && platform_sp->IsHost() && use_lldb_cache)
1942                     {
1943                         data_was_read = true;
1944                         nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size, eByteOrderLittle);
1945                         strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size, eByteOrderLittle);
1946                         if (function_starts_load_command.cmd)
1947                         {
1948                             const addr_t func_start_addr = linkedit_load_addr + function_starts_load_command.dataoff - linkedit_file_offset;
1949                             function_starts_data.SetData ((void *)func_start_addr, function_starts_load_command.datasize, eByteOrderLittle);
1950                         }
1951                     }
1952                 }
1953 #endif
1954 
1955                 if (!data_was_read)
1956                 {
1957                     if (memory_module_load_level == eMemoryModuleLoadLevelComplete)
1958                     {
1959                         DataBufferSP nlist_data_sp (ReadMemory (process_sp, symoff_addr, nlist_data_byte_size));
1960                         if (nlist_data_sp)
1961                             nlist_data.SetData (nlist_data_sp, 0, nlist_data_sp->GetByteSize());
1962                         // Load strings individually from memory when loading from memory since shared cache
1963                         // string tables contain strings for all symbols from all shared cached libraries
1964                         //DataBufferSP strtab_data_sp (ReadMemory (process_sp, strtab_addr, strtab_data_byte_size));
1965                         //if (strtab_data_sp)
1966                         //    strtab_data.SetData (strtab_data_sp, 0, strtab_data_sp->GetByteSize());
1967                         if (m_dysymtab.nindirectsyms != 0)
1968                         {
1969                             const addr_t indirect_syms_addr = linkedit_load_addr + m_dysymtab.indirectsymoff - linkedit_file_offset;
1970                             DataBufferSP indirect_syms_data_sp (ReadMemory (process_sp, indirect_syms_addr, m_dysymtab.nindirectsyms * 4));
1971                             if (indirect_syms_data_sp)
1972                                 indirect_symbol_index_data.SetData (indirect_syms_data_sp, 0, indirect_syms_data_sp->GetByteSize());
1973                         }
1974                     }
1975 
1976                     if (memory_module_load_level >= eMemoryModuleLoadLevelPartial)
1977                     {
1978                         if (function_starts_load_command.cmd)
1979                         {
1980                             const addr_t func_start_addr = linkedit_load_addr + function_starts_load_command.dataoff - linkedit_file_offset;
1981                             DataBufferSP func_start_data_sp (ReadMemory (process_sp, func_start_addr, function_starts_load_command.datasize));
1982                             if (func_start_data_sp)
1983                                 function_starts_data.SetData (func_start_data_sp, 0, func_start_data_sp->GetByteSize());
1984                         }
1985                     }
1986                 }
1987             }
1988         }
1989         else
1990         {
1991             nlist_data.SetData (m_data,
1992                                 symtab_load_command.symoff,
1993                                 nlist_data_byte_size);
1994             strtab_data.SetData (m_data,
1995                                  symtab_load_command.stroff,
1996                                  strtab_data_byte_size);
1997 
1998             if (dyld_info.export_size > 0)
1999             {
2000                 dyld_trie_data.SetData (m_data,
2001                                         dyld_info.export_off,
2002                                         dyld_info.export_size);
2003             }
2004 
2005             if (m_dysymtab.nindirectsyms != 0)
2006             {
2007                 indirect_symbol_index_data.SetData (m_data,
2008                                                     m_dysymtab.indirectsymoff,
2009                                                     m_dysymtab.nindirectsyms * 4);
2010             }
2011             if (function_starts_load_command.cmd)
2012             {
2013                 function_starts_data.SetData (m_data,
2014                                               function_starts_load_command.dataoff,
2015                                               function_starts_load_command.datasize);
2016             }
2017         }
2018 
2019         if (nlist_data.GetByteSize() == 0 && memory_module_load_level == eMemoryModuleLoadLevelComplete)
2020         {
2021             if (log)
2022                 module_sp->LogMessage(log, "failed to read nlist data");
2023             return 0;
2024         }
2025 
2026 
2027         const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2028         if (!have_strtab_data)
2029         {
2030             if (process)
2031             {
2032                 if (strtab_addr == LLDB_INVALID_ADDRESS)
2033                 {
2034                     if (log)
2035                         module_sp->LogMessage(log, "failed to locate the strtab in memory");
2036                     return 0;
2037                 }
2038             }
2039             else
2040             {
2041                 if (log)
2042                     module_sp->LogMessage(log, "failed to read strtab data");
2043                 return 0;
2044             }
2045         }
2046 
2047         const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT();
2048         const ConstString &g_segment_name_DATA = GetSegmentNameDATA();
2049         const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC();
2050         const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame();
2051         SectionSP text_section_sp(section_list->FindSectionByName(g_segment_name_TEXT));
2052         SectionSP data_section_sp(section_list->FindSectionByName(g_segment_name_DATA));
2053         SectionSP objc_section_sp(section_list->FindSectionByName(g_segment_name_OBJC));
2054         SectionSP eh_frame_section_sp;
2055         if (text_section_sp.get())
2056             eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName (g_section_name_eh_frame);
2057         else
2058             eh_frame_section_sp = section_list->FindSectionByName (g_section_name_eh_frame);
2059 
2060         const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
2061 
2062         // lldb works best if it knows the start addresss of all functions in a module.
2063         // Linker symbols or debug info are normally the best source of information for start addr / size but
2064         // they may be stripped in a released binary.
2065         // Two additional sources of information exist in Mach-O binaries:
2066         //    LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each function's start address in the
2067         //                         binary, relative to the text section.
2068         //    eh_frame           - the eh_frame FDEs have the start addr & size of each function
2069         //  LC_FUNCTION_STARTS is the fastest source to read in, and is present on all modern binaries.
2070         //  Binaries built to run on older releases may need to use eh_frame information.
2071 
2072         if (text_section_sp && function_starts_data.GetByteSize())
2073         {
2074             FunctionStarts::Entry function_start_entry;
2075             function_start_entry.data = false;
2076             lldb::offset_t function_start_offset = 0;
2077             function_start_entry.addr = text_section_sp->GetFileAddress();
2078             uint64_t delta;
2079             while ((delta = function_starts_data.GetULEB128(&function_start_offset)) > 0)
2080             {
2081                 // Now append the current entry
2082                 function_start_entry.addr += delta;
2083                 function_starts.Append(function_start_entry);
2084             }
2085         }
2086         else
2087         {
2088             // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the load command claiming an eh_frame
2089             // but it doesn't actually have the eh_frame content.  And if we have a dSYM, we don't need to do any
2090             // of this fill-in-the-missing-symbols works anyway - the debug info should give us all the functions in
2091             // the module.
2092             if (text_section_sp.get() && eh_frame_section_sp.get() && m_type != eTypeDebugInfo)
2093             {
2094                 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp, eRegisterKindGCC, true);
2095                 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions;
2096                 eh_frame.GetFunctionAddressAndSizeVector (functions);
2097                 addr_t text_base_addr = text_section_sp->GetFileAddress();
2098                 size_t count = functions.GetSize();
2099                 for (size_t i = 0; i < count; ++i)
2100                 {
2101                     const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func = functions.GetEntryAtIndex (i);
2102                     if (func)
2103                     {
2104                         FunctionStarts::Entry function_start_entry;
2105                         function_start_entry.addr = func->base - text_base_addr;
2106                         function_starts.Append(function_start_entry);
2107                     }
2108                 }
2109             }
2110         }
2111 
2112         const size_t function_starts_count = function_starts.GetSize();
2113 
2114         const user_id_t TEXT_eh_frame_sectID = eh_frame_section_sp.get() ? eh_frame_section_sp->GetID() : NO_SECT;
2115 
2116         lldb::offset_t nlist_data_offset = 0;
2117 
2118         uint32_t N_SO_index = UINT32_MAX;
2119 
2120         MachSymtabSectionInfo section_info (section_list);
2121         std::vector<uint32_t> N_FUN_indexes;
2122         std::vector<uint32_t> N_NSYM_indexes;
2123         std::vector<uint32_t> N_INCL_indexes;
2124         std::vector<uint32_t> N_BRAC_indexes;
2125         std::vector<uint32_t> N_COMM_indexes;
2126         typedef std::multimap <uint64_t, uint32_t> ValueToSymbolIndexMap;
2127         typedef std::map <uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2128         typedef std::map <const char *, uint32_t> ConstNameToSymbolIndexMap;
2129         ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2130         ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2131         ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
2132         // Any symbols that get merged into another will get an entry
2133         // in this map so we know
2134         NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2135         uint32_t nlist_idx = 0;
2136         Symbol *symbol_ptr = NULL;
2137 
2138         uint32_t sym_idx = 0;
2139         Symbol *sym = NULL;
2140         size_t num_syms = 0;
2141         std::string memory_symbol_name;
2142         uint32_t unmapped_local_symbols_found = 0;
2143 
2144         std::vector<TrieEntryWithOffset> trie_entries;
2145         std::set<lldb::addr_t> resolver_addresses;
2146 
2147         if (dyld_trie_data.GetByteSize() > 0)
2148         {
2149             std::vector<llvm::StringRef> nameSlices;
2150             ParseTrieEntries (dyld_trie_data,
2151                               0,
2152                               nameSlices,
2153                               resolver_addresses,
2154                               trie_entries);
2155 
2156             ConstString text_segment_name ("__TEXT");
2157             SectionSP text_segment_sp = GetSectionList()->FindSectionByName(text_segment_name);
2158             if (text_segment_sp)
2159             {
2160                 const lldb::addr_t text_segment_file_addr = text_segment_sp->GetFileAddress();
2161                 if (text_segment_file_addr != LLDB_INVALID_ADDRESS)
2162                 {
2163                     for (auto &e : trie_entries)
2164                         e.entry.address += text_segment_file_addr;
2165                 }
2166             }
2167         }
2168 
2169 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__))
2170 
2171         // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been optimized by moving LOCAL
2172         // symbols out of the memory mapped portion of the DSC. The symbol information has all been retained,
2173         // but it isn't available in the normal nlist data. However, there *are* duplicate entries of *some*
2174         // LOCAL symbols in the normal nlist data. To handle this situation correctly, we must first attempt
2175         // to parse any DSC unmapped symbol information. If we find any, we set a flag that tells the normal
2176         // nlist parser to ignore all LOCAL symbols.
2177 
2178         if (m_header.flags & 0x80000000u)
2179         {
2180             // Before we can start mapping the DSC, we need to make certain the target process is actually
2181             // using the cache we can find.
2182 
2183             // Next we need to determine the correct path for the dyld shared cache.
2184 
2185             ArchSpec header_arch(eArchTypeMachO, m_header.cputype, m_header.cpusubtype);
2186             char dsc_path[PATH_MAX];
2187 
2188             snprintf(dsc_path, sizeof(dsc_path), "%s%s%s",
2189                      "/System/Library/Caches/com.apple.dyld/",  /* IPHONE_DYLD_SHARED_CACHE_DIR */
2190                      "dyld_shared_cache_",          /* DYLD_SHARED_CACHE_BASE_NAME */
2191                      header_arch.GetArchitectureName());
2192 
2193             FileSpec dsc_filespec(dsc_path, false);
2194 
2195             // We need definitions of two structures in the on-disk DSC, copy them here manually
2196             struct lldb_copy_dyld_cache_header_v0
2197             {
2198                 char        magic[16];            // e.g. "dyld_v0    i386", "dyld_v1   armv7", etc.
2199                 uint32_t    mappingOffset;        // file offset to first dyld_cache_mapping_info
2200                 uint32_t    mappingCount;         // number of dyld_cache_mapping_info entries
2201                 uint32_t    imagesOffset;
2202                 uint32_t    imagesCount;
2203                 uint64_t    dyldBaseAddress;
2204                 uint64_t    codeSignatureOffset;
2205                 uint64_t    codeSignatureSize;
2206                 uint64_t    slideInfoOffset;
2207                 uint64_t    slideInfoSize;
2208                 uint64_t    localSymbolsOffset;   // file offset of where local symbols are stored
2209                 uint64_t    localSymbolsSize;     // size of local symbols information
2210             };
2211             struct lldb_copy_dyld_cache_header_v1
2212             {
2213                 char        magic[16];            // e.g. "dyld_v0    i386", "dyld_v1   armv7", etc.
2214                 uint32_t    mappingOffset;        // file offset to first dyld_cache_mapping_info
2215                 uint32_t    mappingCount;         // number of dyld_cache_mapping_info entries
2216                 uint32_t    imagesOffset;
2217                 uint32_t    imagesCount;
2218                 uint64_t    dyldBaseAddress;
2219                 uint64_t    codeSignatureOffset;
2220                 uint64_t    codeSignatureSize;
2221                 uint64_t    slideInfoOffset;
2222                 uint64_t    slideInfoSize;
2223                 uint64_t    localSymbolsOffset;
2224                 uint64_t    localSymbolsSize;
2225                 uint8_t     uuid[16];             // v1 and above, also recorded in dyld_all_image_infos v13 and later
2226             };
2227 
2228             struct lldb_copy_dyld_cache_mapping_info
2229             {
2230                 uint64_t        address;
2231                 uint64_t        size;
2232                 uint64_t        fileOffset;
2233                 uint32_t        maxProt;
2234                 uint32_t        initProt;
2235             };
2236 
2237             struct lldb_copy_dyld_cache_local_symbols_info
2238             {
2239                 uint32_t        nlistOffset;
2240                 uint32_t        nlistCount;
2241                 uint32_t        stringsOffset;
2242                 uint32_t        stringsSize;
2243                 uint32_t        entriesOffset;
2244                 uint32_t        entriesCount;
2245             };
2246             struct lldb_copy_dyld_cache_local_symbols_entry
2247             {
2248                 uint32_t        dylibOffset;
2249                 uint32_t        nlistStartIndex;
2250                 uint32_t        nlistCount;
2251             };
2252 
2253             /* The dyld_cache_header has a pointer to the dyld_cache_local_symbols_info structure (localSymbolsOffset).
2254                The dyld_cache_local_symbols_info structure gives us three things:
2255                  1. The start and count of the nlist records in the dyld_shared_cache file
2256                  2. The start and size of the strings for these nlist records
2257                  3. The start and count of dyld_cache_local_symbols_entry entries
2258 
2259                There is one dyld_cache_local_symbols_entry per dylib/framework in the dyld shared cache.
2260                The "dylibOffset" field is the Mach-O header of this dylib/framework in the dyld shared cache.
2261                The dyld_cache_local_symbols_entry also lists the start of this dylib/framework's nlist records
2262                and the count of how many nlist records there are for this dylib/framework.
2263             */
2264 
2265             // Process the dsc header to find the unmapped symbols
2266             //
2267             // Save some VM space, do not map the entire cache in one shot.
2268 
2269             DataBufferSP dsc_data_sp;
2270             dsc_data_sp = dsc_filespec.MemoryMapFileContents(0, sizeof(struct lldb_copy_dyld_cache_header_v1));
2271 
2272             if (dsc_data_sp)
2273             {
2274                 DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size);
2275 
2276                 char version_str[17];
2277                 int version = -1;
2278                 lldb::offset_t offset = 0;
2279                 memcpy (version_str, dsc_header_data.GetData (&offset, 16), 16);
2280                 version_str[16] = '\0';
2281                 if (strncmp (version_str, "dyld_v", 6) == 0 && isdigit (version_str[6]))
2282                 {
2283                     int v;
2284                     if (::sscanf (version_str + 6, "%d", &v) == 1)
2285                     {
2286                         version = v;
2287                     }
2288                 }
2289 
2290                 UUID dsc_uuid;
2291                 if (version >= 1)
2292                 {
2293                     offset = offsetof (struct lldb_copy_dyld_cache_header_v1, uuid);
2294                     uint8_t uuid_bytes[sizeof (uuid_t)];
2295                     memcpy (uuid_bytes, dsc_header_data.GetData (&offset, sizeof (uuid_t)), sizeof (uuid_t));
2296                     dsc_uuid.SetBytes (uuid_bytes);
2297                 }
2298 
2299                 bool uuid_match = true;
2300                 if (dsc_uuid.IsValid() && process)
2301                 {
2302                     UUID shared_cache_uuid(GetProcessSharedCacheUUID(process));
2303 
2304                     if (shared_cache_uuid.IsValid() && dsc_uuid != shared_cache_uuid)
2305                     {
2306                         // The on-disk dyld_shared_cache file is not the same as the one in this
2307                         // process' memory, don't use it.
2308                         uuid_match = false;
2309                         ModuleSP module_sp (GetModule());
2310                         if (module_sp)
2311                             module_sp->ReportWarning ("process shared cache does not match on-disk dyld_shared_cache file, some symbol names will be missing.");
2312                     }
2313                 }
2314 
2315                 offset = offsetof (struct lldb_copy_dyld_cache_header_v1, mappingOffset);
2316 
2317                 uint32_t mappingOffset = dsc_header_data.GetU32(&offset);
2318 
2319                 // If the mappingOffset points to a location inside the header, we've
2320                 // opened an old dyld shared cache, and should not proceed further.
2321                 if (uuid_match && mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v0))
2322                 {
2323 
2324                     DataBufferSP dsc_mapping_info_data_sp = dsc_filespec.MemoryMapFileContents(mappingOffset, sizeof (struct lldb_copy_dyld_cache_mapping_info));
2325                     DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp, byte_order, addr_byte_size);
2326                     offset = 0;
2327 
2328                     // The File addresses (from the in-memory Mach-O load commands) for the shared libraries
2329                     // in the shared library cache need to be adjusted by an offset to match up with the
2330                     // dylibOffset identifying field in the dyld_cache_local_symbol_entry's.  This offset is
2331                     // recorded in mapping_offset_value.
2332                     const uint64_t mapping_offset_value = dsc_mapping_info_data.GetU64(&offset);
2333 
2334                     offset = offsetof (struct lldb_copy_dyld_cache_header_v1, localSymbolsOffset);
2335                     uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset);
2336                     uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset);
2337 
2338                     if (localSymbolsOffset && localSymbolsSize)
2339                     {
2340                         // Map the local symbols
2341                         if (DataBufferSP dsc_local_symbols_data_sp = dsc_filespec.MemoryMapFileContents(localSymbolsOffset, localSymbolsSize))
2342                         {
2343                             DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp, byte_order, addr_byte_size);
2344 
2345                             offset = 0;
2346 
2347                             // Read the local_symbols_infos struct in one shot
2348                             struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info;
2349                             dsc_local_symbols_data.GetU32(&offset, &local_symbols_info.nlistOffset, 6);
2350 
2351                             SectionSP text_section_sp(section_list->FindSectionByName(GetSegmentNameTEXT()));
2352 
2353                             uint32_t header_file_offset = (text_section_sp->GetFileAddress() - mapping_offset_value);
2354 
2355                             offset = local_symbols_info.entriesOffset;
2356                             for (uint32_t entry_index = 0; entry_index < local_symbols_info.entriesCount; entry_index++)
2357                             {
2358                                 struct lldb_copy_dyld_cache_local_symbols_entry local_symbols_entry;
2359                                 local_symbols_entry.dylibOffset = dsc_local_symbols_data.GetU32(&offset);
2360                                 local_symbols_entry.nlistStartIndex = dsc_local_symbols_data.GetU32(&offset);
2361                                 local_symbols_entry.nlistCount = dsc_local_symbols_data.GetU32(&offset);
2362 
2363                                 if (header_file_offset == local_symbols_entry.dylibOffset)
2364                                 {
2365                                     unmapped_local_symbols_found = local_symbols_entry.nlistCount;
2366 
2367                                     // The normal nlist code cannot correctly size the Symbols array, we need to allocate it here.
2368                                     sym = symtab->Resize (symtab_load_command.nsyms + m_dysymtab.nindirectsyms + unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2369                                     num_syms = symtab->GetNumSymbols();
2370 
2371                                     nlist_data_offset = local_symbols_info.nlistOffset + (nlist_byte_size * local_symbols_entry.nlistStartIndex);
2372                                     uint32_t string_table_offset = local_symbols_info.stringsOffset;
2373 
2374                                     for (uint32_t nlist_index = 0; nlist_index < local_symbols_entry.nlistCount; nlist_index++)
2375                                     {
2376                                         /////////////////////////////
2377                                         {
2378                                             struct nlist_64 nlist;
2379                                             if (!dsc_local_symbols_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size))
2380                                                 break;
2381 
2382                                             nlist.n_strx  = dsc_local_symbols_data.GetU32_unchecked(&nlist_data_offset);
2383                                             nlist.n_type  = dsc_local_symbols_data.GetU8_unchecked (&nlist_data_offset);
2384                                             nlist.n_sect  = dsc_local_symbols_data.GetU8_unchecked (&nlist_data_offset);
2385                                             nlist.n_desc  = dsc_local_symbols_data.GetU16_unchecked (&nlist_data_offset);
2386                                             nlist.n_value = dsc_local_symbols_data.GetAddress_unchecked (&nlist_data_offset);
2387 
2388                                             SymbolType type = eSymbolTypeInvalid;
2389                                             const char *symbol_name = dsc_local_symbols_data.PeekCStr(string_table_offset + nlist.n_strx);
2390 
2391                                             if (symbol_name == NULL)
2392                                             {
2393                                                 // No symbol should be NULL, even the symbols with no
2394                                                 // string values should have an offset zero which points
2395                                                 // to an empty C-string
2396                                                 Host::SystemLog (Host::eSystemLogError,
2397                                                                  "error: DSC unmapped local symbol[%u] has invalid string table offset 0x%x in %s, ignoring symbol\n",
2398                                                                  entry_index,
2399                                                                  nlist.n_strx,
2400                                                                  module_sp->GetFileSpec().GetPath().c_str());
2401                                                 continue;
2402                                             }
2403                                             if (symbol_name[0] == '\0')
2404                                                 symbol_name = NULL;
2405 
2406                                             const char *symbol_name_non_abi_mangled = NULL;
2407 
2408                                             SectionSP symbol_section;
2409                                             uint32_t symbol_byte_size = 0;
2410                                             bool add_nlist = true;
2411                                             bool is_debug = ((nlist.n_type & N_STAB) != 0);
2412                                             bool demangled_is_synthesized = false;
2413                                             bool is_gsym = false;
2414 
2415                                             assert (sym_idx < num_syms);
2416 
2417                                             sym[sym_idx].SetDebug (is_debug);
2418 
2419                                             if (is_debug)
2420                                             {
2421                                                 switch (nlist.n_type)
2422                                                 {
2423                                                     case N_GSYM:
2424                                                         // global symbol: name,,NO_SECT,type,0
2425                                                         // Sometimes the N_GSYM value contains the address.
2426 
2427                                                         // FIXME: In the .o files, we have a GSYM and a debug symbol for all the ObjC data.  They
2428                                                         // have the same address, but we want to ensure that we always find only the real symbol,
2429                                                         // 'cause we don't currently correctly attribute the GSYM one to the ObjCClass/Ivar/MetaClass
2430                                                         // symbol type.  This is a temporary hack to make sure the ObjectiveC symbols get treated
2431                                                         // correctly.  To do this right, we should coalesce all the GSYM & global symbols that have the
2432                                                         // same address.
2433 
2434                                                         if (symbol_name && symbol_name[0] == '_' && symbol_name[1] ==  'O'
2435                                                             && (strncmp (symbol_name, "_OBJC_IVAR_$_", strlen ("_OBJC_IVAR_$_")) == 0
2436                                                                 || strncmp (symbol_name, "_OBJC_CLASS_$_", strlen ("_OBJC_CLASS_$_")) == 0
2437                                                                 || strncmp (symbol_name, "_OBJC_METACLASS_$_", strlen ("_OBJC_METACLASS_$_")) == 0))
2438                                                             add_nlist = false;
2439                                                         else
2440                                                         {
2441                                                             is_gsym = true;
2442                                                             sym[sym_idx].SetExternal(true);
2443                                                             if (nlist.n_value != 0)
2444                                                                 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2445                                                             type = eSymbolTypeData;
2446                                                         }
2447                                                         break;
2448 
2449                                                     case N_FNAME:
2450                                                         // procedure name (f77 kludge): name,,NO_SECT,0,0
2451                                                         type = eSymbolTypeCompiler;
2452                                                         break;
2453 
2454                                                     case N_FUN:
2455                                                         // procedure: name,,n_sect,linenumber,address
2456                                                         if (symbol_name)
2457                                                         {
2458                                                             type = eSymbolTypeCode;
2459                                                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2460 
2461                                                             N_FUN_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx));
2462                                                             // We use the current number of symbols in the symbol table in lieu of
2463                                                             // using nlist_idx in case we ever start trimming entries out
2464                                                             N_FUN_indexes.push_back(sym_idx);
2465                                                         }
2466                                                         else
2467                                                         {
2468                                                             type = eSymbolTypeCompiler;
2469 
2470                                                             if ( !N_FUN_indexes.empty() )
2471                                                             {
2472                                                                 // Copy the size of the function into the original STAB entry so we don't have
2473                                                                 // to hunt for it later
2474                                                                 symtab->SymbolAtIndex(N_FUN_indexes.back())->SetByteSize(nlist.n_value);
2475                                                                 N_FUN_indexes.pop_back();
2476                                                                 // We don't really need the end function STAB as it contains the size which
2477                                                                 // we already placed with the original symbol, so don't add it if we want a
2478                                                                 // minimal symbol table
2479                                                                 add_nlist = false;
2480                                                             }
2481                                                         }
2482                                                         break;
2483 
2484                                                     case N_STSYM:
2485                                                         // static symbol: name,,n_sect,type,address
2486                                                         N_STSYM_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx));
2487                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2488                                                         type = eSymbolTypeData;
2489                                                         break;
2490 
2491                                                     case N_LCSYM:
2492                                                         // .lcomm symbol: name,,n_sect,type,address
2493                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2494                                                         type = eSymbolTypeCommonBlock;
2495                                                         break;
2496 
2497                                                     case N_BNSYM:
2498                                                         // We use the current number of symbols in the symbol table in lieu of
2499                                                         // using nlist_idx in case we ever start trimming entries out
2500                                                         // Skip these if we want minimal symbol tables
2501                                                         add_nlist = false;
2502                                                         break;
2503 
2504                                                     case N_ENSYM:
2505                                                         // Set the size of the N_BNSYM to the terminating index of this N_ENSYM
2506                                                         // so that we can always skip the entire symbol if we need to navigate
2507                                                         // more quickly at the source level when parsing STABS
2508                                                         // Skip these if we want minimal symbol tables
2509                                                         add_nlist = false;
2510                                                         break;
2511 
2512 
2513                                                     case N_OPT:
2514                                                         // emitted with gcc2_compiled and in gcc source
2515                                                         type = eSymbolTypeCompiler;
2516                                                         break;
2517 
2518                                                     case N_RSYM:
2519                                                         // register sym: name,,NO_SECT,type,register
2520                                                         type = eSymbolTypeVariable;
2521                                                         break;
2522 
2523                                                     case N_SLINE:
2524                                                         // src line: 0,,n_sect,linenumber,address
2525                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2526                                                         type = eSymbolTypeLineEntry;
2527                                                         break;
2528 
2529                                                     case N_SSYM:
2530                                                         // structure elt: name,,NO_SECT,type,struct_offset
2531                                                         type = eSymbolTypeVariableType;
2532                                                         break;
2533 
2534                                                     case N_SO:
2535                                                         // source file name
2536                                                         type = eSymbolTypeSourceFile;
2537                                                         if (symbol_name == NULL)
2538                                                         {
2539                                                             add_nlist = false;
2540                                                             if (N_SO_index != UINT32_MAX)
2541                                                             {
2542                                                                 // Set the size of the N_SO to the terminating index of this N_SO
2543                                                                 // so that we can always skip the entire N_SO if we need to navigate
2544                                                                 // more quickly at the source level when parsing STABS
2545                                                                 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
2546                                                                 symbol_ptr->SetByteSize(sym_idx);
2547                                                                 symbol_ptr->SetSizeIsSibling(true);
2548                                                             }
2549                                                             N_NSYM_indexes.clear();
2550                                                             N_INCL_indexes.clear();
2551                                                             N_BRAC_indexes.clear();
2552                                                             N_COMM_indexes.clear();
2553                                                             N_FUN_indexes.clear();
2554                                                             N_SO_index = UINT32_MAX;
2555                                                         }
2556                                                         else
2557                                                         {
2558                                                             // We use the current number of symbols in the symbol table in lieu of
2559                                                             // using nlist_idx in case we ever start trimming entries out
2560                                                             const bool N_SO_has_full_path = symbol_name[0] == '/';
2561                                                             if (N_SO_has_full_path)
2562                                                             {
2563                                                                 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
2564                                                                 {
2565                                                                     // We have two consecutive N_SO entries where the first contains a directory
2566                                                                     // and the second contains a full path.
2567                                                                     sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name), false);
2568                                                                     m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
2569                                                                     add_nlist = false;
2570                                                                 }
2571                                                                 else
2572                                                                 {
2573                                                                     // This is the first entry in a N_SO that contains a directory or
2574                                                                     // a full path to the source file
2575                                                                     N_SO_index = sym_idx;
2576                                                                 }
2577                                                             }
2578                                                             else if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
2579                                                             {
2580                                                                 // This is usually the second N_SO entry that contains just the filename,
2581                                                                 // so here we combine it with the first one if we are minimizing the symbol table
2582                                                                 const char *so_path = sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString();
2583                                                                 if (so_path && so_path[0])
2584                                                                 {
2585                                                                     std::string full_so_path (so_path);
2586                                                                     const size_t double_slash_pos = full_so_path.find("//");
2587                                                                     if (double_slash_pos != std::string::npos)
2588                                                                     {
2589                                                                         // The linker has been generating bad N_SO entries with doubled up paths
2590                                                                         // in the format "%s%s" where the first string in the DW_AT_comp_dir,
2591                                                                         // and the second is the directory for the source file so you end up with
2592                                                                         // a path that looks like "/tmp/src//tmp/src/"
2593                                                                         FileSpec so_dir(so_path, false);
2594                                                                         if (!so_dir.Exists())
2595                                                                         {
2596                                                                             so_dir.SetFile(&full_so_path[double_slash_pos + 1], false);
2597                                                                             if (so_dir.Exists())
2598                                                                             {
2599                                                                                 // Trim off the incorrect path
2600                                                                                 full_so_path.erase(0, double_slash_pos + 1);
2601                                                                             }
2602                                                                         }
2603                                                                     }
2604                                                                     if (*full_so_path.rbegin() != '/')
2605                                                                         full_so_path += '/';
2606                                                                     full_so_path += symbol_name;
2607                                                                     sym[sym_idx - 1].GetMangled().SetValue(ConstString(full_so_path.c_str()), false);
2608                                                                     add_nlist = false;
2609                                                                     m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
2610                                                                 }
2611                                                             }
2612                                                             else
2613                                                             {
2614                                                                 // This could be a relative path to a N_SO
2615                                                                 N_SO_index = sym_idx;
2616                                                             }
2617                                                         }
2618                                                         break;
2619 
2620                                                     case N_OSO:
2621                                                         // object file name: name,,0,0,st_mtime
2622                                                         type = eSymbolTypeObjectFile;
2623                                                         break;
2624 
2625                                                     case N_LSYM:
2626                                                         // local sym: name,,NO_SECT,type,offset
2627                                                         type = eSymbolTypeLocal;
2628                                                         break;
2629 
2630                                                         //----------------------------------------------------------------------
2631                                                         // INCL scopes
2632                                                         //----------------------------------------------------------------------
2633                                                     case N_BINCL:
2634                                                         // include file beginning: name,,NO_SECT,0,sum
2635                                                         // We use the current number of symbols in the symbol table in lieu of
2636                                                         // using nlist_idx in case we ever start trimming entries out
2637                                                         N_INCL_indexes.push_back(sym_idx);
2638                                                         type = eSymbolTypeScopeBegin;
2639                                                         break;
2640 
2641                                                     case N_EINCL:
2642                                                         // include file end: name,,NO_SECT,0,0
2643                                                         // Set the size of the N_BINCL to the terminating index of this N_EINCL
2644                                                         // so that we can always skip the entire symbol if we need to navigate
2645                                                         // more quickly at the source level when parsing STABS
2646                                                         if ( !N_INCL_indexes.empty() )
2647                                                         {
2648                                                             symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
2649                                                             symbol_ptr->SetByteSize(sym_idx + 1);
2650                                                             symbol_ptr->SetSizeIsSibling(true);
2651                                                             N_INCL_indexes.pop_back();
2652                                                         }
2653                                                         type = eSymbolTypeScopeEnd;
2654                                                         break;
2655 
2656                                                     case N_SOL:
2657                                                         // #included file name: name,,n_sect,0,address
2658                                                         type = eSymbolTypeHeaderFile;
2659 
2660                                                         // We currently don't use the header files on darwin
2661                                                         add_nlist = false;
2662                                                         break;
2663 
2664                                                     case N_PARAMS:
2665                                                         // compiler parameters: name,,NO_SECT,0,0
2666                                                         type = eSymbolTypeCompiler;
2667                                                         break;
2668 
2669                                                     case N_VERSION:
2670                                                         // compiler version: name,,NO_SECT,0,0
2671                                                         type = eSymbolTypeCompiler;
2672                                                         break;
2673 
2674                                                     case N_OLEVEL:
2675                                                         // compiler -O level: name,,NO_SECT,0,0
2676                                                         type = eSymbolTypeCompiler;
2677                                                         break;
2678 
2679                                                     case N_PSYM:
2680                                                         // parameter: name,,NO_SECT,type,offset
2681                                                         type = eSymbolTypeVariable;
2682                                                         break;
2683 
2684                                                     case N_ENTRY:
2685                                                         // alternate entry: name,,n_sect,linenumber,address
2686                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2687                                                         type = eSymbolTypeLineEntry;
2688                                                         break;
2689 
2690                                                         //----------------------------------------------------------------------
2691                                                         // Left and Right Braces
2692                                                         //----------------------------------------------------------------------
2693                                                     case N_LBRAC:
2694                                                         // left bracket: 0,,NO_SECT,nesting level,address
2695                                                         // We use the current number of symbols in the symbol table in lieu of
2696                                                         // using nlist_idx in case we ever start trimming entries out
2697                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2698                                                         N_BRAC_indexes.push_back(sym_idx);
2699                                                         type = eSymbolTypeScopeBegin;
2700                                                         break;
2701 
2702                                                     case N_RBRAC:
2703                                                         // right bracket: 0,,NO_SECT,nesting level,address
2704                                                         // Set the size of the N_LBRAC to the terminating index of this N_RBRAC
2705                                                         // so that we can always skip the entire symbol if we need to navigate
2706                                                         // more quickly at the source level when parsing STABS
2707                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2708                                                         if ( !N_BRAC_indexes.empty() )
2709                                                         {
2710                                                             symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
2711                                                             symbol_ptr->SetByteSize(sym_idx + 1);
2712                                                             symbol_ptr->SetSizeIsSibling(true);
2713                                                             N_BRAC_indexes.pop_back();
2714                                                         }
2715                                                         type = eSymbolTypeScopeEnd;
2716                                                         break;
2717 
2718                                                     case N_EXCL:
2719                                                         // deleted include file: name,,NO_SECT,0,sum
2720                                                         type = eSymbolTypeHeaderFile;
2721                                                         break;
2722 
2723                                                         //----------------------------------------------------------------------
2724                                                         // COMM scopes
2725                                                         //----------------------------------------------------------------------
2726                                                     case N_BCOMM:
2727                                                         // begin common: name,,NO_SECT,0,0
2728                                                         // We use the current number of symbols in the symbol table in lieu of
2729                                                         // using nlist_idx in case we ever start trimming entries out
2730                                                         type = eSymbolTypeScopeBegin;
2731                                                         N_COMM_indexes.push_back(sym_idx);
2732                                                         break;
2733 
2734                                                     case N_ECOML:
2735                                                         // end common (local name): 0,,n_sect,0,address
2736                                                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2737                                                         // Fall through
2738 
2739                                                     case N_ECOMM:
2740                                                         // end common: name,,n_sect,0,0
2741                                                         // Set the size of the N_BCOMM to the terminating index of this N_ECOMM/N_ECOML
2742                                                         // so that we can always skip the entire symbol if we need to navigate
2743                                                         // more quickly at the source level when parsing STABS
2744                                                         if ( !N_COMM_indexes.empty() )
2745                                                         {
2746                                                             symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
2747                                                             symbol_ptr->SetByteSize(sym_idx + 1);
2748                                                             symbol_ptr->SetSizeIsSibling(true);
2749                                                             N_COMM_indexes.pop_back();
2750                                                         }
2751                                                         type = eSymbolTypeScopeEnd;
2752                                                         break;
2753 
2754                                                     case N_LENG:
2755                                                         // second stab entry with length information
2756                                                         type = eSymbolTypeAdditional;
2757                                                         break;
2758 
2759                                                     default: break;
2760                                                 }
2761                                             }
2762                                             else
2763                                             {
2764                                                 //uint8_t n_pext    = N_PEXT & nlist.n_type;
2765                                                 uint8_t n_type  = N_TYPE & nlist.n_type;
2766                                                 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
2767 
2768                                                 switch (n_type)
2769                                                 {
2770                                                     case N_INDR: // Fall through
2771                                                     case N_PBUD: // Fall through
2772                                                     case N_UNDF:
2773                                                         type = eSymbolTypeUndefined;
2774                                                         break;
2775 
2776                                                     case N_ABS:
2777                                                         type = eSymbolTypeAbsolute;
2778                                                         break;
2779 
2780                                                     case N_SECT:
2781                                                         {
2782                                                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
2783 
2784                                                             if (symbol_section == NULL)
2785                                                             {
2786                                                                 // TODO: warn about this?
2787                                                                 add_nlist = false;
2788                                                                 break;
2789                                                             }
2790 
2791                                                             if (TEXT_eh_frame_sectID == nlist.n_sect)
2792                                                             {
2793                                                                 type = eSymbolTypeException;
2794                                                             }
2795                                                             else
2796                                                             {
2797                                                                 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
2798 
2799                                                                 switch (section_type)
2800                                                                 {
2801                                                                     case S_REGULAR:                    break; // regular section
2802                                                                                                                                                   //case S_ZEROFILL:                   type = eSymbolTypeData;    break; // zero fill on demand section
2803                                                                     case S_CSTRING_LITERALS:           type = eSymbolTypeData;    break; // section with only literal C strings
2804                                                                     case S_4BYTE_LITERALS:             type = eSymbolTypeData;    break; // section with only 4 byte literals
2805                                                                     case S_8BYTE_LITERALS:             type = eSymbolTypeData;    break; // section with only 8 byte literals
2806                                                                     case S_LITERAL_POINTERS:           type = eSymbolTypeTrampoline; break; // section with only pointers to literals
2807                                                                     case S_NON_LAZY_SYMBOL_POINTERS:   type = eSymbolTypeTrampoline; break; // section with only non-lazy symbol pointers
2808                                                                     case S_LAZY_SYMBOL_POINTERS:       type = eSymbolTypeTrampoline; break; // section with only lazy symbol pointers
2809                                                                     case S_SYMBOL_STUBS:               type = eSymbolTypeTrampoline; break; // section with only symbol stubs, byte size of stub in the reserved2 field
2810                                                                     case S_MOD_INIT_FUNC_POINTERS:     type = eSymbolTypeCode;    break; // section with only function pointers for initialization
2811                                                                     case S_MOD_TERM_FUNC_POINTERS:     type = eSymbolTypeCode;    break; // section with only function pointers for termination
2812                                                                                                                                                   //case S_COALESCED:                  type = eSymbolType;    break; // section contains symbols that are to be coalesced
2813                                                                                                                                                   //case S_GB_ZEROFILL:                type = eSymbolTypeData;    break; // zero fill on demand section (that can be larger than 4 gigabytes)
2814                                                                     case S_INTERPOSING:                type = eSymbolTypeTrampoline;  break; // section with only pairs of function pointers for interposing
2815                                                                     case S_16BYTE_LITERALS:            type = eSymbolTypeData;    break; // section with only 16 byte literals
2816                                                                     case S_DTRACE_DOF:                 type = eSymbolTypeInstrumentation; break;
2817                                                                     case S_LAZY_DYLIB_SYMBOL_POINTERS: type = eSymbolTypeTrampoline; break;
2818                                                                     default: break;
2819                                                                 }
2820 
2821                                                                 if (type == eSymbolTypeInvalid)
2822                                                                 {
2823                                                                     const char *symbol_sect_name = symbol_section->GetName().AsCString();
2824                                                                     if (symbol_section->IsDescendant (text_section_sp.get()))
2825                                                                     {
2826                                                                         if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
2827                                                                                                     S_ATTR_SELF_MODIFYING_CODE |
2828                                                                                                     S_ATTR_SOME_INSTRUCTIONS))
2829                                                                             type = eSymbolTypeData;
2830                                                                         else
2831                                                                             type = eSymbolTypeCode;
2832                                                                     }
2833                                                                     else if (symbol_section->IsDescendant(data_section_sp.get()))
2834                                                                     {
2835                                                                         if (symbol_sect_name && ::strstr (symbol_sect_name, "__objc") == symbol_sect_name)
2836                                                                         {
2837                                                                             type = eSymbolTypeRuntime;
2838 
2839                                                                             if (symbol_name &&
2840                                                                                 symbol_name[0] == '_' &&
2841                                                                                 symbol_name[1] == 'O' &&
2842                                                                                 symbol_name[2] == 'B')
2843                                                                             {
2844                                                                                 llvm::StringRef symbol_name_ref(symbol_name);
2845                                                                                 static const llvm::StringRef g_objc_v2_prefix_class ("_OBJC_CLASS_$_");
2846                                                                                 static const llvm::StringRef g_objc_v2_prefix_metaclass ("_OBJC_METACLASS_$_");
2847                                                                                 static const llvm::StringRef g_objc_v2_prefix_ivar ("_OBJC_IVAR_$_");
2848                                                                                 if (symbol_name_ref.startswith(g_objc_v2_prefix_class))
2849                                                                                 {
2850                                                                                     symbol_name_non_abi_mangled = symbol_name + 1;
2851                                                                                     symbol_name = symbol_name + g_objc_v2_prefix_class.size();
2852                                                                                     type = eSymbolTypeObjCClass;
2853                                                                                     demangled_is_synthesized = true;
2854                                                                                 }
2855                                                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass))
2856                                                                                 {
2857                                                                                     symbol_name_non_abi_mangled = symbol_name + 1;
2858                                                                                     symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
2859                                                                                     type = eSymbolTypeObjCMetaClass;
2860                                                                                     demangled_is_synthesized = true;
2861                                                                                 }
2862                                                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar))
2863                                                                                 {
2864                                                                                     symbol_name_non_abi_mangled = symbol_name + 1;
2865                                                                                     symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
2866                                                                                     type = eSymbolTypeObjCIVar;
2867                                                                                     demangled_is_synthesized = true;
2868                                                                                 }
2869                                                                             }
2870                                                                         }
2871                                                                         else if (symbol_sect_name && ::strstr (symbol_sect_name, "__gcc_except_tab") == symbol_sect_name)
2872                                                                         {
2873                                                                             type = eSymbolTypeException;
2874                                                                         }
2875                                                                         else
2876                                                                         {
2877                                                                             type = eSymbolTypeData;
2878                                                                         }
2879                                                                     }
2880                                                                     else if (symbol_sect_name && ::strstr (symbol_sect_name, "__IMPORT") == symbol_sect_name)
2881                                                                     {
2882                                                                         type = eSymbolTypeTrampoline;
2883                                                                     }
2884                                                                     else if (symbol_section->IsDescendant(objc_section_sp.get()))
2885                                                                     {
2886                                                                         type = eSymbolTypeRuntime;
2887                                                                         if (symbol_name && symbol_name[0] == '.')
2888                                                                         {
2889                                                                             llvm::StringRef symbol_name_ref(symbol_name);
2890                                                                             static const llvm::StringRef g_objc_v1_prefix_class (".objc_class_name_");
2891                                                                             if (symbol_name_ref.startswith(g_objc_v1_prefix_class))
2892                                                                             {
2893                                                                                 symbol_name_non_abi_mangled = symbol_name;
2894                                                                                 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
2895                                                                                 type = eSymbolTypeObjCClass;
2896                                                                                 demangled_is_synthesized = true;
2897                                                                             }
2898                                                                         }
2899                                                                     }
2900                                                                 }
2901                                                             }
2902                                                         }
2903                                                         break;
2904                                                 }
2905                                             }
2906 
2907                                             if (add_nlist)
2908                                             {
2909                                                 uint64_t symbol_value = nlist.n_value;
2910                                                 if (symbol_name_non_abi_mangled)
2911                                                 {
2912                                                     sym[sym_idx].GetMangled().SetMangledName (ConstString(symbol_name_non_abi_mangled));
2913                                                     sym[sym_idx].GetMangled().SetDemangledName (ConstString(symbol_name));
2914                                                 }
2915                                                 else
2916                                                 {
2917                                                     bool symbol_name_is_mangled = false;
2918 
2919                                                     if (symbol_name && symbol_name[0] == '_')
2920                                                     {
2921                                                         symbol_name_is_mangled = symbol_name[1] == '_';
2922                                                         symbol_name++;  // Skip the leading underscore
2923                                                     }
2924 
2925                                                     if (symbol_name)
2926                                                     {
2927                                                         ConstString const_symbol_name(symbol_name);
2928                                                         sym[sym_idx].GetMangled().SetValue(const_symbol_name, symbol_name_is_mangled);
2929                                                         if (is_gsym && is_debug)
2930                                                             N_GSYM_name_to_sym_idx[sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString()] = sym_idx;
2931                                                     }
2932                                                 }
2933                                                 if (symbol_section)
2934                                                 {
2935                                                     const addr_t section_file_addr = symbol_section->GetFileAddress();
2936                                                     if (symbol_byte_size == 0 && function_starts_count > 0)
2937                                                     {
2938                                                         addr_t symbol_lookup_file_addr = nlist.n_value;
2939                                                         // Do an exact address match for non-ARM addresses, else get the closest since
2940                                                         // the symbol might be a thumb symbol which has an address with bit zero set
2941                                                         FunctionStarts::Entry *func_start_entry = function_starts.FindEntry (symbol_lookup_file_addr, !is_arm);
2942                                                         if (is_arm && func_start_entry)
2943                                                         {
2944                                                             // Verify that the function start address is the symbol address (ARM)
2945                                                             // or the symbol address + 1 (thumb)
2946                                                             if (func_start_entry->addr != symbol_lookup_file_addr &&
2947                                                                 func_start_entry->addr != (symbol_lookup_file_addr + 1))
2948                                                             {
2949                                                                 // Not the right entry, NULL it out...
2950                                                                 func_start_entry = NULL;
2951                                                             }
2952                                                         }
2953                                                         if (func_start_entry)
2954                                                         {
2955                                                             func_start_entry->data = true;
2956 
2957                                                             addr_t symbol_file_addr = func_start_entry->addr;
2958                                                             uint32_t symbol_flags = 0;
2959                                                             if (is_arm)
2960                                                             {
2961                                                                 if (symbol_file_addr & 1)
2962                                                                     symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
2963                                                                 symbol_file_addr &= 0xfffffffffffffffeull;
2964                                                             }
2965 
2966                                                             const FunctionStarts::Entry *next_func_start_entry = function_starts.FindNextEntry (func_start_entry);
2967                                                             const addr_t section_end_file_addr = section_file_addr + symbol_section->GetByteSize();
2968                                                             if (next_func_start_entry)
2969                                                             {
2970                                                                 addr_t next_symbol_file_addr = next_func_start_entry->addr;
2971                                                                 // Be sure the clear the Thumb address bit when we calculate the size
2972                                                                 // from the current and next address
2973                                                                 if (is_arm)
2974                                                                     next_symbol_file_addr &= 0xfffffffffffffffeull;
2975                                                                 symbol_byte_size = std::min<lldb::addr_t>(next_symbol_file_addr - symbol_file_addr, section_end_file_addr - symbol_file_addr);
2976                                                             }
2977                                                             else
2978                                                             {
2979                                                                 symbol_byte_size = section_end_file_addr - symbol_file_addr;
2980                                                             }
2981                                                         }
2982                                                     }
2983                                                     symbol_value -= section_file_addr;
2984                                                 }
2985 
2986                                                 if (is_debug == false)
2987                                                 {
2988                                                     if (type == eSymbolTypeCode)
2989                                                     {
2990                                                         // See if we can find a N_FUN entry for any code symbols.
2991                                                         // If we do find a match, and the name matches, then we
2992                                                         // can merge the two into just the function symbol to avoid
2993                                                         // duplicate entries in the symbol table
2994                                                         std::pair<ValueToSymbolIndexMap::const_iterator, ValueToSymbolIndexMap::const_iterator> range;
2995                                                         range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
2996                                                         if (range.first != range.second)
2997                                                         {
2998                                                             bool found_it = false;
2999                                                             for (ValueToSymbolIndexMap::const_iterator pos = range.first; pos != range.second; ++pos)
3000                                                             {
3001                                                                 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled))
3002                                                                 {
3003                                                                     m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3004                                                                     // We just need the flags from the linker symbol, so put these flags
3005                                                                     // into the N_FUN flags to avoid duplicate symbols in the symbol table
3006                                                                     sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
3007                                                                     sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3008                                                                     if (resolver_addresses.find(nlist.n_value) != resolver_addresses.end())
3009                                                                         sym[pos->second].SetType (eSymbolTypeResolver);
3010                                                                     sym[sym_idx].Clear();
3011                                                                     found_it = true;
3012                                                                     break;
3013                                                                 }
3014                                                             }
3015                                                             if (found_it)
3016                                                                 continue;
3017                                                         }
3018                                                         else
3019                                                         {
3020                                                             if (resolver_addresses.find(nlist.n_value) != resolver_addresses.end())
3021                                                                 type = eSymbolTypeResolver;
3022                                                         }
3023                                                     }
3024                                                     else if (type == eSymbolTypeData)
3025                                                     {
3026                                                         // See if we can find a N_STSYM entry for any data symbols.
3027                                                         // If we do find a match, and the name matches, then we
3028                                                         // can merge the two into just the Static symbol to avoid
3029                                                         // duplicate entries in the symbol table
3030                                                         std::pair<ValueToSymbolIndexMap::const_iterator, ValueToSymbolIndexMap::const_iterator> range;
3031                                                         range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
3032                                                         if (range.first != range.second)
3033                                                         {
3034                                                             bool found_it = false;
3035                                                             for (ValueToSymbolIndexMap::const_iterator pos = range.first; pos != range.second; ++pos)
3036                                                             {
3037                                                                 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled))
3038                                                                 {
3039                                                                     m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3040                                                                     // We just need the flags from the linker symbol, so put these flags
3041                                                                     // into the N_STSYM flags to avoid duplicate symbols in the symbol table
3042                                                                     sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
3043                                                                     sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3044                                                                     sym[sym_idx].Clear();
3045                                                                     found_it = true;
3046                                                                     break;
3047                                                                 }
3048                                                             }
3049                                                             if (found_it)
3050                                                                 continue;
3051                                                         }
3052                                                         else
3053                                                         {
3054                                                             // Combine N_GSYM stab entries with the non stab symbol
3055                                                             ConstNameToSymbolIndexMap::const_iterator pos = N_GSYM_name_to_sym_idx.find(sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString());
3056                                                             if (pos != N_GSYM_name_to_sym_idx.end())
3057                                                             {
3058                                                                 const uint32_t GSYM_sym_idx = pos->second;
3059                                                                 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
3060                                                                 // Copy the address, because often the N_GSYM address has an invalid address of zero
3061                                                                 // when the global is a common symbol
3062                                                                 sym[GSYM_sym_idx].GetAddress().SetSection (symbol_section);
3063                                                                 sym[GSYM_sym_idx].GetAddress().SetOffset (symbol_value);
3064                                                                 // We just need the flags from the linker symbol, so put these flags
3065                                                                 // into the N_STSYM flags to avoid duplicate symbols in the symbol table
3066                                                                 sym[GSYM_sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3067                                                                 sym[sym_idx].Clear();
3068                                                                 continue;
3069                                                             }
3070                                                         }
3071                                                     }
3072                                                 }
3073 
3074                                                 sym[sym_idx].SetID (nlist_idx);
3075                                                 sym[sym_idx].SetType (type);
3076                                                 sym[sym_idx].GetAddress().SetSection (symbol_section);
3077                                                 sym[sym_idx].GetAddress().SetOffset (symbol_value);
3078                                                 sym[sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3079 
3080                                                 if (symbol_byte_size > 0)
3081                                                     sym[sym_idx].SetByteSize(symbol_byte_size);
3082 
3083                                                 if (demangled_is_synthesized)
3084                                                     sym[sym_idx].SetDemangledNameIsSynthesized(true);
3085                                                 ++sym_idx;
3086                                             }
3087                                             else
3088                                             {
3089                                                 sym[sym_idx].Clear();
3090                                             }
3091 
3092                                         }
3093                                         /////////////////////////////
3094                                     }
3095                                     break; // No more entries to consider
3096                                 }
3097                             }
3098                         }
3099                     }
3100                 }
3101             }
3102         }
3103 
3104         // Must reset this in case it was mutated above!
3105         nlist_data_offset = 0;
3106 #endif
3107 
3108         if (nlist_data.GetByteSize() > 0)
3109         {
3110 
3111             // If the sym array was not created while parsing the DSC unmapped
3112             // symbols, create it now.
3113             if (sym == NULL)
3114             {
3115                 sym = symtab->Resize (symtab_load_command.nsyms + m_dysymtab.nindirectsyms);
3116                 num_syms = symtab->GetNumSymbols();
3117             }
3118 
3119             if (unmapped_local_symbols_found)
3120             {
3121                 assert(m_dysymtab.ilocalsym == 0);
3122                 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3123                 nlist_idx = m_dysymtab.nlocalsym;
3124             }
3125             else
3126             {
3127                 nlist_idx = 0;
3128             }
3129 
3130             for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx)
3131             {
3132                 struct nlist_64 nlist;
3133                 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size))
3134                     break;
3135 
3136                 nlist.n_strx  = nlist_data.GetU32_unchecked(&nlist_data_offset);
3137                 nlist.n_type  = nlist_data.GetU8_unchecked (&nlist_data_offset);
3138                 nlist.n_sect  = nlist_data.GetU8_unchecked (&nlist_data_offset);
3139                 nlist.n_desc  = nlist_data.GetU16_unchecked (&nlist_data_offset);
3140                 nlist.n_value = nlist_data.GetAddress_unchecked (&nlist_data_offset);
3141 
3142                 SymbolType type = eSymbolTypeInvalid;
3143                 const char *symbol_name = NULL;
3144 
3145                 if (have_strtab_data)
3146                 {
3147                     symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3148 
3149                     if (symbol_name == NULL)
3150                     {
3151                         // No symbol should be NULL, even the symbols with no
3152                         // string values should have an offset zero which points
3153                         // to an empty C-string
3154                         Host::SystemLog (Host::eSystemLogError,
3155                                          "error: symbol[%u] has invalid string table offset 0x%x in %s, ignoring symbol\n",
3156                                          nlist_idx,
3157                                          nlist.n_strx,
3158                                          module_sp->GetFileSpec().GetPath().c_str());
3159                         continue;
3160                     }
3161                     if (symbol_name[0] == '\0')
3162                         symbol_name = NULL;
3163                 }
3164                 else
3165                 {
3166                     const addr_t str_addr = strtab_addr + nlist.n_strx;
3167                     Error str_error;
3168                     if (process->ReadCStringFromMemory(str_addr, memory_symbol_name, str_error))
3169                         symbol_name = memory_symbol_name.c_str();
3170                 }
3171                 const char *symbol_name_non_abi_mangled = NULL;
3172 
3173                 SectionSP symbol_section;
3174                 lldb::addr_t symbol_byte_size = 0;
3175                 bool add_nlist = true;
3176                 bool is_gsym = false;
3177                 bool is_debug = ((nlist.n_type & N_STAB) != 0);
3178                 bool demangled_is_synthesized = false;
3179 
3180                 assert (sym_idx < num_syms);
3181 
3182                 sym[sym_idx].SetDebug (is_debug);
3183 
3184                 if (is_debug)
3185                 {
3186                     switch (nlist.n_type)
3187                     {
3188                     case N_GSYM:
3189                         // global symbol: name,,NO_SECT,type,0
3190                         // Sometimes the N_GSYM value contains the address.
3191 
3192                         // FIXME: In the .o files, we have a GSYM and a debug symbol for all the ObjC data.  They
3193                         // have the same address, but we want to ensure that we always find only the real symbol,
3194                         // 'cause we don't currently correctly attribute the GSYM one to the ObjCClass/Ivar/MetaClass
3195                         // symbol type.  This is a temporary hack to make sure the ObjectiveC symbols get treated
3196                         // correctly.  To do this right, we should coalesce all the GSYM & global symbols that have the
3197                         // same address.
3198 
3199                         if (symbol_name && symbol_name[0] == '_' && symbol_name[1] ==  'O'
3200                             && (strncmp (symbol_name, "_OBJC_IVAR_$_", strlen ("_OBJC_IVAR_$_")) == 0
3201                                 || strncmp (symbol_name, "_OBJC_CLASS_$_", strlen ("_OBJC_CLASS_$_")) == 0
3202                                 || strncmp (symbol_name, "_OBJC_METACLASS_$_", strlen ("_OBJC_METACLASS_$_")) == 0))
3203                             add_nlist = false;
3204                         else
3205                         {
3206                             is_gsym = true;
3207                             sym[sym_idx].SetExternal(true);
3208                             if (nlist.n_value != 0)
3209                                 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3210                             type = eSymbolTypeData;
3211                         }
3212                         break;
3213 
3214                     case N_FNAME:
3215                         // procedure name (f77 kludge): name,,NO_SECT,0,0
3216                         type = eSymbolTypeCompiler;
3217                         break;
3218 
3219                     case N_FUN:
3220                         // procedure: name,,n_sect,linenumber,address
3221                         if (symbol_name)
3222                         {
3223                             type = eSymbolTypeCode;
3224                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3225 
3226                             N_FUN_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx));
3227                             // We use the current number of symbols in the symbol table in lieu of
3228                             // using nlist_idx in case we ever start trimming entries out
3229                             N_FUN_indexes.push_back(sym_idx);
3230                         }
3231                         else
3232                         {
3233                             type = eSymbolTypeCompiler;
3234 
3235                             if ( !N_FUN_indexes.empty() )
3236                             {
3237                                 // Copy the size of the function into the original STAB entry so we don't have
3238                                 // to hunt for it later
3239                                 symtab->SymbolAtIndex(N_FUN_indexes.back())->SetByteSize(nlist.n_value);
3240                                 N_FUN_indexes.pop_back();
3241                                 // We don't really need the end function STAB as it contains the size which
3242                                 // we already placed with the original symbol, so don't add it if we want a
3243                                 // minimal symbol table
3244                                 add_nlist = false;
3245                             }
3246                         }
3247                         break;
3248 
3249                     case N_STSYM:
3250                         // static symbol: name,,n_sect,type,address
3251                         N_STSYM_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx));
3252                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3253                         type = eSymbolTypeData;
3254                         break;
3255 
3256                     case N_LCSYM:
3257                         // .lcomm symbol: name,,n_sect,type,address
3258                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3259                         type = eSymbolTypeCommonBlock;
3260                         break;
3261 
3262                     case N_BNSYM:
3263                         // We use the current number of symbols in the symbol table in lieu of
3264                         // using nlist_idx in case we ever start trimming entries out
3265                         // Skip these if we want minimal symbol tables
3266                         add_nlist = false;
3267                         break;
3268 
3269                     case N_ENSYM:
3270                         // Set the size of the N_BNSYM to the terminating index of this N_ENSYM
3271                         // so that we can always skip the entire symbol if we need to navigate
3272                         // more quickly at the source level when parsing STABS
3273                         // Skip these if we want minimal symbol tables
3274                         add_nlist = false;
3275                         break;
3276 
3277 
3278                     case N_OPT:
3279                         // emitted with gcc2_compiled and in gcc source
3280                         type = eSymbolTypeCompiler;
3281                         break;
3282 
3283                     case N_RSYM:
3284                         // register sym: name,,NO_SECT,type,register
3285                         type = eSymbolTypeVariable;
3286                         break;
3287 
3288                     case N_SLINE:
3289                         // src line: 0,,n_sect,linenumber,address
3290                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3291                         type = eSymbolTypeLineEntry;
3292                         break;
3293 
3294                     case N_SSYM:
3295                         // structure elt: name,,NO_SECT,type,struct_offset
3296                         type = eSymbolTypeVariableType;
3297                         break;
3298 
3299                     case N_SO:
3300                         // source file name
3301                         type = eSymbolTypeSourceFile;
3302                         if (symbol_name == NULL)
3303                         {
3304                             add_nlist = false;
3305                             if (N_SO_index != UINT32_MAX)
3306                             {
3307                                 // Set the size of the N_SO to the terminating index of this N_SO
3308                                 // so that we can always skip the entire N_SO if we need to navigate
3309                                 // more quickly at the source level when parsing STABS
3310                                 symbol_ptr = symtab->SymbolAtIndex(N_SO_index);
3311                                 symbol_ptr->SetByteSize(sym_idx);
3312                                 symbol_ptr->SetSizeIsSibling(true);
3313                             }
3314                             N_NSYM_indexes.clear();
3315                             N_INCL_indexes.clear();
3316                             N_BRAC_indexes.clear();
3317                             N_COMM_indexes.clear();
3318                             N_FUN_indexes.clear();
3319                             N_SO_index = UINT32_MAX;
3320                         }
3321                         else
3322                         {
3323                             // We use the current number of symbols in the symbol table in lieu of
3324                             // using nlist_idx in case we ever start trimming entries out
3325                             const bool N_SO_has_full_path = symbol_name[0] == '/';
3326                             if (N_SO_has_full_path)
3327                             {
3328                                 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
3329                                 {
3330                                     // We have two consecutive N_SO entries where the first contains a directory
3331                                     // and the second contains a full path.
3332                                     sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name), false);
3333                                     m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3334                                     add_nlist = false;
3335                                 }
3336                                 else
3337                                 {
3338                                     // This is the first entry in a N_SO that contains a directory or
3339                                     // a full path to the source file
3340                                     N_SO_index = sym_idx;
3341                                 }
3342                             }
3343                             else if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms))
3344                             {
3345                                 // This is usually the second N_SO entry that contains just the filename,
3346                                 // so here we combine it with the first one if we are minimizing the symbol table
3347                                 const char *so_path = sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString();
3348                                 if (so_path && so_path[0])
3349                                 {
3350                                     std::string full_so_path (so_path);
3351                                     const size_t double_slash_pos = full_so_path.find("//");
3352                                     if (double_slash_pos != std::string::npos)
3353                                     {
3354                                         // The linker has been generating bad N_SO entries with doubled up paths
3355                                         // in the format "%s%s" where the first string in the DW_AT_comp_dir,
3356                                         // and the second is the directory for the source file so you end up with
3357                                         // a path that looks like "/tmp/src//tmp/src/"
3358                                         FileSpec so_dir(so_path, false);
3359                                         if (!so_dir.Exists())
3360                                         {
3361                                             so_dir.SetFile(&full_so_path[double_slash_pos + 1], false);
3362                                             if (so_dir.Exists())
3363                                             {
3364                                                 // Trim off the incorrect path
3365                                                 full_so_path.erase(0, double_slash_pos + 1);
3366                                             }
3367                                         }
3368                                     }
3369                                     if (*full_so_path.rbegin() != '/')
3370                                         full_so_path += '/';
3371                                     full_so_path += symbol_name;
3372                                     sym[sym_idx - 1].GetMangled().SetValue(ConstString(full_so_path.c_str()), false);
3373                                     add_nlist = false;
3374                                     m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3375                                 }
3376                             }
3377                             else
3378                             {
3379                                 // This could be a relative path to a N_SO
3380                                 N_SO_index = sym_idx;
3381                             }
3382                         }
3383 
3384                         break;
3385 
3386                     case N_OSO:
3387                         // object file name: name,,0,0,st_mtime
3388                         type = eSymbolTypeObjectFile;
3389                         break;
3390 
3391                     case N_LSYM:
3392                         // local sym: name,,NO_SECT,type,offset
3393                         type = eSymbolTypeLocal;
3394                         break;
3395 
3396                     //----------------------------------------------------------------------
3397                     // INCL scopes
3398                     //----------------------------------------------------------------------
3399                     case N_BINCL:
3400                         // include file beginning: name,,NO_SECT,0,sum
3401                         // We use the current number of symbols in the symbol table in lieu of
3402                         // using nlist_idx in case we ever start trimming entries out
3403                         N_INCL_indexes.push_back(sym_idx);
3404                         type = eSymbolTypeScopeBegin;
3405                         break;
3406 
3407                     case N_EINCL:
3408                         // include file end: name,,NO_SECT,0,0
3409                         // Set the size of the N_BINCL to the terminating index of this N_EINCL
3410                         // so that we can always skip the entire symbol if we need to navigate
3411                         // more quickly at the source level when parsing STABS
3412                         if ( !N_INCL_indexes.empty() )
3413                         {
3414                             symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back());
3415                             symbol_ptr->SetByteSize(sym_idx + 1);
3416                             symbol_ptr->SetSizeIsSibling(true);
3417                             N_INCL_indexes.pop_back();
3418                         }
3419                         type = eSymbolTypeScopeEnd;
3420                         break;
3421 
3422                     case N_SOL:
3423                         // #included file name: name,,n_sect,0,address
3424                         type = eSymbolTypeHeaderFile;
3425 
3426                         // We currently don't use the header files on darwin
3427                         add_nlist = false;
3428                         break;
3429 
3430                     case N_PARAMS:
3431                         // compiler parameters: name,,NO_SECT,0,0
3432                         type = eSymbolTypeCompiler;
3433                         break;
3434 
3435                     case N_VERSION:
3436                         // compiler version: name,,NO_SECT,0,0
3437                         type = eSymbolTypeCompiler;
3438                         break;
3439 
3440                     case N_OLEVEL:
3441                         // compiler -O level: name,,NO_SECT,0,0
3442                         type = eSymbolTypeCompiler;
3443                         break;
3444 
3445                     case N_PSYM:
3446                         // parameter: name,,NO_SECT,type,offset
3447                         type = eSymbolTypeVariable;
3448                         break;
3449 
3450                     case N_ENTRY:
3451                         // alternate entry: name,,n_sect,linenumber,address
3452                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3453                         type = eSymbolTypeLineEntry;
3454                         break;
3455 
3456                     //----------------------------------------------------------------------
3457                     // Left and Right Braces
3458                     //----------------------------------------------------------------------
3459                     case N_LBRAC:
3460                         // left bracket: 0,,NO_SECT,nesting level,address
3461                         // We use the current number of symbols in the symbol table in lieu of
3462                         // using nlist_idx in case we ever start trimming entries out
3463                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3464                         N_BRAC_indexes.push_back(sym_idx);
3465                         type = eSymbolTypeScopeBegin;
3466                         break;
3467 
3468                     case N_RBRAC:
3469                         // right bracket: 0,,NO_SECT,nesting level,address
3470                         // Set the size of the N_LBRAC to the terminating index of this N_RBRAC
3471                         // so that we can always skip the entire symbol if we need to navigate
3472                         // more quickly at the source level when parsing STABS
3473                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3474                         if ( !N_BRAC_indexes.empty() )
3475                         {
3476                             symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back());
3477                             symbol_ptr->SetByteSize(sym_idx + 1);
3478                             symbol_ptr->SetSizeIsSibling(true);
3479                             N_BRAC_indexes.pop_back();
3480                         }
3481                         type = eSymbolTypeScopeEnd;
3482                         break;
3483 
3484                     case N_EXCL:
3485                         // deleted include file: name,,NO_SECT,0,sum
3486                         type = eSymbolTypeHeaderFile;
3487                         break;
3488 
3489                     //----------------------------------------------------------------------
3490                     // COMM scopes
3491                     //----------------------------------------------------------------------
3492                     case N_BCOMM:
3493                         // begin common: name,,NO_SECT,0,0
3494                         // We use the current number of symbols in the symbol table in lieu of
3495                         // using nlist_idx in case we ever start trimming entries out
3496                         type = eSymbolTypeScopeBegin;
3497                         N_COMM_indexes.push_back(sym_idx);
3498                         break;
3499 
3500                     case N_ECOML:
3501                         // end common (local name): 0,,n_sect,0,address
3502                         symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3503                         // Fall through
3504 
3505                     case N_ECOMM:
3506                         // end common: name,,n_sect,0,0
3507                         // Set the size of the N_BCOMM to the terminating index of this N_ECOMM/N_ECOML
3508                         // so that we can always skip the entire symbol if we need to navigate
3509                         // more quickly at the source level when parsing STABS
3510                         if ( !N_COMM_indexes.empty() )
3511                         {
3512                             symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back());
3513                             symbol_ptr->SetByteSize(sym_idx + 1);
3514                             symbol_ptr->SetSizeIsSibling(true);
3515                             N_COMM_indexes.pop_back();
3516                         }
3517                         type = eSymbolTypeScopeEnd;
3518                         break;
3519 
3520                     case N_LENG:
3521                         // second stab entry with length information
3522                         type = eSymbolTypeAdditional;
3523                         break;
3524 
3525                     default: break;
3526                     }
3527                 }
3528                 else
3529                 {
3530                     //uint8_t n_pext    = N_PEXT & nlist.n_type;
3531                     uint8_t n_type  = N_TYPE & nlist.n_type;
3532                     sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
3533 
3534                     switch (n_type)
3535                     {
3536                     case N_INDR:// Fall through
3537                     case N_PBUD:// Fall through
3538                     case N_UNDF:
3539                         type = eSymbolTypeUndefined;
3540                         break;
3541 
3542                     case N_ABS:
3543                         type = eSymbolTypeAbsolute;
3544                         break;
3545 
3546                     case N_SECT:
3547                         {
3548                             symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value);
3549 
3550                             if (!symbol_section)
3551                             {
3552                                 // TODO: warn about this?
3553                                 add_nlist = false;
3554                                 break;
3555                             }
3556 
3557                             if (TEXT_eh_frame_sectID == nlist.n_sect)
3558                             {
3559                                 type = eSymbolTypeException;
3560                             }
3561                             else
3562                             {
3563                                 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
3564 
3565                                 switch (section_type)
3566                                 {
3567                                 case S_REGULAR:                    break; // regular section
3568                                 //case S_ZEROFILL:                 type = eSymbolTypeData;    break; // zero fill on demand section
3569                                 case S_CSTRING_LITERALS:           type = eSymbolTypeData;    break; // section with only literal C strings
3570                                 case S_4BYTE_LITERALS:             type = eSymbolTypeData;    break; // section with only 4 byte literals
3571                                 case S_8BYTE_LITERALS:             type = eSymbolTypeData;    break; // section with only 8 byte literals
3572                                 case S_LITERAL_POINTERS:           type = eSymbolTypeTrampoline; break; // section with only pointers to literals
3573                                 case S_NON_LAZY_SYMBOL_POINTERS:   type = eSymbolTypeTrampoline; break; // section with only non-lazy symbol pointers
3574                                 case S_LAZY_SYMBOL_POINTERS:       type = eSymbolTypeTrampoline; break; // section with only lazy symbol pointers
3575                                 case S_SYMBOL_STUBS:               type = eSymbolTypeTrampoline; break; // section with only symbol stubs, byte size of stub in the reserved2 field
3576                                 case S_MOD_INIT_FUNC_POINTERS:     type = eSymbolTypeCode;    break; // section with only function pointers for initialization
3577                                 case S_MOD_TERM_FUNC_POINTERS:     type = eSymbolTypeCode;    break; // section with only function pointers for termination
3578                                 //case S_COALESCED:                type = eSymbolType;    break; // section contains symbols that are to be coalesced
3579                                 //case S_GB_ZEROFILL:              type = eSymbolTypeData;    break; // zero fill on demand section (that can be larger than 4 gigabytes)
3580                                 case S_INTERPOSING:                type = eSymbolTypeTrampoline;  break; // section with only pairs of function pointers for interposing
3581                                 case S_16BYTE_LITERALS:            type = eSymbolTypeData;    break; // section with only 16 byte literals
3582                                 case S_DTRACE_DOF:                 type = eSymbolTypeInstrumentation; break;
3583                                 case S_LAZY_DYLIB_SYMBOL_POINTERS: type = eSymbolTypeTrampoline; break;
3584                                 default: break;
3585                                 }
3586 
3587                                 if (type == eSymbolTypeInvalid)
3588                                 {
3589                                     const char *symbol_sect_name = symbol_section->GetName().AsCString();
3590                                     if (symbol_section->IsDescendant (text_section_sp.get()))
3591                                     {
3592                                         if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
3593                                                                     S_ATTR_SELF_MODIFYING_CODE |
3594                                                                     S_ATTR_SOME_INSTRUCTIONS))
3595                                             type = eSymbolTypeData;
3596                                         else
3597                                             type = eSymbolTypeCode;
3598                                     }
3599                                     else
3600                                     if (symbol_section->IsDescendant(data_section_sp.get()))
3601                                     {
3602                                         if (symbol_sect_name && ::strstr (symbol_sect_name, "__objc") == symbol_sect_name)
3603                                         {
3604                                             type = eSymbolTypeRuntime;
3605 
3606                                             if (symbol_name &&
3607                                                 symbol_name[0] == '_' &&
3608                                                 symbol_name[1] == 'O' &&
3609                                                 symbol_name[2] == 'B')
3610                                             {
3611                                                 llvm::StringRef symbol_name_ref(symbol_name);
3612                                                 static const llvm::StringRef g_objc_v2_prefix_class ("_OBJC_CLASS_$_");
3613                                                 static const llvm::StringRef g_objc_v2_prefix_metaclass ("_OBJC_METACLASS_$_");
3614                                                 static const llvm::StringRef g_objc_v2_prefix_ivar ("_OBJC_IVAR_$_");
3615                                                 if (symbol_name_ref.startswith(g_objc_v2_prefix_class))
3616                                                 {
3617                                                     symbol_name_non_abi_mangled = symbol_name + 1;
3618                                                     symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3619                                                     type = eSymbolTypeObjCClass;
3620                                                     demangled_is_synthesized = true;
3621                                                 }
3622                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass))
3623                                                 {
3624                                                     symbol_name_non_abi_mangled = symbol_name + 1;
3625                                                     symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3626                                                     type = eSymbolTypeObjCMetaClass;
3627                                                     demangled_is_synthesized = true;
3628                                                 }
3629                                                 else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar))
3630                                                 {
3631                                                     symbol_name_non_abi_mangled = symbol_name + 1;
3632                                                     symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3633                                                     type = eSymbolTypeObjCIVar;
3634                                                     demangled_is_synthesized = true;
3635                                                 }
3636                                             }
3637                                         }
3638                                         else
3639                                         if (symbol_sect_name && ::strstr (symbol_sect_name, "__gcc_except_tab") == symbol_sect_name)
3640                                         {
3641                                             type = eSymbolTypeException;
3642                                         }
3643                                         else
3644                                         {
3645                                             type = eSymbolTypeData;
3646                                         }
3647                                     }
3648                                     else
3649                                     if (symbol_sect_name && ::strstr (symbol_sect_name, "__IMPORT") == symbol_sect_name)
3650                                     {
3651                                         type = eSymbolTypeTrampoline;
3652                                     }
3653                                     else
3654                                     if (symbol_section->IsDescendant(objc_section_sp.get()))
3655                                     {
3656                                         type = eSymbolTypeRuntime;
3657                                         if (symbol_name && symbol_name[0] == '.')
3658                                         {
3659                                             llvm::StringRef symbol_name_ref(symbol_name);
3660                                             static const llvm::StringRef g_objc_v1_prefix_class (".objc_class_name_");
3661                                             if (symbol_name_ref.startswith(g_objc_v1_prefix_class))
3662                                             {
3663                                                 symbol_name_non_abi_mangled = symbol_name;
3664                                                 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
3665                                                 type = eSymbolTypeObjCClass;
3666                                                 demangled_is_synthesized = true;
3667                                             }
3668                                         }
3669                                     }
3670                                 }
3671                             }
3672                         }
3673                         break;
3674                     }
3675                 }
3676 
3677                 if (add_nlist)
3678                 {
3679                     uint64_t symbol_value = nlist.n_value;
3680 
3681                     if (symbol_name_non_abi_mangled)
3682                     {
3683                         sym[sym_idx].GetMangled().SetMangledName (ConstString(symbol_name_non_abi_mangled));
3684                         sym[sym_idx].GetMangled().SetDemangledName (ConstString(symbol_name));
3685                     }
3686                     else
3687                     {
3688                         bool symbol_name_is_mangled = false;
3689 
3690                         if (symbol_name && symbol_name[0] == '_')
3691                         {
3692                             symbol_name_is_mangled = symbol_name[1] == '_';
3693                             symbol_name++;  // Skip the leading underscore
3694                         }
3695 
3696                         if (symbol_name)
3697                         {
3698                             ConstString const_symbol_name(symbol_name);
3699                             sym[sym_idx].GetMangled().SetValue(const_symbol_name, symbol_name_is_mangled);
3700                             if (is_gsym && is_debug)
3701                             {
3702                                 N_GSYM_name_to_sym_idx[sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString()] = sym_idx;
3703                             }
3704                         }
3705                     }
3706                     if (symbol_section)
3707                     {
3708                         const addr_t section_file_addr = symbol_section->GetFileAddress();
3709                         if (symbol_byte_size == 0 && function_starts_count > 0)
3710                         {
3711                             addr_t symbol_lookup_file_addr = nlist.n_value;
3712                             // Do an exact address match for non-ARM addresses, else get the closest since
3713                             // the symbol might be a thumb symbol which has an address with bit zero set
3714                             FunctionStarts::Entry *func_start_entry = function_starts.FindEntry (symbol_lookup_file_addr, !is_arm);
3715                             if (is_arm && func_start_entry)
3716                             {
3717                                 // Verify that the function start address is the symbol address (ARM)
3718                                 // or the symbol address + 1 (thumb)
3719                                 if (func_start_entry->addr != symbol_lookup_file_addr &&
3720                                     func_start_entry->addr != (symbol_lookup_file_addr + 1))
3721                                 {
3722                                     // Not the right entry, NULL it out...
3723                                     func_start_entry = NULL;
3724                                 }
3725                             }
3726                             if (func_start_entry)
3727                             {
3728                                 func_start_entry->data = true;
3729 
3730                                 addr_t symbol_file_addr = func_start_entry->addr;
3731                                 if (is_arm)
3732                                     symbol_file_addr &= 0xfffffffffffffffeull;
3733 
3734                                 const FunctionStarts::Entry *next_func_start_entry = function_starts.FindNextEntry (func_start_entry);
3735                                 const addr_t section_end_file_addr = section_file_addr + symbol_section->GetByteSize();
3736                                 if (next_func_start_entry)
3737                                 {
3738                                     addr_t next_symbol_file_addr = next_func_start_entry->addr;
3739                                     // Be sure the clear the Thumb address bit when we calculate the size
3740                                     // from the current and next address
3741                                     if (is_arm)
3742                                         next_symbol_file_addr &= 0xfffffffffffffffeull;
3743                                     symbol_byte_size = std::min<lldb::addr_t>(next_symbol_file_addr - symbol_file_addr, section_end_file_addr - symbol_file_addr);
3744                                 }
3745                                 else
3746                                 {
3747                                     symbol_byte_size = section_end_file_addr - symbol_file_addr;
3748                                 }
3749                             }
3750                         }
3751                         symbol_value -= section_file_addr;
3752                     }
3753 
3754                     if (is_debug == false)
3755                     {
3756                         if (type == eSymbolTypeCode)
3757                         {
3758                             // See if we can find a N_FUN entry for any code symbols.
3759                             // If we do find a match, and the name matches, then we
3760                             // can merge the two into just the function symbol to avoid
3761                             // duplicate entries in the symbol table
3762                             std::pair<ValueToSymbolIndexMap::const_iterator, ValueToSymbolIndexMap::const_iterator> range;
3763                             range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
3764                             if (range.first != range.second)
3765                             {
3766                                 bool found_it = false;
3767                                 for (ValueToSymbolIndexMap::const_iterator pos = range.first; pos != range.second; ++pos)
3768                                 {
3769                                     if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled))
3770                                     {
3771                                         m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3772                                         // We just need the flags from the linker symbol, so put these flags
3773                                         // into the N_FUN flags to avoid duplicate symbols in the symbol table
3774                                         sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
3775                                         sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3776                                         if (resolver_addresses.find(nlist.n_value) != resolver_addresses.end())
3777                                             sym[pos->second].SetType (eSymbolTypeResolver);
3778                                         sym[sym_idx].Clear();
3779                                         found_it = true;
3780                                         break;
3781                                     }
3782                                 }
3783                                 if (found_it)
3784                                     continue;
3785                             }
3786                             else
3787                             {
3788                                 if (resolver_addresses.find(nlist.n_value) != resolver_addresses.end())
3789                                     type = eSymbolTypeResolver;
3790                             }
3791                         }
3792                         else if (type == eSymbolTypeData)
3793                         {
3794                             // See if we can find a N_STSYM entry for any data symbols.
3795                             // If we do find a match, and the name matches, then we
3796                             // can merge the two into just the Static symbol to avoid
3797                             // duplicate entries in the symbol table
3798                             std::pair<ValueToSymbolIndexMap::const_iterator, ValueToSymbolIndexMap::const_iterator> range;
3799                             range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
3800                             if (range.first != range.second)
3801                             {
3802                                 bool found_it = false;
3803                                 for (ValueToSymbolIndexMap::const_iterator pos = range.first; pos != range.second; ++pos)
3804                                 {
3805                                     if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled))
3806                                     {
3807                                         m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3808                                         // We just need the flags from the linker symbol, so put these flags
3809                                         // into the N_STSYM flags to avoid duplicate symbols in the symbol table
3810                                         sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
3811                                         sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3812                                         sym[sym_idx].Clear();
3813                                         found_it = true;
3814                                         break;
3815                                     }
3816                                 }
3817                                 if (found_it)
3818                                     continue;
3819                             }
3820                             else
3821                             {
3822                                 // Combine N_GSYM stab entries with the non stab symbol
3823                                 ConstNameToSymbolIndexMap::const_iterator pos = N_GSYM_name_to_sym_idx.find(sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString());
3824                                 if (pos != N_GSYM_name_to_sym_idx.end())
3825                                 {
3826                                     const uint32_t GSYM_sym_idx = pos->second;
3827                                     m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
3828                                     // Copy the address, because often the N_GSYM address has an invalid address of zero
3829                                     // when the global is a common symbol
3830                                     sym[GSYM_sym_idx].GetAddress().SetSection (symbol_section);
3831                                     sym[GSYM_sym_idx].GetAddress().SetOffset (symbol_value);
3832                                     // We just need the flags from the linker symbol, so put these flags
3833                                     // into the N_STSYM flags to avoid duplicate symbols in the symbol table
3834                                     sym[GSYM_sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3835                                     sym[sym_idx].Clear();
3836                                     continue;
3837                                 }
3838                             }
3839                         }
3840                     }
3841 
3842                     sym[sym_idx].SetID (nlist_idx);
3843                     sym[sym_idx].SetType (type);
3844                     sym[sym_idx].GetAddress().SetSection (symbol_section);
3845                     sym[sym_idx].GetAddress().SetOffset (symbol_value);
3846                     sym[sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc);
3847 
3848                     if (symbol_byte_size > 0)
3849                         sym[sym_idx].SetByteSize(symbol_byte_size);
3850 
3851                     if (demangled_is_synthesized)
3852                         sym[sym_idx].SetDemangledNameIsSynthesized(true);
3853 
3854                     ++sym_idx;
3855                 }
3856                 else
3857                 {
3858                     sym[sym_idx].Clear();
3859                 }
3860             }
3861         }
3862 
3863         uint32_t synthetic_sym_id = symtab_load_command.nsyms;
3864 
3865         if (function_starts_count > 0)
3866         {
3867             char synthetic_function_symbol[PATH_MAX];
3868             uint32_t num_synthetic_function_symbols = 0;
3869             for (i=0; i<function_starts_count; ++i)
3870             {
3871                 if (function_starts.GetEntryRef (i).data == false)
3872                     ++num_synthetic_function_symbols;
3873             }
3874 
3875             if (num_synthetic_function_symbols > 0)
3876             {
3877                 if (num_syms < sym_idx + num_synthetic_function_symbols)
3878                 {
3879                     num_syms = sym_idx + num_synthetic_function_symbols;
3880                     sym = symtab->Resize (num_syms);
3881                 }
3882                 uint32_t synthetic_function_symbol_idx = 0;
3883                 for (i=0; i<function_starts_count; ++i)
3884                 {
3885                     const FunctionStarts::Entry *func_start_entry = function_starts.GetEntryAtIndex (i);
3886                     if (func_start_entry->data == false)
3887                     {
3888                         addr_t symbol_file_addr = func_start_entry->addr;
3889                         uint32_t symbol_flags = 0;
3890                         if (is_arm)
3891                         {
3892                             if (symbol_file_addr & 1)
3893                                 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3894                             symbol_file_addr &= 0xfffffffffffffffeull;
3895                         }
3896                         Address symbol_addr;
3897                         if (module_sp->ResolveFileAddress (symbol_file_addr, symbol_addr))
3898                         {
3899                             SectionSP symbol_section (symbol_addr.GetSection());
3900                             uint32_t symbol_byte_size = 0;
3901                             if (symbol_section)
3902                             {
3903                                 const addr_t section_file_addr = symbol_section->GetFileAddress();
3904                                 const FunctionStarts::Entry *next_func_start_entry = function_starts.FindNextEntry (func_start_entry);
3905                                 const addr_t section_end_file_addr = section_file_addr + symbol_section->GetByteSize();
3906                                 if (next_func_start_entry)
3907                                 {
3908                                     addr_t next_symbol_file_addr = next_func_start_entry->addr;
3909                                     if (is_arm)
3910                                         next_symbol_file_addr &= 0xfffffffffffffffeull;
3911                                     symbol_byte_size = std::min<lldb::addr_t>(next_symbol_file_addr - symbol_file_addr, section_end_file_addr - symbol_file_addr);
3912                                 }
3913                                 else
3914                                 {
3915                                     symbol_byte_size = section_end_file_addr - symbol_file_addr;
3916                                 }
3917                                 snprintf (synthetic_function_symbol,
3918                                           sizeof(synthetic_function_symbol),
3919                                           "___lldb_unnamed_function%u$$%s",
3920                                           ++synthetic_function_symbol_idx,
3921                                           module_sp->GetFileSpec().GetFilename().GetCString());
3922                                 sym[sym_idx].SetID (synthetic_sym_id++);
3923                                 sym[sym_idx].GetMangled().SetDemangledName(ConstString(synthetic_function_symbol));
3924                                 sym[sym_idx].SetType (eSymbolTypeCode);
3925                                 sym[sym_idx].SetIsSynthetic (true);
3926                                 sym[sym_idx].GetAddress() = symbol_addr;
3927                                 if (symbol_flags)
3928                                     sym[sym_idx].SetFlags (symbol_flags);
3929                                 if (symbol_byte_size)
3930                                     sym[sym_idx].SetByteSize (symbol_byte_size);
3931                                 ++sym_idx;
3932                             }
3933                         }
3934                     }
3935                 }
3936             }
3937         }
3938 
3939         // Trim our symbols down to just what we ended up with after
3940         // removing any symbols.
3941         if (sym_idx < num_syms)
3942         {
3943             num_syms = sym_idx;
3944             sym = symtab->Resize (num_syms);
3945         }
3946 
3947         // Now synthesize indirect symbols
3948         if (m_dysymtab.nindirectsyms != 0)
3949         {
3950             if (indirect_symbol_index_data.GetByteSize())
3951             {
3952                 NListIndexToSymbolIndexMap::const_iterator end_index_pos = m_nlist_idx_to_sym_idx.end();
3953 
3954                 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size(); ++sect_idx)
3955                 {
3956                     if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) == S_SYMBOL_STUBS)
3957                     {
3958                         uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2;
3959                         if (symbol_stub_byte_size == 0)
3960                             continue;
3961 
3962                         const uint32_t num_symbol_stubs = m_mach_sections[sect_idx].size / symbol_stub_byte_size;
3963 
3964                         if (num_symbol_stubs == 0)
3965                             continue;
3966 
3967                         const uint32_t symbol_stub_index_offset = m_mach_sections[sect_idx].reserved1;
3968                         for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx)
3969                         {
3970                             const uint32_t symbol_stub_index = symbol_stub_index_offset + stub_idx;
3971                             const lldb::addr_t symbol_stub_addr = m_mach_sections[sect_idx].addr + (stub_idx * symbol_stub_byte_size);
3972                             lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
3973                             if (indirect_symbol_index_data.ValidOffsetForDataOfSize(symbol_stub_offset, 4))
3974                             {
3975                                 const uint32_t stub_sym_id = indirect_symbol_index_data.GetU32 (&symbol_stub_offset);
3976                                 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
3977                                     continue;
3978 
3979                                 NListIndexToSymbolIndexMap::const_iterator index_pos = m_nlist_idx_to_sym_idx.find (stub_sym_id);
3980                                 Symbol *stub_symbol = NULL;
3981                                 if (index_pos != end_index_pos)
3982                                 {
3983                                     // We have a remapping from the original nlist index to
3984                                     // a current symbol index, so just look this up by index
3985                                     stub_symbol = symtab->SymbolAtIndex (index_pos->second);
3986                                 }
3987                                 else
3988                                 {
3989                                     // We need to lookup a symbol using the original nlist
3990                                     // symbol index since this index is coming from the
3991                                     // S_SYMBOL_STUBS
3992                                     stub_symbol = symtab->FindSymbolByID (stub_sym_id);
3993                                 }
3994 
3995                                 if (stub_symbol)
3996                                 {
3997                                     Address so_addr(symbol_stub_addr, section_list);
3998 
3999                                     if (stub_symbol->GetType() == eSymbolTypeUndefined)
4000                                     {
4001                                         // Change the external symbol into a trampoline that makes sense
4002                                         // These symbols were N_UNDF N_EXT, and are useless to us, so we
4003                                         // can re-use them so we don't have to make up a synthetic symbol
4004                                         // for no good reason.
4005                                         if (resolver_addresses.find(symbol_stub_addr) == resolver_addresses.end())
4006                                             stub_symbol->SetType (eSymbolTypeTrampoline);
4007                                         else
4008                                             stub_symbol->SetType (eSymbolTypeResolver);
4009                                         stub_symbol->SetExternal (false);
4010                                         stub_symbol->GetAddress() = so_addr;
4011                                         stub_symbol->SetByteSize (symbol_stub_byte_size);
4012                                     }
4013                                     else
4014                                     {
4015                                         // Make a synthetic symbol to describe the trampoline stub
4016                                         Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4017                                         if (sym_idx >= num_syms)
4018                                         {
4019                                             sym = symtab->Resize (++num_syms);
4020                                             stub_symbol = NULL;  // this pointer no longer valid
4021                                         }
4022                                         sym[sym_idx].SetID (synthetic_sym_id++);
4023                                         sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4024                                         if (resolver_addresses.find(symbol_stub_addr) == resolver_addresses.end())
4025                                             sym[sym_idx].SetType (eSymbolTypeTrampoline);
4026                                         else
4027                                             sym[sym_idx].SetType (eSymbolTypeResolver);
4028                                         sym[sym_idx].SetIsSynthetic (true);
4029                                         sym[sym_idx].GetAddress() = so_addr;
4030                                         sym[sym_idx].SetByteSize (symbol_stub_byte_size);
4031                                         ++sym_idx;
4032                                     }
4033                                 }
4034                                 else
4035                                 {
4036                                     if (log)
4037                                         log->Warning ("symbol stub referencing symbol table symbol %u that isn't in our minimal symbol table, fix this!!!", stub_sym_id);
4038                                 }
4039                             }
4040                         }
4041                     }
4042                 }
4043             }
4044         }
4045 
4046 
4047         if (!trie_entries.empty())
4048         {
4049             for (const auto &e : trie_entries)
4050             {
4051                 if (e.entry.import_name)
4052                 {
4053                     // Make a synthetic symbol to describe re-exported symbol.
4054                     if (sym_idx >= num_syms)
4055                         sym = symtab->Resize (++num_syms);
4056                     sym[sym_idx].SetID (synthetic_sym_id++);
4057                     sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4058                     sym[sym_idx].SetType (eSymbolTypeReExported);
4059                     sym[sym_idx].SetIsSynthetic (true);
4060                     sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4061                     if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize())
4062                     {
4063                         sym[sym_idx].SetReExportedSymbolSharedLibrary(dylib_files.GetFileSpecAtIndex(e.entry.other-1));
4064                     }
4065                     ++sym_idx;
4066                 }
4067             }
4068         }
4069 
4070 
4071 
4072 //        StreamFile s(stdout, false);
4073 //        s.Printf ("Symbol table before CalculateSymbolSizes():\n");
4074 //        symtab->Dump(&s, NULL, eSortOrderNone);
4075         // Set symbol byte sizes correctly since mach-o nlist entries don't have sizes
4076         symtab->CalculateSymbolSizes();
4077 
4078 //        s.Printf ("Symbol table after CalculateSymbolSizes():\n");
4079 //        symtab->Dump(&s, NULL, eSortOrderNone);
4080 
4081         return symtab->GetNumSymbols();
4082     }
4083     return 0;
4084 }
4085 
4086 
4087 void
4088 ObjectFileMachO::Dump (Stream *s)
4089 {
4090     ModuleSP module_sp(GetModule());
4091     if (module_sp)
4092     {
4093         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4094         s->Printf("%p: ", static_cast<void*>(this));
4095         s->Indent();
4096         if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4097             s->PutCString("ObjectFileMachO64");
4098         else
4099             s->PutCString("ObjectFileMachO32");
4100 
4101         ArchSpec header_arch(eArchTypeMachO, m_header.cputype, m_header.cpusubtype);
4102 
4103         *s << ", file = '" << m_file << "', arch = " << header_arch.GetArchitectureName() << "\n";
4104 
4105         SectionList *sections = GetSectionList();
4106         if (sections)
4107             sections->Dump(s, NULL, true, UINT32_MAX);
4108 
4109         if (m_symtab_ap.get())
4110             m_symtab_ap->Dump(s, NULL, eSortOrderNone);
4111     }
4112 }
4113 
4114 bool
4115 ObjectFileMachO::GetUUID (const llvm::MachO::mach_header &header,
4116                           const lldb_private::DataExtractor &data,
4117                           lldb::offset_t lc_offset,
4118                           lldb_private::UUID& uuid)
4119 {
4120     uint32_t i;
4121     struct uuid_command load_cmd;
4122 
4123     lldb::offset_t offset = lc_offset;
4124     for (i=0; i<header.ncmds; ++i)
4125     {
4126         const lldb::offset_t cmd_offset = offset;
4127         if (data.GetU32(&offset, &load_cmd, 2) == NULL)
4128             break;
4129 
4130         if (load_cmd.cmd == LC_UUID)
4131         {
4132             const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4133 
4134             if (uuid_bytes)
4135             {
4136                 // OpenCL on Mac OS X uses the same UUID for each of its object files.
4137                 // We pretend these object files have no UUID to prevent crashing.
4138 
4139                 const uint8_t opencl_uuid[] = { 0x8c, 0x8e, 0xb3, 0x9b,
4140                     0x3b, 0xa8,
4141                     0x4b, 0x16,
4142                     0xb6, 0xa4,
4143                     0x27, 0x63, 0xbb, 0x14, 0xf0, 0x0d };
4144 
4145                 if (!memcmp(uuid_bytes, opencl_uuid, 16))
4146                     return false;
4147 
4148                 uuid.SetBytes (uuid_bytes);
4149                 return true;
4150             }
4151             return false;
4152         }
4153         offset = cmd_offset + load_cmd.cmdsize;
4154     }
4155     return false;
4156 }
4157 
4158 bool
4159 ObjectFileMachO::GetUUID (lldb_private::UUID* uuid)
4160 {
4161     ModuleSP module_sp(GetModule());
4162     if (module_sp)
4163     {
4164         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4165         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4166         return GetUUID (m_header, m_data, offset, *uuid);
4167     }
4168     return false;
4169 }
4170 
4171 
4172 uint32_t
4173 ObjectFileMachO::GetDependentModules (FileSpecList& files)
4174 {
4175     uint32_t count = 0;
4176     ModuleSP module_sp(GetModule());
4177     if (module_sp)
4178     {
4179         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4180         struct load_command load_cmd;
4181         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4182         const bool resolve_path = false; // Don't resolve the dependend file paths since they may not reside on this system
4183         uint32_t i;
4184         for (i=0; i<m_header.ncmds; ++i)
4185         {
4186             const uint32_t cmd_offset = offset;
4187             if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
4188                 break;
4189 
4190             switch (load_cmd.cmd)
4191             {
4192             case LC_LOAD_DYLIB:
4193             case LC_LOAD_WEAK_DYLIB:
4194             case LC_REEXPORT_DYLIB:
4195             case LC_LOAD_DYLINKER:
4196             case LC_LOADFVMLIB:
4197             case LC_LOAD_UPWARD_DYLIB:
4198                 {
4199                     uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
4200                     const char *path = m_data.PeekCStr(name_offset);
4201                     // Skip any path that starts with '@' since these are usually:
4202                     // @executable_path/.../file
4203                     // @rpath/.../file
4204                     if (path && path[0] != '@')
4205                     {
4206                         FileSpec file_spec(path, resolve_path);
4207                         if (files.AppendIfUnique(file_spec))
4208                             count++;
4209                     }
4210                 }
4211                 break;
4212 
4213             default:
4214                 break;
4215             }
4216             offset = cmd_offset + load_cmd.cmdsize;
4217         }
4218     }
4219     return count;
4220 }
4221 
4222 lldb_private::Address
4223 ObjectFileMachO::GetEntryPointAddress ()
4224 {
4225     // If the object file is not an executable it can't hold the entry point.  m_entry_point_address
4226     // is initialized to an invalid address, so we can just return that.
4227     // If m_entry_point_address is valid it means we've found it already, so return the cached value.
4228 
4229     if (!IsExecutable() || m_entry_point_address.IsValid())
4230         return m_entry_point_address;
4231 
4232     // Otherwise, look for the UnixThread or Thread command.  The data for the Thread command is given in
4233     // /usr/include/mach-o.h, but it is basically:
4234     //
4235     //  uint32_t flavor  - this is the flavor argument you would pass to thread_get_state
4236     //  uint32_t count   - this is the count of longs in the thread state data
4237     //  struct XXX_thread_state state - this is the structure from <machine/thread_status.h> corresponding to the flavor.
4238     //  <repeat this trio>
4239     //
4240     // So we just keep reading the various register flavors till we find the GPR one, then read the PC out of there.
4241     // FIXME: We will need to have a "RegisterContext data provider" class at some point that can get all the registers
4242     // out of data in this form & attach them to a given thread.  That should underlie the MacOS X User process plugin,
4243     // and we'll also need it for the MacOS X Core File process plugin.  When we have that we can also use it here.
4244     //
4245     // For now we hard-code the offsets and flavors we need:
4246     //
4247     //
4248 
4249     ModuleSP module_sp(GetModule());
4250     if (module_sp)
4251     {
4252         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4253         struct load_command load_cmd;
4254         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4255         uint32_t i;
4256         lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
4257         bool done = false;
4258 
4259         for (i=0; i<m_header.ncmds; ++i)
4260         {
4261             const lldb::offset_t cmd_offset = offset;
4262             if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
4263                 break;
4264 
4265             switch (load_cmd.cmd)
4266             {
4267             case LC_UNIXTHREAD:
4268             case LC_THREAD:
4269                 {
4270                     while (offset < cmd_offset + load_cmd.cmdsize)
4271                     {
4272                         uint32_t flavor = m_data.GetU32(&offset);
4273                         uint32_t count = m_data.GetU32(&offset);
4274                         if (count == 0)
4275                         {
4276                             // We've gotten off somehow, log and exit;
4277                             return m_entry_point_address;
4278                         }
4279 
4280                         switch (m_header.cputype)
4281                         {
4282                         case llvm::MachO::CPU_TYPE_ARM:
4283                            if (flavor == 1) // ARM_THREAD_STATE from mach/arm/thread_status.h
4284                            {
4285                                offset += 60;  // This is the offset of pc in the GPR thread state data structure.
4286                                start_address = m_data.GetU32(&offset);
4287                                done = true;
4288                             }
4289                         break;
4290                         case llvm::MachO::CPU_TYPE_ARM64:
4291                            if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
4292                            {
4293                                offset += 256;  // This is the offset of pc in the GPR thread state data structure.
4294                                start_address = m_data.GetU64(&offset);
4295                                done = true;
4296                             }
4297                         break;
4298                         case llvm::MachO::CPU_TYPE_I386:
4299                            if (flavor == 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h
4300                            {
4301                                offset += 40;  // This is the offset of eip in the GPR thread state data structure.
4302                                start_address = m_data.GetU32(&offset);
4303                                done = true;
4304                             }
4305                         break;
4306                         case llvm::MachO::CPU_TYPE_X86_64:
4307                            if (flavor == 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
4308                            {
4309                                offset += 16 * 8;  // This is the offset of rip in the GPR thread state data structure.
4310                                start_address = m_data.GetU64(&offset);
4311                                done = true;
4312                             }
4313                         break;
4314                         default:
4315                             return m_entry_point_address;
4316                         }
4317                         // Haven't found the GPR flavor yet, skip over the data for this flavor:
4318                         if (done)
4319                             break;
4320                         offset += count * 4;
4321                     }
4322                 }
4323                 break;
4324             case LC_MAIN:
4325                 {
4326                     ConstString text_segment_name ("__TEXT");
4327                     uint64_t entryoffset = m_data.GetU64(&offset);
4328                     SectionSP text_segment_sp = GetSectionList()->FindSectionByName(text_segment_name);
4329                     if (text_segment_sp)
4330                     {
4331                         done = true;
4332                         start_address = text_segment_sp->GetFileAddress() + entryoffset;
4333                     }
4334                 }
4335 
4336             default:
4337                 break;
4338             }
4339             if (done)
4340                 break;
4341 
4342             // Go to the next load command:
4343             offset = cmd_offset + load_cmd.cmdsize;
4344         }
4345 
4346         if (start_address != LLDB_INVALID_ADDRESS)
4347         {
4348             // We got the start address from the load commands, so now resolve that address in the sections
4349             // of this ObjectFile:
4350             if (!m_entry_point_address.ResolveAddressUsingFileSections (start_address, GetSectionList()))
4351             {
4352                 m_entry_point_address.Clear();
4353             }
4354         }
4355         else
4356         {
4357             // We couldn't read the UnixThread load command - maybe it wasn't there.  As a fallback look for the
4358             // "start" symbol in the main executable.
4359 
4360             ModuleSP module_sp (GetModule());
4361 
4362             if (module_sp)
4363             {
4364                 SymbolContextList contexts;
4365                 SymbolContext context;
4366                 if (module_sp->FindSymbolsWithNameAndType(ConstString ("start"), eSymbolTypeCode, contexts))
4367                 {
4368                     if (contexts.GetContextAtIndex(0, context))
4369                         m_entry_point_address = context.symbol->GetAddress();
4370                 }
4371             }
4372         }
4373     }
4374 
4375     return m_entry_point_address;
4376 
4377 }
4378 
4379 lldb_private::Address
4380 ObjectFileMachO::GetHeaderAddress ()
4381 {
4382     lldb_private::Address header_addr;
4383     SectionList *section_list = GetSectionList();
4384     if (section_list)
4385     {
4386         SectionSP text_segment_sp (section_list->FindSectionByName (GetSegmentNameTEXT()));
4387         if (text_segment_sp)
4388         {
4389             header_addr.SetSection (text_segment_sp);
4390             header_addr.SetOffset (0);
4391         }
4392     }
4393     return header_addr;
4394 }
4395 
4396 uint32_t
4397 ObjectFileMachO::GetNumThreadContexts ()
4398 {
4399     ModuleSP module_sp(GetModule());
4400     if (module_sp)
4401     {
4402         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4403         if (!m_thread_context_offsets_valid)
4404         {
4405             m_thread_context_offsets_valid = true;
4406             lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4407             FileRangeArray::Entry file_range;
4408             thread_command thread_cmd;
4409             for (uint32_t i=0; i<m_header.ncmds; ++i)
4410             {
4411                 const uint32_t cmd_offset = offset;
4412                 if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL)
4413                     break;
4414 
4415                 if (thread_cmd.cmd == LC_THREAD)
4416                 {
4417                     file_range.SetRangeBase (offset);
4418                     file_range.SetByteSize (thread_cmd.cmdsize - 8);
4419                     m_thread_context_offsets.Append (file_range);
4420                 }
4421                 offset = cmd_offset + thread_cmd.cmdsize;
4422             }
4423         }
4424     }
4425     return m_thread_context_offsets.GetSize();
4426 }
4427 
4428 lldb::RegisterContextSP
4429 ObjectFileMachO::GetThreadContextAtIndex (uint32_t idx, lldb_private::Thread &thread)
4430 {
4431     lldb::RegisterContextSP reg_ctx_sp;
4432 
4433     ModuleSP module_sp(GetModule());
4434     if (module_sp)
4435     {
4436         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4437         if (!m_thread_context_offsets_valid)
4438             GetNumThreadContexts ();
4439 
4440         const FileRangeArray::Entry *thread_context_file_range = m_thread_context_offsets.GetEntryAtIndex (idx);
4441         if (thread_context_file_range)
4442         {
4443 
4444             DataExtractor data (m_data,
4445                                 thread_context_file_range->GetRangeBase(),
4446                                 thread_context_file_range->GetByteSize());
4447 
4448             switch (m_header.cputype)
4449             {
4450                 case llvm::MachO::CPU_TYPE_ARM64:
4451                     reg_ctx_sp.reset (new RegisterContextDarwin_arm64_Mach (thread, data));
4452                     break;
4453 
4454                 case llvm::MachO::CPU_TYPE_ARM:
4455                     reg_ctx_sp.reset (new RegisterContextDarwin_arm_Mach (thread, data));
4456                     break;
4457 
4458                 case llvm::MachO::CPU_TYPE_I386:
4459                     reg_ctx_sp.reset (new RegisterContextDarwin_i386_Mach (thread, data));
4460                     break;
4461 
4462                 case llvm::MachO::CPU_TYPE_X86_64:
4463                     reg_ctx_sp.reset (new RegisterContextDarwin_x86_64_Mach (thread, data));
4464                     break;
4465             }
4466         }
4467     }
4468     return reg_ctx_sp;
4469 }
4470 
4471 
4472 ObjectFile::Type
4473 ObjectFileMachO::CalculateType()
4474 {
4475     switch (m_header.filetype)
4476     {
4477         case MH_OBJECT:                                         // 0x1u
4478             if (GetAddressByteSize () == 4)
4479             {
4480                 // 32 bit kexts are just object files, but they do have a valid
4481                 // UUID load command.
4482                 UUID uuid;
4483                 if (GetUUID(&uuid))
4484                 {
4485                     // this checking for the UUID load command is not enough
4486                     // we could eventually look for the symbol named
4487                     // "OSKextGetCurrentIdentifier" as this is required of kexts
4488                     if (m_strata == eStrataInvalid)
4489                         m_strata = eStrataKernel;
4490                     return eTypeSharedLibrary;
4491                 }
4492             }
4493             return eTypeObjectFile;
4494 
4495         case MH_EXECUTE:            return eTypeExecutable;     // 0x2u
4496         case MH_FVMLIB:             return eTypeSharedLibrary;  // 0x3u
4497         case MH_CORE:               return eTypeCoreFile;       // 0x4u
4498         case MH_PRELOAD:            return eTypeSharedLibrary;  // 0x5u
4499         case MH_DYLIB:              return eTypeSharedLibrary;  // 0x6u
4500         case MH_DYLINKER:           return eTypeDynamicLinker;  // 0x7u
4501         case MH_BUNDLE:             return eTypeSharedLibrary;  // 0x8u
4502         case MH_DYLIB_STUB:         return eTypeStubLibrary;    // 0x9u
4503         case MH_DSYM:               return eTypeDebugInfo;      // 0xAu
4504         case MH_KEXT_BUNDLE:        return eTypeSharedLibrary;  // 0xBu
4505         default:
4506             break;
4507     }
4508     return eTypeUnknown;
4509 }
4510 
4511 ObjectFile::Strata
4512 ObjectFileMachO::CalculateStrata()
4513 {
4514     switch (m_header.filetype)
4515     {
4516         case MH_OBJECT:                                  // 0x1u
4517             {
4518                 // 32 bit kexts are just object files, but they do have a valid
4519                 // UUID load command.
4520                 UUID uuid;
4521                 if (GetUUID(&uuid))
4522                 {
4523                     // this checking for the UUID load command is not enough
4524                     // we could eventually look for the symbol named
4525                     // "OSKextGetCurrentIdentifier" as this is required of kexts
4526                     if (m_type == eTypeInvalid)
4527                         m_type = eTypeSharedLibrary;
4528 
4529                     return eStrataKernel;
4530                 }
4531             }
4532             return eStrataUnknown;
4533 
4534         case MH_EXECUTE:                                 // 0x2u
4535             // Check for the MH_DYLDLINK bit in the flags
4536             if (m_header.flags & MH_DYLDLINK)
4537             {
4538                 return eStrataUser;
4539             }
4540             else
4541             {
4542                 SectionList *section_list = GetSectionList();
4543                 if (section_list)
4544                 {
4545                     static ConstString g_kld_section_name ("__KLD");
4546                     if (section_list->FindSectionByName(g_kld_section_name))
4547                         return eStrataKernel;
4548                 }
4549             }
4550             return eStrataRawImage;
4551 
4552         case MH_FVMLIB:      return eStrataUser;         // 0x3u
4553         case MH_CORE:        return eStrataUnknown;      // 0x4u
4554         case MH_PRELOAD:     return eStrataRawImage;     // 0x5u
4555         case MH_DYLIB:       return eStrataUser;         // 0x6u
4556         case MH_DYLINKER:    return eStrataUser;         // 0x7u
4557         case MH_BUNDLE:      return eStrataUser;         // 0x8u
4558         case MH_DYLIB_STUB:  return eStrataUser;         // 0x9u
4559         case MH_DSYM:        return eStrataUnknown;      // 0xAu
4560         case MH_KEXT_BUNDLE: return eStrataKernel;       // 0xBu
4561         default:
4562             break;
4563     }
4564     return eStrataUnknown;
4565 }
4566 
4567 
4568 uint32_t
4569 ObjectFileMachO::GetVersion (uint32_t *versions, uint32_t num_versions)
4570 {
4571     ModuleSP module_sp(GetModule());
4572     if (module_sp)
4573     {
4574         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4575         struct dylib_command load_cmd;
4576         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4577         uint32_t version_cmd = 0;
4578         uint64_t version = 0;
4579         uint32_t i;
4580         for (i=0; i<m_header.ncmds; ++i)
4581         {
4582             const lldb::offset_t cmd_offset = offset;
4583             if (m_data.GetU32(&offset, &load_cmd, 2) == NULL)
4584                 break;
4585 
4586             if (load_cmd.cmd == LC_ID_DYLIB)
4587             {
4588                 if (version_cmd == 0)
4589                 {
4590                     version_cmd = load_cmd.cmd;
4591                     if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL)
4592                         break;
4593                     version = load_cmd.dylib.current_version;
4594                 }
4595                 break; // Break for now unless there is another more complete version
4596                        // number load command in the future.
4597             }
4598             offset = cmd_offset + load_cmd.cmdsize;
4599         }
4600 
4601         if (version_cmd == LC_ID_DYLIB)
4602         {
4603             if (versions != NULL && num_versions > 0)
4604             {
4605                 if (num_versions > 0)
4606                     versions[0] = (version & 0xFFFF0000ull) >> 16;
4607                 if (num_versions > 1)
4608                     versions[1] = (version & 0x0000FF00ull) >> 8;
4609                 if (num_versions > 2)
4610                     versions[2] = (version & 0x000000FFull);
4611                 // Fill in an remaining version numbers with invalid values
4612                 for (i=3; i<num_versions; ++i)
4613                     versions[i] = UINT32_MAX;
4614             }
4615             // The LC_ID_DYLIB load command has a version with 3 version numbers
4616             // in it, so always return 3
4617             return 3;
4618         }
4619     }
4620     return false;
4621 }
4622 
4623 bool
4624 ObjectFileMachO::GetArchitecture (ArchSpec &arch)
4625 {
4626     ModuleSP module_sp(GetModule());
4627     if (module_sp)
4628     {
4629         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
4630         arch.SetArchitecture (eArchTypeMachO, m_header.cputype, m_header.cpusubtype);
4631 
4632         // Files with type MH_PRELOAD are currently used in cases where the image
4633         // debugs at the addresses in the file itself. Below we set the OS to
4634         // unknown to make sure we use the DynamicLoaderStatic()...
4635         if (m_header.filetype == MH_PRELOAD)
4636         {
4637             arch.GetTriple().setOS (llvm::Triple::UnknownOS);
4638         }
4639         return true;
4640     }
4641     return false;
4642 }
4643 
4644 
4645 UUID
4646 ObjectFileMachO::GetProcessSharedCacheUUID (Process *process)
4647 {
4648     UUID uuid;
4649     if (process)
4650     {
4651         addr_t all_image_infos = process->GetImageInfoAddress();
4652 
4653         // The address returned by GetImageInfoAddress may be the address of dyld (don't want)
4654         // or it may be the address of the dyld_all_image_infos structure (want).  The first four
4655         // bytes will be either the version field (all_image_infos) or a Mach-O file magic constant.
4656         // Version 13 and higher of dyld_all_image_infos is required to get the sharedCacheUUID field.
4657 
4658         Error err;
4659         uint32_t version_or_magic = process->ReadUnsignedIntegerFromMemory (all_image_infos, 4, -1, err);
4660         if (version_or_magic != static_cast<uint32_t>(-1)
4661             && version_or_magic != MH_MAGIC
4662             && version_or_magic != MH_CIGAM
4663             && version_or_magic != MH_MAGIC_64
4664             && version_or_magic != MH_CIGAM_64
4665             && version_or_magic >= 13)
4666         {
4667             addr_t sharedCacheUUID_address = LLDB_INVALID_ADDRESS;
4668             int wordsize = process->GetAddressByteSize();
4669             if (wordsize == 8)
4670             {
4671                 sharedCacheUUID_address = all_image_infos + 160;  // sharedCacheUUID <mach-o/dyld_images.h>
4672             }
4673             if (wordsize == 4)
4674             {
4675                 sharedCacheUUID_address = all_image_infos + 84;   // sharedCacheUUID <mach-o/dyld_images.h>
4676             }
4677             if (sharedCacheUUID_address != LLDB_INVALID_ADDRESS)
4678             {
4679                 uuid_t shared_cache_uuid;
4680                 if (process->ReadMemory (sharedCacheUUID_address, shared_cache_uuid, sizeof (uuid_t), err) == sizeof (uuid_t))
4681                 {
4682                     uuid.SetBytes (shared_cache_uuid);
4683                 }
4684             }
4685         }
4686     }
4687     return uuid;
4688 }
4689 
4690 UUID
4691 ObjectFileMachO::GetLLDBSharedCacheUUID ()
4692 {
4693     UUID uuid;
4694 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__))
4695     uint8_t *(*dyld_get_all_image_infos)(void);
4696     dyld_get_all_image_infos = (uint8_t*(*)()) dlsym (RTLD_DEFAULT, "_dyld_get_all_image_infos");
4697     if (dyld_get_all_image_infos)
4698     {
4699         uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
4700         if (dyld_all_image_infos_address)
4701         {
4702             uint32_t *version = (uint32_t*) dyld_all_image_infos_address;              // version <mach-o/dyld_images.h>
4703             if (*version >= 13)
4704             {
4705                 uuid_t *sharedCacheUUID_address = 0;
4706                 int wordsize = sizeof (uint8_t *);
4707                 if (wordsize == 8)
4708                 {
4709                     sharedCacheUUID_address = (uuid_t*) ((uint8_t*) dyld_all_image_infos_address + 160); // sharedCacheUUID <mach-o/dyld_images.h>
4710                 }
4711                 else
4712                 {
4713                     sharedCacheUUID_address = (uuid_t*) ((uint8_t*) dyld_all_image_infos_address + 84);  // sharedCacheUUID <mach-o/dyld_images.h>
4714                 }
4715                 uuid.SetBytes (sharedCacheUUID_address);
4716             }
4717         }
4718     }
4719 #endif
4720     return uuid;
4721 }
4722 
4723 uint32_t
4724 ObjectFileMachO::GetMinimumOSVersion (uint32_t *versions, uint32_t num_versions)
4725 {
4726     if (m_min_os_versions.empty())
4727     {
4728         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4729         bool success = false;
4730         for (uint32_t i=0; success == false && i < m_header.ncmds; ++i)
4731         {
4732             const lldb::offset_t load_cmd_offset = offset;
4733 
4734             version_min_command lc;
4735             if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
4736                 break;
4737             if (lc.cmd == LC_VERSION_MIN_MACOSX || lc.cmd == LC_VERSION_MIN_IPHONEOS)
4738             {
4739                 if (m_data.GetU32 (&offset, &lc.version, (sizeof(lc) / sizeof(uint32_t)) - 2))
4740                 {
4741                     const uint32_t xxxx = lc.version >> 16;
4742                     const uint32_t yy = (lc.version >> 8) & 0xffu;
4743                     const uint32_t zz = lc.version  & 0xffu;
4744                     if (xxxx)
4745                     {
4746                         m_min_os_versions.push_back(xxxx);
4747                         if (yy)
4748                         {
4749                             m_min_os_versions.push_back(yy);
4750                             if (zz)
4751                                 m_min_os_versions.push_back(zz);
4752                         }
4753                     }
4754                     success = true;
4755                 }
4756             }
4757             offset = load_cmd_offset + lc.cmdsize;
4758         }
4759 
4760         if (success == false)
4761         {
4762             // Push an invalid value so we don't keep trying to
4763             m_min_os_versions.push_back(UINT32_MAX);
4764         }
4765     }
4766 
4767     if (m_min_os_versions.size() > 1 || m_min_os_versions[0] != UINT32_MAX)
4768     {
4769         if (versions != NULL && num_versions > 0)
4770         {
4771             for (size_t i=0; i<num_versions; ++i)
4772             {
4773                 if (i < m_min_os_versions.size())
4774                     versions[i] = m_min_os_versions[i];
4775                 else
4776                     versions[i] = 0;
4777             }
4778         }
4779         return m_min_os_versions.size();
4780     }
4781     // Call the superclasses version that will empty out the data
4782     return ObjectFile::GetMinimumOSVersion (versions, num_versions);
4783 }
4784 
4785 uint32_t
4786 ObjectFileMachO::GetSDKVersion(uint32_t *versions, uint32_t num_versions)
4787 {
4788     if (m_sdk_versions.empty())
4789     {
4790         lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic);
4791         bool success = false;
4792         for (uint32_t i=0; success == false && i < m_header.ncmds; ++i)
4793         {
4794             const lldb::offset_t load_cmd_offset = offset;
4795 
4796             version_min_command lc;
4797             if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL)
4798                 break;
4799             if (lc.cmd == LC_VERSION_MIN_MACOSX || lc.cmd == LC_VERSION_MIN_IPHONEOS)
4800             {
4801                 if (m_data.GetU32 (&offset, &lc.version, (sizeof(lc) / sizeof(uint32_t)) - 2))
4802                 {
4803                     const uint32_t xxxx = lc.reserved >> 16;
4804                     const uint32_t yy = (lc.reserved >> 8) & 0xffu;
4805                     const uint32_t zz = lc.reserved  & 0xffu;
4806                     if (xxxx)
4807                     {
4808                         m_sdk_versions.push_back(xxxx);
4809                         if (yy)
4810                         {
4811                             m_sdk_versions.push_back(yy);
4812                             if (zz)
4813                                 m_sdk_versions.push_back(zz);
4814                         }
4815                     }
4816                     success = true;
4817                 }
4818             }
4819             offset = load_cmd_offset + lc.cmdsize;
4820         }
4821 
4822         if (success == false)
4823         {
4824             // Push an invalid value so we don't keep trying to
4825             m_sdk_versions.push_back(UINT32_MAX);
4826         }
4827     }
4828 
4829     if (m_sdk_versions.size() > 1 || m_sdk_versions[0] != UINT32_MAX)
4830     {
4831         if (versions != NULL && num_versions > 0)
4832         {
4833             for (size_t i=0; i<num_versions; ++i)
4834             {
4835                 if (i < m_sdk_versions.size())
4836                     versions[i] = m_sdk_versions[i];
4837                 else
4838                     versions[i] = 0;
4839             }
4840         }
4841         return m_sdk_versions.size();
4842     }
4843     // Call the superclasses version that will empty out the data
4844     return ObjectFile::GetSDKVersion (versions, num_versions);
4845 }
4846 
4847 
4848 //------------------------------------------------------------------
4849 // PluginInterface protocol
4850 //------------------------------------------------------------------
4851 lldb_private::ConstString
4852 ObjectFileMachO::GetPluginName()
4853 {
4854     return GetPluginNameStatic();
4855 }
4856 
4857 uint32_t
4858 ObjectFileMachO::GetPluginVersion()
4859 {
4860     return 1;
4861 }
4862 
4863 
4864 bool
4865 ObjectFileMachO::SetLoadAddress (Target &target,
4866                                  lldb::addr_t value,
4867                                  bool value_is_offset)
4868 {
4869     bool changed = false;
4870     ModuleSP module_sp = GetModule();
4871     if (module_sp)
4872     {
4873         size_t num_loaded_sections = 0;
4874         SectionList *section_list = GetSectionList ();
4875         if (section_list)
4876         {
4877             lldb::addr_t mach_base_file_addr = LLDB_INVALID_ADDRESS;
4878             const size_t num_sections = section_list->GetSize();
4879 
4880             const bool is_memory_image = (bool)m_process_wp.lock();
4881             const Strata strata = GetStrata();
4882             static ConstString g_linkedit_segname ("__LINKEDIT");
4883             if (value_is_offset)
4884             {
4885                 // "value" is an offset to apply to each top level segment
4886                 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx)
4887                 {
4888                     // Iterate through the object file sections to find all
4889                     // of the sections that size on disk (to avoid __PAGEZERO)
4890                     // and load them
4891                     SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
4892                     if (section_sp &&
4893                         section_sp->GetFileSize() > 0 &&
4894                         section_sp->IsThreadSpecific() == false &&
4895                         module_sp.get() == section_sp->GetModule().get())
4896                     {
4897                         // Ignore __LINKEDIT and __DWARF segments
4898                         if (section_sp->GetName() == g_linkedit_segname)
4899                         {
4900                             // Only map __LINKEDIT if we have an in memory image and this isn't
4901                             // a kernel binary like a kext or mach_kernel.
4902                             if (is_memory_image == false || strata == eStrataKernel)
4903                                 continue;
4904                         }
4905                         if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() + value))
4906                             ++num_loaded_sections;
4907                     }
4908                 }
4909             }
4910             else
4911             {
4912                 // "value" is the new base address of the mach_header, adjust each
4913                 // section accordingly
4914 
4915                 // First find the address of the mach header which is the first non-zero
4916                 // file sized section whose file offset is zero as this will be subtracted
4917                 // from each other valid section's vmaddr and then get "base_addr" added to
4918                 // it when loading the module in the target
4919                 for (size_t sect_idx = 0;
4920                      sect_idx < num_sections && mach_base_file_addr == LLDB_INVALID_ADDRESS;
4921                      ++sect_idx)
4922                 {
4923                     // Iterate through the object file sections to find all
4924                     // of the sections that size on disk (to avoid __PAGEZERO)
4925                     // and load them
4926                     Section *section = section_list->GetSectionAtIndex (sect_idx).get();
4927                     if (section &&
4928                         section->GetFileSize() > 0 &&
4929                         section->GetFileOffset() == 0 &&
4930                         section->IsThreadSpecific() == false &&
4931                         module_sp.get() == section->GetModule().get())
4932                     {
4933                         // Ignore __LINKEDIT and __DWARF segments
4934                         if (section->GetName() == g_linkedit_segname)
4935                         {
4936                             // Only map __LINKEDIT if we have an in memory image and this isn't
4937                             // a kernel binary like a kext or mach_kernel.
4938                             if (is_memory_image == false || strata == eStrataKernel)
4939                                 continue;
4940                         }
4941                         mach_base_file_addr = section->GetFileAddress();
4942                     }
4943                 }
4944 
4945                 if (mach_base_file_addr != LLDB_INVALID_ADDRESS)
4946                 {
4947                     for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx)
4948                     {
4949                         // Iterate through the object file sections to find all
4950                         // of the sections that size on disk (to avoid __PAGEZERO)
4951                         // and load them
4952                         SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
4953                         if (section_sp &&
4954                             section_sp->GetFileSize() > 0 &&
4955                             section_sp->IsThreadSpecific() == false &&
4956                             module_sp.get() == section_sp->GetModule().get())
4957                         {
4958                             // Ignore __LINKEDIT and __DWARF segments
4959                             if (section_sp->GetName() == g_linkedit_segname)
4960                             {
4961                                 // Only map __LINKEDIT if we have an in memory image and this isn't
4962                                 // a kernel binary like a kext or mach_kernel.
4963                                 if (is_memory_image == false || strata == eStrataKernel)
4964                                     continue;
4965                             }
4966                             if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() - mach_base_file_addr + value))
4967                                 ++num_loaded_sections;
4968                         }
4969                     }
4970                 }
4971             }
4972         }
4973         changed = num_loaded_sections > 0;
4974         return num_loaded_sections > 0;
4975     }
4976     return changed;
4977 }
4978 
4979