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