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