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 &&
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(
328             "ProcessMachCore::DoLoadCore: Using the kernel address 0x%" PRIx64
329             " from LC_IDENT/LC_NOTE 'kern ver str' string: '%s'",
330             addr, corefile_identifier.c_str());
331     }
332   }
333 
334   if (!found_main_binary_definitively &&
335       (m_dyld_addr == LLDB_INVALID_ADDRESS ||
336        m_mach_kernel_addr == LLDB_INVALID_ADDRESS)) {
337     // We need to locate the main executable in the memory ranges we have in
338     // the core file.  We need to search for both a user-process dyld binary
339     // and a kernel binary in memory; we must look at all the pages in the
340     // binary so we don't miss one or the other.  Step through all memory
341     // segments searching for a kernel binary and for a user process dyld --
342     // we'll decide which to prefer later if both are present.
343 
344     const size_t num_core_aranges = m_core_aranges.GetSize();
345     for (size_t i = 0; i < num_core_aranges; ++i) {
346       const VMRangeToFileOffset::Entry *entry =
347           m_core_aranges.GetEntryAtIndex(i);
348       lldb::addr_t section_vm_addr_start = entry->GetRangeBase();
349       lldb::addr_t section_vm_addr_end = entry->GetRangeEnd();
350       for (lldb::addr_t section_vm_addr = section_vm_addr_start;
351            section_vm_addr < section_vm_addr_end; section_vm_addr += 0x1000) {
352         GetDynamicLoaderAddress(section_vm_addr);
353       }
354     }
355   }
356 
357   if (!found_main_binary_definitively &&
358       m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
359     // In the case of multiple kernel images found in the core file via
360     // exhaustive search, we may not pick the correct one.  See if the
361     // DynamicLoaderDarwinKernel's search heuristics might identify the correct
362     // one. Most of the time, I expect the address from SearchForDarwinKernel()
363     // will be the same as the address we found via exhaustive search.
364 
365     if (!GetTarget().GetArchitecture().IsValid() && m_core_module_sp.get()) {
366       GetTarget().SetArchitecture(m_core_module_sp->GetArchitecture());
367     }
368 
369     // SearchForDarwinKernel will end up calling back into this this class in
370     // the GetImageInfoAddress method which will give it the
371     // m_mach_kernel_addr/m_dyld_addr it already has.  Save that aside and set
372     // m_mach_kernel_addr/m_dyld_addr to an invalid address temporarily so
373     // DynamicLoaderDarwinKernel does a real search for the kernel using its
374     // own heuristics.
375 
376     addr_t saved_mach_kernel_addr = m_mach_kernel_addr;
377     addr_t saved_user_dyld_addr = m_dyld_addr;
378     m_mach_kernel_addr = LLDB_INVALID_ADDRESS;
379     m_dyld_addr = LLDB_INVALID_ADDRESS;
380 
381     addr_t better_kernel_address =
382         DynamicLoaderDarwinKernel::SearchForDarwinKernel(this);
383 
384     m_mach_kernel_addr = saved_mach_kernel_addr;
385     m_dyld_addr = saved_user_dyld_addr;
386 
387     if (better_kernel_address != LLDB_INVALID_ADDRESS) {
388       if (log)
389         log->Printf("ProcessMachCore::DoLoadCore: Using the kernel address "
390                     "from DynamicLoaderDarwinKernel");
391       m_mach_kernel_addr = better_kernel_address;
392     }
393   }
394 
395   // If we found both a user-process dyld and a kernel binary, we need to
396   // decide which to prefer.
397   if (GetCorefilePreference() == eKernelCorefile) {
398     if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
399       if (log)
400         log->Printf("ProcessMachCore::DoLoadCore: Using kernel corefile image "
401                     "at 0x%" PRIx64,
402                     m_mach_kernel_addr);
403       m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
404     } else if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
405       if (log)
406         log->Printf("ProcessMachCore::DoLoadCore: Using user process dyld "
407                     "image at 0x%" PRIx64,
408                     m_dyld_addr);
409       m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
410     }
411   } else {
412     if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
413       if (log)
414         log->Printf("ProcessMachCore::DoLoadCore: Using user process dyld "
415                     "image at 0x%" PRIx64,
416                     m_dyld_addr);
417       m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
418     } else if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
419       if (log)
420         log->Printf("ProcessMachCore::DoLoadCore: Using kernel corefile image "
421                     "at 0x%" PRIx64,
422                     m_mach_kernel_addr);
423       m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
424     }
425   }
426 
427   if (m_dyld_plugin_name != DynamicLoaderMacOSXDYLD::GetPluginNameStatic()) {
428     // For non-user process core files, the permissions on the core file
429     // segments are usually meaningless, they may be just "read", because we're
430     // dealing with kernel coredumps or early startup coredumps and the dumper
431     // is grabbing pages of memory without knowing what they are.  If they
432     // aren't marked as "exeuctable", that can break the unwinder which will
433     // check a pc value to see if it is in an executable segment and stop the
434     // backtrace early if it is not ("executable" and "unknown" would both be
435     // fine, but "not executable" will break the unwinder).
436     size_t core_range_infos_size = m_core_range_infos.GetSize();
437     for (size_t i = 0; i < core_range_infos_size; i++) {
438       VMRangeToPermissions::Entry *ent =
439           m_core_range_infos.GetMutableEntryAtIndex(i);
440       ent->data = lldb::ePermissionsReadable | lldb::ePermissionsExecutable;
441     }
442   }
443 
444   // Even if the architecture is set in the target, we need to override it to
445   // match the core file which is always single arch.
446   ArchSpec arch(m_core_module_sp->GetArchitecture());
447   if (arch.GetCore() == ArchSpec::eCore_x86_32_i486) {
448     arch = Platform::GetAugmentedArchSpec(GetTarget().GetPlatform().get(), "i386");
449   }
450   if (arch.IsValid())
451     GetTarget().SetArchitecture(arch);
452 
453   return error;
454 }
455 
456 lldb_private::DynamicLoader *ProcessMachCore::GetDynamicLoader() {
457   if (m_dyld_ap.get() == NULL)
458     m_dyld_ap.reset(DynamicLoader::FindPlugin(
459         this,
460         m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
461   return m_dyld_ap.get();
462 }
463 
464 bool ProcessMachCore::UpdateThreadList(ThreadList &old_thread_list,
465                                        ThreadList &new_thread_list) {
466   if (old_thread_list.GetSize(false) == 0) {
467     // Make up the thread the first time this is called so we can setup our one
468     // and only core thread state.
469     ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
470 
471     if (core_objfile) {
472       const uint32_t num_threads = core_objfile->GetNumThreadContexts();
473       for (lldb::tid_t tid = 0; tid < num_threads; ++tid) {
474         ThreadSP thread_sp(new ThreadMachCore(*this, tid));
475         new_thread_list.AddThread(thread_sp);
476       }
477     }
478   } else {
479     const uint32_t num_threads = old_thread_list.GetSize(false);
480     for (uint32_t i = 0; i < num_threads; ++i)
481       new_thread_list.AddThread(old_thread_list.GetThreadAtIndex(i, false));
482   }
483   return new_thread_list.GetSize(false) > 0;
484 }
485 
486 void ProcessMachCore::RefreshStateAfterStop() {
487   // Let all threads recover from stopping and do any clean up based on the
488   // previous thread state (if any).
489   m_thread_list.RefreshStateAfterStop();
490   // SetThreadStopInfo (m_last_stop_packet);
491 }
492 
493 Status ProcessMachCore::DoDestroy() { return Status(); }
494 
495 //------------------------------------------------------------------
496 // Process Queries
497 //------------------------------------------------------------------
498 
499 bool ProcessMachCore::IsAlive() { return true; }
500 
501 bool ProcessMachCore::WarnBeforeDetach() const { return false; }
502 
503 //------------------------------------------------------------------
504 // Process Memory
505 //------------------------------------------------------------------
506 size_t ProcessMachCore::ReadMemory(addr_t addr, void *buf, size_t size,
507                                    Status &error) {
508   // Don't allow the caching that lldb_private::Process::ReadMemory does since
509   // in core files we have it all cached our our core file anyway.
510   return DoReadMemory(addr, buf, size, error);
511 }
512 
513 size_t ProcessMachCore::DoReadMemory(addr_t addr, void *buf, size_t size,
514                                      Status &error) {
515   ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
516   size_t bytes_read = 0;
517 
518   if (core_objfile) {
519     //----------------------------------------------------------------------
520     // Segments are not always contiguous in mach-o core files. We have core
521     // files that have segments like:
522     //            Address    Size       File off   File size
523     //            ---------- ---------- ---------- ----------
524     // LC_SEGMENT 0x000f6000 0x00001000 0x1d509ee8 0x00001000 --- ---   0
525     // 0x00000000 __TEXT LC_SEGMENT 0x0f600000 0x00100000 0x1d50aee8 0x00100000
526     // --- ---   0 0x00000000 __TEXT LC_SEGMENT 0x000f7000 0x00001000
527     // 0x1d60aee8 0x00001000 --- ---   0 0x00000000 __TEXT
528     //
529     // Any if the user executes the following command:
530     //
531     // (lldb) mem read 0xf6ff0
532     //
533     // We would attempt to read 32 bytes from 0xf6ff0 but would only get 16
534     // unless we loop through consecutive memory ranges that are contiguous in
535     // the address space, but not in the file data.
536     //----------------------------------------------------------------------
537     while (bytes_read < size) {
538       const addr_t curr_addr = addr + bytes_read;
539       const VMRangeToFileOffset::Entry *core_memory_entry =
540           m_core_aranges.FindEntryThatContains(curr_addr);
541 
542       if (core_memory_entry) {
543         const addr_t offset = curr_addr - core_memory_entry->GetRangeBase();
544         const addr_t bytes_left = core_memory_entry->GetRangeEnd() - curr_addr;
545         const size_t bytes_to_read =
546             std::min(size - bytes_read, (size_t)bytes_left);
547         const size_t curr_bytes_read = core_objfile->CopyData(
548             core_memory_entry->data.GetRangeBase() + offset, bytes_to_read,
549             (char *)buf + bytes_read);
550         if (curr_bytes_read == 0)
551           break;
552         bytes_read += curr_bytes_read;
553       } else {
554         // Only set the error if we didn't read any bytes
555         if (bytes_read == 0)
556           error.SetErrorStringWithFormat(
557               "core file does not contain 0x%" PRIx64, curr_addr);
558         break;
559       }
560     }
561   }
562 
563   return bytes_read;
564 }
565 
566 Status ProcessMachCore::GetMemoryRegionInfo(addr_t load_addr,
567                                             MemoryRegionInfo &region_info) {
568   region_info.Clear();
569   const VMRangeToPermissions::Entry *permission_entry =
570       m_core_range_infos.FindEntryThatContainsOrFollows(load_addr);
571   if (permission_entry) {
572     if (permission_entry->Contains(load_addr)) {
573       region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase());
574       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd());
575       const Flags permissions(permission_entry->data);
576       region_info.SetReadable(permissions.Test(ePermissionsReadable)
577                                   ? MemoryRegionInfo::eYes
578                                   : MemoryRegionInfo::eNo);
579       region_info.SetWritable(permissions.Test(ePermissionsWritable)
580                                   ? MemoryRegionInfo::eYes
581                                   : MemoryRegionInfo::eNo);
582       region_info.SetExecutable(permissions.Test(ePermissionsExecutable)
583                                     ? MemoryRegionInfo::eYes
584                                     : MemoryRegionInfo::eNo);
585       region_info.SetMapped(MemoryRegionInfo::eYes);
586     } else if (load_addr < permission_entry->GetRangeBase()) {
587       region_info.GetRange().SetRangeBase(load_addr);
588       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeBase());
589       region_info.SetReadable(MemoryRegionInfo::eNo);
590       region_info.SetWritable(MemoryRegionInfo::eNo);
591       region_info.SetExecutable(MemoryRegionInfo::eNo);
592       region_info.SetMapped(MemoryRegionInfo::eNo);
593     }
594     return Status();
595   }
596 
597   region_info.GetRange().SetRangeBase(load_addr);
598   region_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
599   region_info.SetReadable(MemoryRegionInfo::eNo);
600   region_info.SetWritable(MemoryRegionInfo::eNo);
601   region_info.SetExecutable(MemoryRegionInfo::eNo);
602   region_info.SetMapped(MemoryRegionInfo::eNo);
603   return Status();
604 }
605 
606 void ProcessMachCore::Clear() { m_thread_list.Clear(); }
607 
608 void ProcessMachCore::Initialize() {
609   static llvm::once_flag g_once_flag;
610 
611   llvm::call_once(g_once_flag, []() {
612     PluginManager::RegisterPlugin(GetPluginNameStatic(),
613                                   GetPluginDescriptionStatic(), CreateInstance);
614   });
615 }
616 
617 addr_t ProcessMachCore::GetImageInfoAddress() {
618   // If we found both a user-process dyld and a kernel binary, we need to
619   // decide which to prefer.
620   if (GetCorefilePreference() == eKernelCorefile) {
621     if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
622       return m_mach_kernel_addr;
623     }
624     return m_dyld_addr;
625   } else {
626     if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
627       return m_dyld_addr;
628     }
629     return m_mach_kernel_addr;
630   }
631 }
632 
633 lldb_private::ObjectFile *ProcessMachCore::GetCoreObjectFile() {
634   return m_core_module_sp->GetObjectFile();
635 }
636