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