1 //===-- ProcessMachCore.cpp ------------------------------------------*- C++
2 //-*-===//
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 
11 #include <errno.h>
12 #include <stdlib.h>
13 
14 #include "llvm/Support/MathExtras.h"
15 #include "llvm/Support/Threading.h"
16 #include <mutex>
17 
18 #include "lldb/Core/Debugger.h"
19 #include "lldb/Core/Module.h"
20 #include "lldb/Core/ModuleSpec.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/Section.h"
23 #include "lldb/Host/Host.h"
24 #include "lldb/Symbol/ObjectFile.h"
25 #include "lldb/Target/MemoryRegionInfo.h"
26 #include "lldb/Target/Target.h"
27 #include "lldb/Target/Thread.h"
28 #include "lldb/Utility/DataBuffer.h"
29 #include "lldb/Utility/Log.h"
30 #include "lldb/Utility/State.h"
31 
32 #include "ProcessMachCore.h"
33 #include "Plugins/Process/Utility/StopInfoMachException.h"
34 #include "ThreadMachCore.h"
35 
36 // Needed for the plug-in names for the dynamic loaders.
37 #include "lldb/Host/SafeMachO.h"
38 
39 #include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
40 #include "Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h"
41 #include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
42 
43 using namespace lldb;
44 using namespace lldb_private;
45 
46 ConstString ProcessMachCore::GetPluginNameStatic() {
47   static ConstString g_name("mach-o-core");
48   return g_name;
49 }
50 
51 const char *ProcessMachCore::GetPluginDescriptionStatic() {
52   return "Mach-O core file debugging plug-in.";
53 }
54 
55 void ProcessMachCore::Terminate() {
56   PluginManager::UnregisterPlugin(ProcessMachCore::CreateInstance);
57 }
58 
59 lldb::ProcessSP ProcessMachCore::CreateInstance(lldb::TargetSP target_sp,
60                                                 ListenerSP listener_sp,
61                                                 const FileSpec *crash_file) {
62   lldb::ProcessSP process_sp;
63   if (crash_file) {
64     const size_t header_size = sizeof(llvm::MachO::mach_header);
65     auto data_sp = FileSystem::Instance().CreateDataBuffer(
66         crash_file->GetPath(), header_size, 0);
67     if (data_sp && data_sp->GetByteSize() == header_size) {
68       DataExtractor data(data_sp, lldb::eByteOrderLittle, 4);
69 
70       lldb::offset_t data_offset = 0;
71       llvm::MachO::mach_header mach_header;
72       if (ObjectFileMachO::ParseHeader(data, &data_offset, mach_header)) {
73         if (mach_header.filetype == llvm::MachO::MH_CORE)
74           process_sp.reset(
75               new ProcessMachCore(target_sp, listener_sp, *crash_file));
76       }
77     }
78   }
79   return process_sp;
80 }
81 
82 bool ProcessMachCore::CanDebug(lldb::TargetSP target_sp,
83                                bool plugin_specified_by_name) {
84   if (plugin_specified_by_name)
85     return true;
86 
87   // For now we are just making sure the file exists for a given module
88   if (!m_core_module_sp && FileSystem::Instance().Exists(m_core_file)) {
89     // Don't add the Target's architecture to the ModuleSpec - we may be
90     // working with a core file that doesn't have the correct cpusubtype in the
91     // header but we should still try to use it -
92     // ModuleSpecList::FindMatchingModuleSpec enforces a strict arch mach.
93     ModuleSpec core_module_spec(m_core_file);
94     Status error(ModuleList::GetSharedModule(core_module_spec, m_core_module_sp,
95                                              NULL, NULL, NULL));
96 
97     if (m_core_module_sp) {
98       ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
99       if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile)
100         return true;
101     }
102   }
103   return false;
104 }
105 
106 //----------------------------------------------------------------------
107 // ProcessMachCore constructor
108 //----------------------------------------------------------------------
109 ProcessMachCore::ProcessMachCore(lldb::TargetSP target_sp,
110                                  ListenerSP listener_sp,
111                                  const FileSpec &core_file)
112     : Process(target_sp, listener_sp), m_core_aranges(), m_core_range_infos(),
113       m_core_module_sp(), m_core_file(core_file),
114       m_dyld_addr(LLDB_INVALID_ADDRESS),
115       m_mach_kernel_addr(LLDB_INVALID_ADDRESS), m_dyld_plugin_name() {}
116 
117 //----------------------------------------------------------------------
118 // Destructor
119 //----------------------------------------------------------------------
120 ProcessMachCore::~ProcessMachCore() {
121   Clear();
122   // We need to call finalize on the process before destroying ourselves to
123   // make sure all of the broadcaster cleanup goes as planned. If we destruct
124   // this class, then Process::~Process() might have problems trying to fully
125   // destroy the broadcaster.
126   Finalize();
127 }
128 
129 //----------------------------------------------------------------------
130 // PluginInterface
131 //----------------------------------------------------------------------
132 ConstString ProcessMachCore::GetPluginName() { return GetPluginNameStatic(); }
133 
134 uint32_t ProcessMachCore::GetPluginVersion() { return 1; }
135 
136 bool ProcessMachCore::GetDynamicLoaderAddress(lldb::addr_t addr) {
137   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER |
138                                                   LIBLLDB_LOG_PROCESS));
139   llvm::MachO::mach_header header;
140   Status error;
141   if (DoReadMemory(addr, &header, sizeof(header), error) != sizeof(header))
142     return false;
143   if (header.magic == llvm::MachO::MH_CIGAM ||
144       header.magic == llvm::MachO::MH_CIGAM_64) {
145     header.magic = llvm::ByteSwap_32(header.magic);
146     header.cputype = llvm::ByteSwap_32(header.cputype);
147     header.cpusubtype = llvm::ByteSwap_32(header.cpusubtype);
148     header.filetype = llvm::ByteSwap_32(header.filetype);
149     header.ncmds = llvm::ByteSwap_32(header.ncmds);
150     header.sizeofcmds = llvm::ByteSwap_32(header.sizeofcmds);
151     header.flags = llvm::ByteSwap_32(header.flags);
152   }
153 
154   // TODO: swap header if needed...
155   // printf("0x%16.16" PRIx64 ": magic = 0x%8.8x, file_type= %u\n", vaddr,
156   // header.magic, header.filetype);
157   if (header.magic == llvm::MachO::MH_MAGIC ||
158       header.magic == llvm::MachO::MH_MAGIC_64) {
159     // Check MH_EXECUTABLE to see if we can find the mach image that contains
160     // the shared library list. The dynamic loader (dyld) is what contains the
161     // list for user applications, and the mach kernel contains a global that
162     // has the list of kexts to load
163     switch (header.filetype) {
164     case llvm::MachO::MH_DYLINKER:
165       // printf("0x%16.16" PRIx64 ": file_type = MH_DYLINKER\n", vaddr);
166       // Address of dyld "struct mach_header" in the core file
167       if (log)
168         log->Printf("ProcessMachCore::GetDynamicLoaderAddress found a user "
169                     "process dyld binary image at 0x%" PRIx64,
170                     addr);
171       m_dyld_addr = addr;
172       return true;
173 
174     case llvm::MachO::MH_EXECUTE:
175       // printf("0x%16.16" PRIx64 ": file_type = MH_EXECUTE\n", vaddr);
176       // Check MH_EXECUTABLE file types to see if the dynamic link object flag
177       // is NOT set. If it isn't, then we have a mach_kernel.
178       if ((header.flags & llvm::MachO::MH_DYLDLINK) == 0) {
179         if (log)
180           log->Printf("ProcessMachCore::GetDynamicLoaderAddress found a mach "
181                       "kernel binary image at 0x%" PRIx64,
182                       addr);
183         // Address of the mach kernel "struct mach_header" in the core file.
184         m_mach_kernel_addr = addr;
185         return true;
186       }
187       break;
188     }
189   }
190   return false;
191 }
192 
193 //----------------------------------------------------------------------
194 // Process Control
195 //----------------------------------------------------------------------
196 Status ProcessMachCore::DoLoadCore() {
197   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER |
198                                                   LIBLLDB_LOG_PROCESS));
199   Status error;
200   if (!m_core_module_sp) {
201     error.SetErrorString("invalid core module");
202     return error;
203   }
204 
205   ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
206   if (core_objfile == NULL) {
207     error.SetErrorString("invalid core object file");
208     return error;
209   }
210 
211   if (core_objfile->GetNumThreadContexts() == 0) {
212     error.SetErrorString("core file doesn't contain any LC_THREAD load "
213                          "commands, or the LC_THREAD architecture is not "
214                          "supported in this lldb");
215     return error;
216   }
217 
218   SectionList *section_list = core_objfile->GetSectionList();
219   if (section_list == NULL) {
220     error.SetErrorString("core file has no sections");
221     return error;
222   }
223 
224   const uint32_t num_sections = section_list->GetNumSections(0);
225   if (num_sections == 0) {
226     error.SetErrorString("core file has no sections");
227     return error;
228   }
229 
230   SetCanJIT(false);
231 
232   llvm::MachO::mach_header header;
233   DataExtractor data(&header, sizeof(header),
234                      m_core_module_sp->GetArchitecture().GetByteOrder(),
235                      m_core_module_sp->GetArchitecture().GetAddressByteSize());
236 
237   bool ranges_are_sorted = true;
238   addr_t vm_addr = 0;
239   for (uint32_t i = 0; i < num_sections; ++i) {
240     Section *section = section_list->GetSectionAtIndex(i).get();
241     if (section) {
242       lldb::addr_t section_vm_addr = section->GetFileAddress();
243       FileRange file_range(section->GetFileOffset(), section->GetFileSize());
244       VMRangeToFileOffset::Entry range_entry(
245           section_vm_addr, section->GetByteSize(), file_range);
246 
247       if (vm_addr > section_vm_addr)
248         ranges_are_sorted = false;
249       vm_addr = section->GetFileAddress();
250       VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back();
251       //            printf ("LC_SEGMENT[%u] arange=[0x%16.16" PRIx64 " -
252       //            0x%16.16" PRIx64 "), frange=[0x%8.8x - 0x%8.8x)\n",
253       //                    i,
254       //                    range_entry.GetRangeBase(),
255       //                    range_entry.GetRangeEnd(),
256       //                    range_entry.data.GetRangeBase(),
257       //                    range_entry.data.GetRangeEnd());
258 
259       if (last_entry &&
260           last_entry->GetRangeEnd() == range_entry.GetRangeBase() &&
261           last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase()) {
262         last_entry->SetRangeEnd(range_entry.GetRangeEnd());
263         last_entry->data.SetRangeEnd(range_entry.data.GetRangeEnd());
264         // puts("combine");
265       } else {
266         m_core_aranges.Append(range_entry);
267       }
268       // Some core files don't fill in the permissions correctly. If that is
269       // the case assume read + execute so clients don't think the memory is
270       // not readable, or executable. The memory isn't writable since this
271       // plug-in doesn't implement DoWriteMemory.
272       uint32_t permissions = section->GetPermissions();
273       if (permissions == 0)
274         permissions = lldb::ePermissionsReadable | lldb::ePermissionsExecutable;
275       m_core_range_infos.Append(VMRangeToPermissions::Entry(
276           section_vm_addr, section->GetByteSize(), permissions));
277     }
278   }
279   if (!ranges_are_sorted) {
280     m_core_aranges.Sort();
281     m_core_range_infos.Sort();
282   }
283 
284 
285   bool found_main_binary_definitively = false;
286 
287   addr_t objfile_binary_addr;
288   UUID objfile_binary_uuid;
289   if (core_objfile->GetCorefileMainBinaryInfo (objfile_binary_addr, objfile_binary_uuid))
290   {
291     if (objfile_binary_addr != LLDB_INVALID_ADDRESS)
292     {
293         m_mach_kernel_addr = objfile_binary_addr;
294         found_main_binary_definitively = true;
295         if (log)
296             log->Printf ("ProcessMachCore::DoLoadCore: using kernel address 0x%" PRIx64
297                          " from LC_NOTE 'main bin spec' load command.", m_mach_kernel_addr);
298     }
299   }
300 
301   // This checks for the presence of an LC_IDENT string in a core file;
302   // LC_IDENT is very obsolete and should not be used in new code, but if the
303   // load command is present, let's use the contents.
304   std::string corefile_identifier = core_objfile->GetIdentifierString();
305   if (found_main_binary_definitively == false
306       && corefile_identifier.find("Darwin Kernel") != std::string::npos) {
307       UUID uuid;
308       addr_t addr = LLDB_INVALID_ADDRESS;
309       if (corefile_identifier.find("UUID=") != std::string::npos) {
310           size_t p = corefile_identifier.find("UUID=") + strlen("UUID=");
311           std::string uuid_str = corefile_identifier.substr(p, 36);
312           uuid.SetFromStringRef(uuid_str);
313       }
314       if (corefile_identifier.find("stext=") != std::string::npos) {
315           size_t p = corefile_identifier.find("stext=") + strlen("stext=");
316           if (corefile_identifier[p] == '0' && corefile_identifier[p + 1] == 'x') {
317               errno = 0;
318               addr = ::strtoul(corefile_identifier.c_str() + p, NULL, 16);
319               if (errno != 0 || addr == 0)
320                   addr = LLDB_INVALID_ADDRESS;
321           }
322       }
323       if (uuid.IsValid() && addr != LLDB_INVALID_ADDRESS) {
324           m_mach_kernel_addr = addr;
325           found_main_binary_definitively = true;
326           if (log)
327             log->Printf("ProcessMachCore::DoLoadCore: Using the kernel address 0x%" PRIx64
328                         " from LC_IDENT/LC_NOTE 'kern ver str' string: '%s'", addr, corefile_identifier.c_str());
329       }
330   }
331 
332   if (found_main_binary_definitively == false
333       && (m_dyld_addr == LLDB_INVALID_ADDRESS
334           || m_mach_kernel_addr == LLDB_INVALID_ADDRESS)) {
335     // We need to locate the main executable in the memory ranges we have in
336     // the core file.  We need to search for both a user-process dyld binary
337     // and a kernel binary in memory; we must look at all the pages in the
338     // binary so we don't miss one or the other.  Step through all memory
339     // segments searching for a kernel binary and for a user process dyld --
340     // we'll decide which to prefer later if both are present.
341 
342     const size_t num_core_aranges = m_core_aranges.GetSize();
343     for (size_t i = 0; i < num_core_aranges; ++i) {
344       const VMRangeToFileOffset::Entry *entry =
345           m_core_aranges.GetEntryAtIndex(i);
346       lldb::addr_t section_vm_addr_start = entry->GetRangeBase();
347       lldb::addr_t section_vm_addr_end = entry->GetRangeEnd();
348       for (lldb::addr_t section_vm_addr = section_vm_addr_start;
349            section_vm_addr < section_vm_addr_end; section_vm_addr += 0x1000) {
350         GetDynamicLoaderAddress(section_vm_addr);
351       }
352     }
353   }
354 
355   if (found_main_binary_definitively == false
356        && m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
357     // In the case of multiple kernel images found in the core file via
358     // exhaustive search, we may not pick the correct one.  See if the
359     // DynamicLoaderDarwinKernel's search heuristics might identify the correct
360     // one. Most of the time, I expect the address from SearchForDarwinKernel()
361     // will be the same as the address we found via exhaustive search.
362 
363     if (GetTarget().GetArchitecture().IsValid() == false &&
364         m_core_module_sp.get()) {
365       GetTarget().SetArchitecture(m_core_module_sp->GetArchitecture());
366     }
367 
368     // SearchForDarwinKernel will end up calling back into this this class in
369     // the GetImageInfoAddress method which will give it the
370     // m_mach_kernel_addr/m_dyld_addr it already has.  Save that aside and set
371     // m_mach_kernel_addr/m_dyld_addr to an invalid address temporarily so
372     // DynamicLoaderDarwinKernel does a real search for the kernel using its
373     // own heuristics.
374 
375     addr_t saved_mach_kernel_addr = m_mach_kernel_addr;
376     addr_t saved_user_dyld_addr = m_dyld_addr;
377     m_mach_kernel_addr = LLDB_INVALID_ADDRESS;
378     m_dyld_addr = LLDB_INVALID_ADDRESS;
379 
380     addr_t better_kernel_address =
381         DynamicLoaderDarwinKernel::SearchForDarwinKernel(this);
382 
383     m_mach_kernel_addr = saved_mach_kernel_addr;
384     m_dyld_addr = saved_user_dyld_addr;
385 
386     if (better_kernel_address != LLDB_INVALID_ADDRESS) {
387       if (log)
388         log->Printf("ProcessMachCore::DoLoadCore: Using the kernel address "
389                     "from DynamicLoaderDarwinKernel");
390       m_mach_kernel_addr = better_kernel_address;
391     }
392   }
393 
394   // If we found both a user-process dyld and a kernel binary, we need to
395   // decide which to prefer.
396   if (GetCorefilePreference() == eKernelCorefile) {
397     if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
398       if (log)
399         log->Printf("ProcessMachCore::DoLoadCore: Using kernel corefile image "
400                     "at 0x%" PRIx64,
401                     m_mach_kernel_addr);
402       m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
403     } else if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
404       if (log)
405         log->Printf("ProcessMachCore::DoLoadCore: Using user process dyld "
406                     "image at 0x%" PRIx64,
407                     m_dyld_addr);
408       m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
409     }
410   } else {
411     if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
412       if (log)
413         log->Printf("ProcessMachCore::DoLoadCore: Using user process dyld "
414                     "image at 0x%" PRIx64,
415                     m_dyld_addr);
416       m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
417     } else if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
418       if (log)
419         log->Printf("ProcessMachCore::DoLoadCore: Using kernel corefile image "
420                     "at 0x%" PRIx64,
421                     m_mach_kernel_addr);
422       m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
423     }
424   }
425 
426   if (m_dyld_plugin_name != DynamicLoaderMacOSXDYLD::GetPluginNameStatic()) {
427     // For non-user process core files, the permissions on the core file
428     // segments are usually meaningless, they may be just "read", because we're
429     // dealing with kernel coredumps or early startup coredumps and the dumper
430     // is grabbing pages of memory without knowing what they are.  If they
431     // aren't marked as "exeuctable", that can break the unwinder which will
432     // check a pc value to see if it is in an executable segment and stop the
433     // backtrace early if it is not ("executable" and "unknown" would both be
434     // fine, but "not executable" will break the unwinder).
435     size_t core_range_infos_size = m_core_range_infos.GetSize();
436     for (size_t i = 0; i < core_range_infos_size; i++) {
437       VMRangeToPermissions::Entry *ent =
438           m_core_range_infos.GetMutableEntryAtIndex(i);
439       ent->data = lldb::ePermissionsReadable | lldb::ePermissionsExecutable;
440     }
441   }
442 
443   // Even if the architecture is set in the target, we need to override it to
444   // match the core file which is always single arch.
445   ArchSpec arch(m_core_module_sp->GetArchitecture());
446   if (arch.GetCore() == ArchSpec::eCore_x86_32_i486) {
447     arch = Platform::GetAugmentedArchSpec(GetTarget().GetPlatform().get(), "i386");
448   }
449   if (arch.IsValid())
450     GetTarget().SetArchitecture(arch);
451 
452   return error;
453 }
454 
455 lldb_private::DynamicLoader *ProcessMachCore::GetDynamicLoader() {
456   if (m_dyld_ap.get() == NULL)
457     m_dyld_ap.reset(DynamicLoader::FindPlugin(
458         this,
459         m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
460   return m_dyld_ap.get();
461 }
462 
463 bool ProcessMachCore::UpdateThreadList(ThreadList &old_thread_list,
464                                        ThreadList &new_thread_list) {
465   if (old_thread_list.GetSize(false) == 0) {
466     // Make up the thread the first time this is called so we can setup our one
467     // and only core thread state.
468     ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
469 
470     if (core_objfile) {
471       const uint32_t num_threads = core_objfile->GetNumThreadContexts();
472       for (lldb::tid_t tid = 0; tid < num_threads; ++tid) {
473         ThreadSP thread_sp(new ThreadMachCore(*this, tid));
474         new_thread_list.AddThread(thread_sp);
475       }
476     }
477   } else {
478     const uint32_t num_threads = old_thread_list.GetSize(false);
479     for (uint32_t i = 0; i < num_threads; ++i)
480       new_thread_list.AddThread(old_thread_list.GetThreadAtIndex(i, false));
481   }
482   return new_thread_list.GetSize(false) > 0;
483 }
484 
485 void ProcessMachCore::RefreshStateAfterStop() {
486   // Let all threads recover from stopping and do any clean up based on the
487   // previous thread state (if any).
488   m_thread_list.RefreshStateAfterStop();
489   // SetThreadStopInfo (m_last_stop_packet);
490 }
491 
492 Status ProcessMachCore::DoDestroy() { return Status(); }
493 
494 //------------------------------------------------------------------
495 // Process Queries
496 //------------------------------------------------------------------
497 
498 bool ProcessMachCore::IsAlive() { return true; }
499 
500 bool ProcessMachCore::WarnBeforeDetach() const { return false; }
501 
502 //------------------------------------------------------------------
503 // Process Memory
504 //------------------------------------------------------------------
505 size_t ProcessMachCore::ReadMemory(addr_t addr, void *buf, size_t size,
506                                    Status &error) {
507   // Don't allow the caching that lldb_private::Process::ReadMemory does since
508   // in core files we have it all cached our our core file anyway.
509   return DoReadMemory(addr, buf, size, error);
510 }
511 
512 size_t ProcessMachCore::DoReadMemory(addr_t addr, void *buf, size_t size,
513                                      Status &error) {
514   ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
515   size_t bytes_read = 0;
516 
517   if (core_objfile) {
518     //----------------------------------------------------------------------
519     // Segments are not always contiguous in mach-o core files. We have core
520     // files that have segments like:
521     //            Address    Size       File off   File size
522     //            ---------- ---------- ---------- ----------
523     // LC_SEGMENT 0x000f6000 0x00001000 0x1d509ee8 0x00001000 --- ---   0
524     // 0x00000000 __TEXT LC_SEGMENT 0x0f600000 0x00100000 0x1d50aee8 0x00100000
525     // --- ---   0 0x00000000 __TEXT LC_SEGMENT 0x000f7000 0x00001000
526     // 0x1d60aee8 0x00001000 --- ---   0 0x00000000 __TEXT
527     //
528     // Any if the user executes the following command:
529     //
530     // (lldb) mem read 0xf6ff0
531     //
532     // We would attempt to read 32 bytes from 0xf6ff0 but would only get 16
533     // unless we loop through consecutive memory ranges that are contiguous in
534     // the address space, but not in the file data.
535     //----------------------------------------------------------------------
536     while (bytes_read < size) {
537       const addr_t curr_addr = addr + bytes_read;
538       const VMRangeToFileOffset::Entry *core_memory_entry =
539           m_core_aranges.FindEntryThatContains(curr_addr);
540 
541       if (core_memory_entry) {
542         const addr_t offset = curr_addr - core_memory_entry->GetRangeBase();
543         const addr_t bytes_left = core_memory_entry->GetRangeEnd() - curr_addr;
544         const size_t bytes_to_read =
545             std::min(size - bytes_read, (size_t)bytes_left);
546         const size_t curr_bytes_read = core_objfile->CopyData(
547             core_memory_entry->data.GetRangeBase() + offset, bytes_to_read,
548             (char *)buf + bytes_read);
549         if (curr_bytes_read == 0)
550           break;
551         bytes_read += curr_bytes_read;
552       } else {
553         // Only set the error if we didn't read any bytes
554         if (bytes_read == 0)
555           error.SetErrorStringWithFormat(
556               "core file does not contain 0x%" PRIx64, curr_addr);
557         break;
558       }
559     }
560   }
561 
562   return bytes_read;
563 }
564 
565 Status ProcessMachCore::GetMemoryRegionInfo(addr_t load_addr,
566                                             MemoryRegionInfo &region_info) {
567   region_info.Clear();
568   const VMRangeToPermissions::Entry *permission_entry =
569       m_core_range_infos.FindEntryThatContainsOrFollows(load_addr);
570   if (permission_entry) {
571     if (permission_entry->Contains(load_addr)) {
572       region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase());
573       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd());
574       const Flags permissions(permission_entry->data);
575       region_info.SetReadable(permissions.Test(ePermissionsReadable)
576                                   ? MemoryRegionInfo::eYes
577                                   : MemoryRegionInfo::eNo);
578       region_info.SetWritable(permissions.Test(ePermissionsWritable)
579                                   ? MemoryRegionInfo::eYes
580                                   : MemoryRegionInfo::eNo);
581       region_info.SetExecutable(permissions.Test(ePermissionsExecutable)
582                                     ? MemoryRegionInfo::eYes
583                                     : MemoryRegionInfo::eNo);
584       region_info.SetMapped(MemoryRegionInfo::eYes);
585     } else if (load_addr < permission_entry->GetRangeBase()) {
586       region_info.GetRange().SetRangeBase(load_addr);
587       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeBase());
588       region_info.SetReadable(MemoryRegionInfo::eNo);
589       region_info.SetWritable(MemoryRegionInfo::eNo);
590       region_info.SetExecutable(MemoryRegionInfo::eNo);
591       region_info.SetMapped(MemoryRegionInfo::eNo);
592     }
593     return Status();
594   }
595 
596   region_info.GetRange().SetRangeBase(load_addr);
597   region_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
598   region_info.SetReadable(MemoryRegionInfo::eNo);
599   region_info.SetWritable(MemoryRegionInfo::eNo);
600   region_info.SetExecutable(MemoryRegionInfo::eNo);
601   region_info.SetMapped(MemoryRegionInfo::eNo);
602   return Status();
603 }
604 
605 void ProcessMachCore::Clear() { m_thread_list.Clear(); }
606 
607 void ProcessMachCore::Initialize() {
608   static llvm::once_flag g_once_flag;
609 
610   llvm::call_once(g_once_flag, []() {
611     PluginManager::RegisterPlugin(GetPluginNameStatic(),
612                                   GetPluginDescriptionStatic(), CreateInstance);
613   });
614 }
615 
616 addr_t ProcessMachCore::GetImageInfoAddress() {
617   // If we found both a user-process dyld and a kernel binary, we need to
618   // decide which to prefer.
619   if (GetCorefilePreference() == eKernelCorefile) {
620     if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
621       return m_mach_kernel_addr;
622     }
623     return m_dyld_addr;
624   } else {
625     if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
626       return m_dyld_addr;
627     }
628     return m_mach_kernel_addr;
629   }
630 }
631 
632 lldb_private::ObjectFile *ProcessMachCore::GetCoreObjectFile() {
633   return m_core_module_sp->GetObjectFile();
634 }
635