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       LLDB_LOGF(log,
164                 "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         LLDB_LOGF(log,
176                   "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         LLDB_LOGF(log,
290                   "ProcessMachCore::DoLoadCore: using kernel address 0x%" PRIx64
291                   " from LC_NOTE 'main bin spec' load command.",
292                   m_mach_kernel_addr);
293     }
294   }
295 
296   // This checks for the presence of an LC_IDENT string in a core file;
297   // LC_IDENT is very obsolete and should not be used in new code, but if the
298   // load command is present, let's use the contents.
299   std::string corefile_identifier = core_objfile->GetIdentifierString();
300   if (!found_main_binary_definitively &&
301       corefile_identifier.find("Darwin Kernel") != std::string::npos) {
302     UUID uuid;
303     addr_t addr = LLDB_INVALID_ADDRESS;
304     if (corefile_identifier.find("UUID=") != std::string::npos) {
305       size_t p = corefile_identifier.find("UUID=") + strlen("UUID=");
306       std::string uuid_str = corefile_identifier.substr(p, 36);
307       uuid.SetFromStringRef(uuid_str);
308     }
309     if (corefile_identifier.find("stext=") != std::string::npos) {
310       size_t p = corefile_identifier.find("stext=") + strlen("stext=");
311       if (corefile_identifier[p] == '0' && corefile_identifier[p + 1] == 'x') {
312         errno = 0;
313         addr = ::strtoul(corefile_identifier.c_str() + p, nullptr, 16);
314         if (errno != 0 || addr == 0)
315           addr = LLDB_INVALID_ADDRESS;
316       }
317     }
318     if (uuid.IsValid() && addr != LLDB_INVALID_ADDRESS) {
319       m_mach_kernel_addr = addr;
320       found_main_binary_definitively = true;
321       LLDB_LOGF(
322           log,
323           "ProcessMachCore::DoLoadCore: Using the kernel address 0x%" PRIx64
324           " from LC_IDENT/LC_NOTE 'kern ver str' string: '%s'",
325           addr, corefile_identifier.c_str());
326     }
327   }
328   if (found_main_binary_definitively == false
329       && corefile_identifier.find("EFI ") != std::string::npos) {
330       UUID uuid;
331       if (corefile_identifier.find("UUID=") != std::string::npos) {
332           size_t p = corefile_identifier.find("UUID=") + strlen("UUID=");
333           std::string uuid_str = corefile_identifier.substr(p, 36);
334           uuid.SetFromStringRef(uuid_str);
335       }
336       if (uuid.IsValid()) {
337         LLDB_LOGF(log,
338                   "ProcessMachCore::DoLoadCore: Using the EFI "
339                   "from LC_IDENT/LC_NOTE 'kern ver str' string: '%s'",
340                   corefile_identifier.c_str());
341 
342         // We're only given a UUID here, not a load address.
343         // But there are python scripts in the EFI binary's dSYM which
344         // know how to relocate the binary to the correct load address.
345         // lldb only needs to locate & load the binary + dSYM.
346         ModuleSpec module_spec;
347         module_spec.GetUUID() = uuid;
348         module_spec.GetArchitecture() = GetTarget().GetArchitecture();
349 
350         // Lookup UUID locally, before attempting dsymForUUID like action
351         FileSpecList search_paths = 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(
358                   executable_module_spec.GetFileSpec())) {
359             module_spec.GetFileSpec() = 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       LLDB_LOGF(log, "ProcessMachCore::DoLoadCore: Using the kernel address "
437                      "from DynamicLoaderDarwinKernel");
438       m_mach_kernel_addr = better_kernel_address;
439     }
440   }
441 
442   // If we found both a user-process dyld and a kernel binary, we need to
443   // decide which to prefer.
444   if (GetCorefilePreference() == eKernelCorefile) {
445     if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
446       LLDB_LOGF(log,
447                 "ProcessMachCore::DoLoadCore: Using kernel corefile image "
448                 "at 0x%" PRIx64,
449                 m_mach_kernel_addr);
450       m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
451     } else if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
452       LLDB_LOGF(log,
453                 "ProcessMachCore::DoLoadCore: Using user process dyld "
454                 "image at 0x%" PRIx64,
455                 m_dyld_addr);
456       m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
457     }
458   } else {
459     if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
460       LLDB_LOGF(log,
461                 "ProcessMachCore::DoLoadCore: Using user process dyld "
462                 "image at 0x%" PRIx64,
463                 m_dyld_addr);
464       m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
465     } else if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
466       LLDB_LOGF(log,
467                 "ProcessMachCore::DoLoadCore: Using kernel corefile image "
468                 "at 0x%" PRIx64,
469                 m_mach_kernel_addr);
470       m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
471     }
472   }
473 
474   if (m_dyld_plugin_name != DynamicLoaderMacOSXDYLD::GetPluginNameStatic()) {
475     // For non-user process core files, the permissions on the core file
476     // segments are usually meaningless, they may be just "read", because we're
477     // dealing with kernel coredumps or early startup coredumps and the dumper
478     // is grabbing pages of memory without knowing what they are.  If they
479     // aren't marked as "exeuctable", that can break the unwinder which will
480     // check a pc value to see if it is in an executable segment and stop the
481     // backtrace early if it is not ("executable" and "unknown" would both be
482     // fine, but "not executable" will break the unwinder).
483     size_t core_range_infos_size = m_core_range_infos.GetSize();
484     for (size_t i = 0; i < core_range_infos_size; i++) {
485       VMRangeToPermissions::Entry *ent =
486           m_core_range_infos.GetMutableEntryAtIndex(i);
487       ent->data = lldb::ePermissionsReadable | lldb::ePermissionsExecutable;
488     }
489   }
490 
491   // Even if the architecture is set in the target, we need to override it to
492   // match the core file which is always single arch.
493   ArchSpec arch(m_core_module_sp->GetArchitecture());
494   if (arch.GetCore() == ArchSpec::eCore_x86_32_i486) {
495     arch = Platform::GetAugmentedArchSpec(GetTarget().GetPlatform().get(), "i386");
496   }
497   if (arch.IsValid())
498     GetTarget().SetArchitecture(arch);
499 
500   return error;
501 }
502 
503 lldb_private::DynamicLoader *ProcessMachCore::GetDynamicLoader() {
504   if (m_dyld_up.get() == nullptr)
505     m_dyld_up.reset(DynamicLoader::FindPlugin(
506         this, m_dyld_plugin_name.IsEmpty() ? nullptr
507                                            : m_dyld_plugin_name.GetCString()));
508   return m_dyld_up.get();
509 }
510 
511 bool ProcessMachCore::UpdateThreadList(ThreadList &old_thread_list,
512                                        ThreadList &new_thread_list) {
513   if (old_thread_list.GetSize(false) == 0) {
514     // Make up the thread the first time this is called so we can setup our one
515     // and only core thread state.
516     ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
517 
518     if (core_objfile) {
519       const uint32_t num_threads = core_objfile->GetNumThreadContexts();
520       for (lldb::tid_t tid = 0; tid < num_threads; ++tid) {
521         ThreadSP thread_sp(new ThreadMachCore(*this, tid));
522         new_thread_list.AddThread(thread_sp);
523       }
524     }
525   } else {
526     const uint32_t num_threads = old_thread_list.GetSize(false);
527     for (uint32_t i = 0; i < num_threads; ++i)
528       new_thread_list.AddThread(old_thread_list.GetThreadAtIndex(i, false));
529   }
530   return new_thread_list.GetSize(false) > 0;
531 }
532 
533 void ProcessMachCore::RefreshStateAfterStop() {
534   // Let all threads recover from stopping and do any clean up based on the
535   // previous thread state (if any).
536   m_thread_list.RefreshStateAfterStop();
537   // SetThreadStopInfo (m_last_stop_packet);
538 }
539 
540 Status ProcessMachCore::DoDestroy() { return Status(); }
541 
542 // Process Queries
543 
544 bool ProcessMachCore::IsAlive() { return true; }
545 
546 bool ProcessMachCore::WarnBeforeDetach() const { return false; }
547 
548 // Process Memory
549 size_t ProcessMachCore::ReadMemory(addr_t addr, void *buf, size_t size,
550                                    Status &error) {
551   // Don't allow the caching that lldb_private::Process::ReadMemory does since
552   // in core files we have it all cached our our core file anyway.
553   return DoReadMemory(addr, buf, size, error);
554 }
555 
556 size_t ProcessMachCore::DoReadMemory(addr_t addr, void *buf, size_t size,
557                                      Status &error) {
558   ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
559   size_t bytes_read = 0;
560 
561   if (core_objfile) {
562     // Segments are not always contiguous in mach-o core files. We have core
563     // files that have segments like:
564     //            Address    Size       File off   File size
565     //            ---------- ---------- ---------- ----------
566     // LC_SEGMENT 0x000f6000 0x00001000 0x1d509ee8 0x00001000 --- ---   0
567     // 0x00000000 __TEXT LC_SEGMENT 0x0f600000 0x00100000 0x1d50aee8 0x00100000
568     // --- ---   0 0x00000000 __TEXT LC_SEGMENT 0x000f7000 0x00001000
569     // 0x1d60aee8 0x00001000 --- ---   0 0x00000000 __TEXT
570     //
571     // Any if the user executes the following command:
572     //
573     // (lldb) mem read 0xf6ff0
574     //
575     // We would attempt to read 32 bytes from 0xf6ff0 but would only get 16
576     // unless we loop through consecutive memory ranges that are contiguous in
577     // the address space, but not in the file data.
578     while (bytes_read < size) {
579       const addr_t curr_addr = addr + bytes_read;
580       const VMRangeToFileOffset::Entry *core_memory_entry =
581           m_core_aranges.FindEntryThatContains(curr_addr);
582 
583       if (core_memory_entry) {
584         const addr_t offset = curr_addr - core_memory_entry->GetRangeBase();
585         const addr_t bytes_left = core_memory_entry->GetRangeEnd() - curr_addr;
586         const size_t bytes_to_read =
587             std::min(size - bytes_read, (size_t)bytes_left);
588         const size_t curr_bytes_read = core_objfile->CopyData(
589             core_memory_entry->data.GetRangeBase() + offset, bytes_to_read,
590             (char *)buf + bytes_read);
591         if (curr_bytes_read == 0)
592           break;
593         bytes_read += curr_bytes_read;
594       } else {
595         // Only set the error if we didn't read any bytes
596         if (bytes_read == 0)
597           error.SetErrorStringWithFormat(
598               "core file does not contain 0x%" PRIx64, curr_addr);
599         break;
600       }
601     }
602   }
603 
604   return bytes_read;
605 }
606 
607 Status ProcessMachCore::GetMemoryRegionInfo(addr_t load_addr,
608                                             MemoryRegionInfo &region_info) {
609   region_info.Clear();
610   const VMRangeToPermissions::Entry *permission_entry =
611       m_core_range_infos.FindEntryThatContainsOrFollows(load_addr);
612   if (permission_entry) {
613     if (permission_entry->Contains(load_addr)) {
614       region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase());
615       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd());
616       const Flags permissions(permission_entry->data);
617       region_info.SetReadable(permissions.Test(ePermissionsReadable)
618                                   ? MemoryRegionInfo::eYes
619                                   : MemoryRegionInfo::eNo);
620       region_info.SetWritable(permissions.Test(ePermissionsWritable)
621                                   ? MemoryRegionInfo::eYes
622                                   : MemoryRegionInfo::eNo);
623       region_info.SetExecutable(permissions.Test(ePermissionsExecutable)
624                                     ? MemoryRegionInfo::eYes
625                                     : MemoryRegionInfo::eNo);
626       region_info.SetMapped(MemoryRegionInfo::eYes);
627     } else if (load_addr < permission_entry->GetRangeBase()) {
628       region_info.GetRange().SetRangeBase(load_addr);
629       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeBase());
630       region_info.SetReadable(MemoryRegionInfo::eNo);
631       region_info.SetWritable(MemoryRegionInfo::eNo);
632       region_info.SetExecutable(MemoryRegionInfo::eNo);
633       region_info.SetMapped(MemoryRegionInfo::eNo);
634     }
635     return Status();
636   }
637 
638   region_info.GetRange().SetRangeBase(load_addr);
639   region_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
640   region_info.SetReadable(MemoryRegionInfo::eNo);
641   region_info.SetWritable(MemoryRegionInfo::eNo);
642   region_info.SetExecutable(MemoryRegionInfo::eNo);
643   region_info.SetMapped(MemoryRegionInfo::eNo);
644   return Status();
645 }
646 
647 void ProcessMachCore::Clear() { m_thread_list.Clear(); }
648 
649 void ProcessMachCore::Initialize() {
650   static llvm::once_flag g_once_flag;
651 
652   llvm::call_once(g_once_flag, []() {
653     PluginManager::RegisterPlugin(GetPluginNameStatic(),
654                                   GetPluginDescriptionStatic(), CreateInstance);
655   });
656 }
657 
658 addr_t ProcessMachCore::GetImageInfoAddress() {
659   // If we found both a user-process dyld and a kernel binary, we need to
660   // decide which to prefer.
661   if (GetCorefilePreference() == eKernelCorefile) {
662     if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
663       return m_mach_kernel_addr;
664     }
665     return m_dyld_addr;
666   } else {
667     if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
668       return m_dyld_addr;
669     }
670     return m_mach_kernel_addr;
671   }
672 }
673 
674 lldb_private::ObjectFile *ProcessMachCore::GetCoreObjectFile() {
675   return m_core_module_sp->GetObjectFile();
676 }
677