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