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