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