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