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