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 <cerrno>
10 #include <cstdlib>
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/SectionLoadList.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
27 #include "lldb/Utility/DataBuffer.h"
28 #include "lldb/Utility/LLDBLog.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/DynamicLoader/Static/DynamicLoaderStatic.h"
42 #include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
43 
44 #include <memory>
45 #include <mutex>
46 
47 using namespace lldb;
48 using namespace lldb_private;
49 
50 LLDB_PLUGIN_DEFINE(ProcessMachCore)
51 
52 llvm::StringRef 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                                                 bool can_connect) {
64   lldb::ProcessSP process_sp;
65   if (crash_file && !can_connect) {
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     : PostMortemProcess(target_sp, listener_sp), m_core_aranges(),
113       m_core_range_infos(), m_core_module_sp(), m_core_file(core_file),
114       m_dyld_addr(LLDB_INVALID_ADDRESS),
115       m_mach_kernel_addr(LLDB_INVALID_ADDRESS) {}
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 bool ProcessMachCore::GetDynamicLoaderAddress(lldb::addr_t addr) {
128   Log *log(GetLog(LLDBLog::DynamicLoader | LLDBLog::Process));
129   llvm::MachO::mach_header header;
130   Status error;
131   if (DoReadMemory(addr, &header, sizeof(header), error) != sizeof(header))
132     return false;
133   if (header.magic == llvm::MachO::MH_CIGAM ||
134       header.magic == llvm::MachO::MH_CIGAM_64) {
135     header.magic = llvm::ByteSwap_32(header.magic);
136     header.cputype = llvm::ByteSwap_32(header.cputype);
137     header.cpusubtype = llvm::ByteSwap_32(header.cpusubtype);
138     header.filetype = llvm::ByteSwap_32(header.filetype);
139     header.ncmds = llvm::ByteSwap_32(header.ncmds);
140     header.sizeofcmds = llvm::ByteSwap_32(header.sizeofcmds);
141     header.flags = llvm::ByteSwap_32(header.flags);
142   }
143 
144   // TODO: swap header if needed...
145   // printf("0x%16.16" PRIx64 ": magic = 0x%8.8x, file_type= %u\n", vaddr,
146   // header.magic, header.filetype);
147   if (header.magic == llvm::MachO::MH_MAGIC ||
148       header.magic == llvm::MachO::MH_MAGIC_64) {
149     // Check MH_EXECUTABLE to see if we can find the mach image that contains
150     // the shared library list. The dynamic loader (dyld) is what contains the
151     // list for user applications, and the mach kernel contains a global that
152     // has the list of kexts to load
153     switch (header.filetype) {
154     case llvm::MachO::MH_DYLINKER:
155       // printf("0x%16.16" PRIx64 ": file_type = MH_DYLINKER\n", vaddr);
156       // Address of dyld "struct mach_header" in the core file
157       LLDB_LOGF(log,
158                 "ProcessMachCore::GetDynamicLoaderAddress found a user "
159                 "process dyld binary image at 0x%" PRIx64,
160                 addr);
161       m_dyld_addr = addr;
162       return true;
163 
164     case llvm::MachO::MH_EXECUTE:
165       // printf("0x%16.16" PRIx64 ": file_type = MH_EXECUTE\n", vaddr);
166       // Check MH_EXECUTABLE file types to see if the dynamic link object flag
167       // is NOT set. If it isn't, then we have a mach_kernel.
168       if ((header.flags & llvm::MachO::MH_DYLDLINK) == 0) {
169         LLDB_LOGF(log,
170                   "ProcessMachCore::GetDynamicLoaderAddress found a mach "
171                   "kernel binary image at 0x%" PRIx64,
172                   addr);
173         // Address of the mach kernel "struct mach_header" in the core file.
174         m_mach_kernel_addr = addr;
175         return true;
176       }
177       break;
178     }
179   }
180   return false;
181 }
182 
183 // We have a hint about a binary -- a UUID, possibly a load address.
184 // Try to load a file with that UUID into lldb, and if we have a load
185 // address, set it correctly.  Else assume that the binary was loaded
186 // with no slide.
187 static bool load_standalone_binary(UUID uuid, addr_t value,
188                                    bool value_is_offset, Target &target) {
189   if (uuid.IsValid()) {
190     ModuleSpec module_spec;
191     module_spec.GetUUID() = uuid;
192 
193     // Look up UUID in global module cache before attempting
194     // dsymForUUID-like action.
195     ModuleSP module_sp;
196     Status error = ModuleList::GetSharedModule(module_spec, module_sp, nullptr,
197                                                nullptr, nullptr);
198 
199     if (!module_sp.get()) {
200       // Force a a dsymForUUID lookup, if that tool is available.
201       if (!module_spec.GetSymbolFileSpec())
202         Symbols::DownloadObjectAndSymbolFile(module_spec, true);
203 
204       if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
205         module_sp = std::make_shared<Module>(module_spec);
206       }
207     }
208 
209     // If we couldn't find the binary anywhere else, as a last resort,
210     // read it out of memory in the corefile.
211     if (!module_sp.get() && value != LLDB_INVALID_ADDRESS && !value_is_offset) {
212       char namebuf[80];
213       snprintf(namebuf, sizeof(namebuf), "mem-image-0x%" PRIx64, value);
214       module_sp =
215           target.GetProcessSP()->ReadModuleFromMemory(FileSpec(namebuf), value);
216     }
217 
218     if (module_sp.get()) {
219       target.SetArchitecture(module_sp->GetObjectFile()->GetArchitecture());
220       target.GetImages().AppendIfNeeded(module_sp, false);
221 
222       bool changed = false;
223       if (module_sp->GetObjectFile()) {
224         if (value != LLDB_INVALID_ADDRESS) {
225           module_sp->SetLoadAddress(target, value, value_is_offset, changed);
226         } else {
227           // No address/offset/slide, load the binary at file address,
228           // offset 0.
229           const bool value_is_slide = true;
230           module_sp->SetLoadAddress(target, 0, value_is_slide, changed);
231         }
232       } else {
233         // In-memory image, load at its true address, offset 0.
234         const bool value_is_slide = true;
235         module_sp->SetLoadAddress(target, 0, value_is_slide, changed);
236       }
237 
238       ModuleList added_module;
239       added_module.Append(module_sp, false);
240       target.ModulesDidLoad(added_module);
241 
242       // Flush info in the process (stack frames, etc).
243       ProcessSP process_sp(target.GetProcessSP());
244       if (process_sp)
245         process_sp->Flush();
246 
247       return true;
248     }
249   }
250   return false;
251 }
252 
253 // Process Control
254 Status ProcessMachCore::DoLoadCore() {
255   Log *log(GetLog(LLDBLog::DynamicLoader | LLDBLog::Process));
256   Status error;
257   if (!m_core_module_sp) {
258     error.SetErrorString("invalid core module");
259     return error;
260   }
261 
262   ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
263   if (core_objfile == nullptr) {
264     error.SetErrorString("invalid core object file");
265     return error;
266   }
267 
268   if (core_objfile->GetNumThreadContexts() == 0) {
269     error.SetErrorString("core file doesn't contain any LC_THREAD load "
270                          "commands, or the LC_THREAD architecture is not "
271                          "supported in this lldb");
272     return error;
273   }
274 
275   SectionList *section_list = core_objfile->GetSectionList();
276   if (section_list == nullptr) {
277     error.SetErrorString("core file has no sections");
278     return error;
279   }
280 
281   const uint32_t num_sections = section_list->GetNumSections(0);
282   if (num_sections == 0) {
283     error.SetErrorString("core file has no sections");
284     return error;
285   }
286 
287   SetCanJIT(false);
288 
289   llvm::MachO::mach_header header;
290   DataExtractor data(&header, sizeof(header),
291                      m_core_module_sp->GetArchitecture().GetByteOrder(),
292                      m_core_module_sp->GetArchitecture().GetAddressByteSize());
293 
294   bool ranges_are_sorted = true;
295   addr_t vm_addr = 0;
296   for (uint32_t i = 0; i < num_sections; ++i) {
297     Section *section = section_list->GetSectionAtIndex(i).get();
298     if (section && section->GetFileSize() > 0) {
299       lldb::addr_t section_vm_addr = section->GetFileAddress();
300       FileRange file_range(section->GetFileOffset(), section->GetFileSize());
301       VMRangeToFileOffset::Entry range_entry(
302           section_vm_addr, section->GetByteSize(), file_range);
303 
304       if (vm_addr > section_vm_addr)
305         ranges_are_sorted = false;
306       vm_addr = section->GetFileAddress();
307       VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back();
308 
309       if (last_entry &&
310           last_entry->GetRangeEnd() == range_entry.GetRangeBase() &&
311           last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase()) {
312         last_entry->SetRangeEnd(range_entry.GetRangeEnd());
313         last_entry->data.SetRangeEnd(range_entry.data.GetRangeEnd());
314       } else {
315         m_core_aranges.Append(range_entry);
316       }
317       // Some core files don't fill in the permissions correctly. If that is
318       // the case assume read + execute so clients don't think the memory is
319       // not readable, or executable. The memory isn't writable since this
320       // plug-in doesn't implement DoWriteMemory.
321       uint32_t permissions = section->GetPermissions();
322       if (permissions == 0)
323         permissions = lldb::ePermissionsReadable | lldb::ePermissionsExecutable;
324       m_core_range_infos.Append(VMRangeToPermissions::Entry(
325           section_vm_addr, section->GetByteSize(), permissions));
326     }
327   }
328   if (!ranges_are_sorted) {
329     m_core_aranges.Sort();
330     m_core_range_infos.Sort();
331   }
332 
333   bool found_main_binary_definitively = false;
334 
335   addr_t objfile_binary_value;
336   bool objfile_binary_value_is_offset;
337   UUID objfile_binary_uuid;
338   ObjectFile::BinaryType type;
339   if (core_objfile->GetCorefileMainBinaryInfo(objfile_binary_value,
340                                               objfile_binary_value_is_offset,
341                                               objfile_binary_uuid, type)) {
342     if (log) {
343       log->Printf(
344           "ProcessMachCore::DoLoadCore: using binary hint from 'main bin spec' "
345           "LC_NOTE with UUID %s value 0x%" PRIx64
346           " value is offset %d and type %d",
347           objfile_binary_uuid.GetAsString().c_str(), objfile_binary_value,
348           objfile_binary_value_is_offset, type);
349     }
350     if (objfile_binary_value != LLDB_INVALID_ADDRESS &&
351         !objfile_binary_value_is_offset) {
352       if (type == ObjectFile::eBinaryTypeUser) {
353         m_dyld_addr = objfile_binary_value;
354         m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
355         found_main_binary_definitively = true;
356       }
357       if (type == ObjectFile::eBinaryTypeKernel) {
358         m_mach_kernel_addr = objfile_binary_value;
359         m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
360         found_main_binary_definitively = true;
361       }
362     }
363     if (!found_main_binary_definitively) {
364       // ObjectFile::eBinaryTypeStandalone, undeclared types
365       if (load_standalone_binary(objfile_binary_uuid, objfile_binary_value,
366                                  objfile_binary_value_is_offset, GetTarget())) {
367         found_main_binary_definitively = true;
368         m_dyld_plugin_name = DynamicLoaderStatic::GetPluginNameStatic();
369       }
370     }
371   }
372 
373   // This checks for the presence of an LC_IDENT string in a core file;
374   // LC_IDENT is very obsolete and should not be used in new code, but if the
375   // load command is present, let's use the contents.
376   UUID ident_uuid;
377   addr_t ident_binary_addr = LLDB_INVALID_ADDRESS;
378   if (!found_main_binary_definitively) {
379     std::string corefile_identifier = core_objfile->GetIdentifierString();
380 
381     // Search for UUID= and stext= strings in the identifier str.
382     if (corefile_identifier.find("UUID=") != std::string::npos) {
383       size_t p = corefile_identifier.find("UUID=") + strlen("UUID=");
384       std::string uuid_str = corefile_identifier.substr(p, 36);
385       ident_uuid.SetFromStringRef(uuid_str);
386       if (log)
387         log->Printf("Got a UUID from LC_IDENT/kern ver str LC_NOTE: %s",
388                     ident_uuid.GetAsString().c_str());
389     }
390     if (corefile_identifier.find("stext=") != std::string::npos) {
391       size_t p = corefile_identifier.find("stext=") + strlen("stext=");
392       if (corefile_identifier[p] == '0' && corefile_identifier[p + 1] == 'x') {
393         ident_binary_addr =
394             ::strtoul(corefile_identifier.c_str() + p, nullptr, 16);
395         if (log)
396           log->Printf("Got a load address from LC_IDENT/kern ver str "
397                       "LC_NOTE: 0x%" PRIx64,
398                       ident_binary_addr);
399       }
400     }
401 
402     // Search for a "Darwin Kernel" str indicating kernel; else treat as
403     // standalone
404     if (corefile_identifier.find("Darwin Kernel") != std::string::npos &&
405         ident_uuid.IsValid() && ident_binary_addr != LLDB_INVALID_ADDRESS) {
406       if (log)
407         log->Printf("ProcessMachCore::DoLoadCore: Found kernel binary via "
408                     "LC_IDENT/kern ver str LC_NOTE");
409       m_mach_kernel_addr = ident_binary_addr;
410       found_main_binary_definitively = true;
411     } else if (ident_uuid.IsValid()) {
412       // We have no address specified, only a UUID.  Load it at the file
413       // address.
414       const bool value_is_offset = false;
415       if (load_standalone_binary(ident_uuid, ident_binary_addr, value_is_offset,
416                                  GetTarget())) {
417         found_main_binary_definitively = true;
418         m_dyld_plugin_name = DynamicLoaderStatic::GetPluginNameStatic();
419       }
420     }
421   }
422 
423   bool did_load_extra_binaries = core_objfile->LoadCoreFileImages(*this);
424   // If we have a "all image infos" LC_NOTE, try to load all of the
425   // binaries listed, and set their Section load addresses in the Target.
426   if (found_main_binary_definitively == false && did_load_extra_binaries) {
427     m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
428     found_main_binary_definitively = true;
429   }
430 
431   if (!found_main_binary_definitively &&
432       (m_dyld_addr == LLDB_INVALID_ADDRESS ||
433        m_mach_kernel_addr == LLDB_INVALID_ADDRESS)) {
434     // We need to locate the main executable in the memory ranges we have in
435     // the core file.  We need to search for both a user-process dyld binary
436     // and a kernel binary in memory; we must look at all the pages in the
437     // binary so we don't miss one or the other.  Step through all memory
438     // segments searching for a kernel binary and for a user process dyld --
439     // we'll decide which to prefer later if both are present.
440 
441     const size_t num_core_aranges = m_core_aranges.GetSize();
442     for (size_t i = 0; i < num_core_aranges; ++i) {
443       const VMRangeToFileOffset::Entry *entry =
444           m_core_aranges.GetEntryAtIndex(i);
445       lldb::addr_t section_vm_addr_start = entry->GetRangeBase();
446       lldb::addr_t section_vm_addr_end = entry->GetRangeEnd();
447       for (lldb::addr_t section_vm_addr = section_vm_addr_start;
448            section_vm_addr < section_vm_addr_end; section_vm_addr += 0x1000) {
449         GetDynamicLoaderAddress(section_vm_addr);
450       }
451     }
452   }
453 
454   if (!found_main_binary_definitively &&
455       m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
456     // In the case of multiple kernel images found in the core file via
457     // exhaustive search, we may not pick the correct one.  See if the
458     // DynamicLoaderDarwinKernel's search heuristics might identify the correct
459     // one. Most of the time, I expect the address from SearchForDarwinKernel()
460     // will be the same as the address we found via exhaustive search.
461 
462     if (!GetTarget().GetArchitecture().IsValid() && m_core_module_sp.get()) {
463       GetTarget().SetArchitecture(m_core_module_sp->GetArchitecture());
464     }
465 
466     // SearchForDarwinKernel will end up calling back into this this class in
467     // the GetImageInfoAddress method which will give it the
468     // m_mach_kernel_addr/m_dyld_addr it already has.  Save that aside and set
469     // m_mach_kernel_addr/m_dyld_addr to an invalid address temporarily so
470     // DynamicLoaderDarwinKernel does a real search for the kernel using its
471     // own heuristics.
472 
473     addr_t saved_mach_kernel_addr = m_mach_kernel_addr;
474     addr_t saved_user_dyld_addr = m_dyld_addr;
475     m_mach_kernel_addr = LLDB_INVALID_ADDRESS;
476     m_dyld_addr = LLDB_INVALID_ADDRESS;
477 
478     addr_t better_kernel_address =
479         DynamicLoaderDarwinKernel::SearchForDarwinKernel(this);
480 
481     m_mach_kernel_addr = saved_mach_kernel_addr;
482     m_dyld_addr = saved_user_dyld_addr;
483 
484     if (better_kernel_address != LLDB_INVALID_ADDRESS) {
485       LLDB_LOGF(log, "ProcessMachCore::DoLoadCore: Using the kernel address "
486                      "from DynamicLoaderDarwinKernel");
487       m_mach_kernel_addr = better_kernel_address;
488     }
489   }
490 
491   if (m_dyld_plugin_name.empty()) {
492     // If we found both a user-process dyld and a kernel binary, we need to
493     // decide which to prefer.
494     if (GetCorefilePreference() == eKernelCorefile) {
495       if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
496         LLDB_LOGF(log,
497                   "ProcessMachCore::DoLoadCore: Using kernel corefile image "
498                   "at 0x%" PRIx64,
499                   m_mach_kernel_addr);
500         m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
501       } else if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
502         LLDB_LOGF(log,
503                   "ProcessMachCore::DoLoadCore: Using user process dyld "
504                   "image at 0x%" PRIx64,
505                   m_dyld_addr);
506         m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
507       }
508     } else {
509       if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
510         LLDB_LOGF(log,
511                   "ProcessMachCore::DoLoadCore: Using user process dyld "
512                   "image at 0x%" PRIx64,
513                   m_dyld_addr);
514         m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
515       } else if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
516         LLDB_LOGF(log,
517                   "ProcessMachCore::DoLoadCore: Using kernel corefile image "
518                   "at 0x%" PRIx64,
519                   m_mach_kernel_addr);
520         m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
521       }
522     }
523   }
524 
525   if (m_dyld_plugin_name != DynamicLoaderMacOSXDYLD::GetPluginNameStatic()) {
526     // For non-user process core files, the permissions on the core file
527     // segments are usually meaningless, they may be just "read", because we're
528     // dealing with kernel coredumps or early startup coredumps and the dumper
529     // is grabbing pages of memory without knowing what they are.  If they
530     // aren't marked as "executable", that can break the unwinder which will
531     // check a pc value to see if it is in an executable segment and stop the
532     // backtrace early if it is not ("executable" and "unknown" would both be
533     // fine, but "not executable" will break the unwinder).
534     size_t core_range_infos_size = m_core_range_infos.GetSize();
535     for (size_t i = 0; i < core_range_infos_size; i++) {
536       VMRangeToPermissions::Entry *ent =
537           m_core_range_infos.GetMutableEntryAtIndex(i);
538       ent->data = lldb::ePermissionsReadable | lldb::ePermissionsExecutable;
539     }
540   }
541 
542   // Even if the architecture is set in the target, we need to override it to
543   // match the core file which is always single arch.
544   ArchSpec arch(m_core_module_sp->GetArchitecture());
545   if (arch.GetCore() == ArchSpec::eCore_x86_32_i486) {
546     arch = Platform::GetAugmentedArchSpec(GetTarget().GetPlatform().get(), "i386");
547   }
548   if (arch.IsValid())
549     GetTarget().SetArchitecture(arch);
550 
551   addr_t address_mask = core_objfile->GetAddressMask();
552   if (address_mask != 0) {
553     SetCodeAddressMask(address_mask);
554     SetDataAddressMask(address_mask);
555   }
556   return error;
557 }
558 
559 lldb_private::DynamicLoader *ProcessMachCore::GetDynamicLoader() {
560   if (m_dyld_up.get() == nullptr)
561     m_dyld_up.reset(DynamicLoader::FindPlugin(this, m_dyld_plugin_name));
562   return m_dyld_up.get();
563 }
564 
565 bool ProcessMachCore::DoUpdateThreadList(ThreadList &old_thread_list,
566                                          ThreadList &new_thread_list) {
567   if (old_thread_list.GetSize(false) == 0) {
568     // Make up the thread the first time this is called so we can setup our one
569     // and only core thread state.
570     ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
571 
572     if (core_objfile) {
573       const uint32_t num_threads = core_objfile->GetNumThreadContexts();
574       for (lldb::tid_t tid = 0; tid < num_threads; ++tid) {
575         ThreadSP thread_sp(new ThreadMachCore(*this, tid));
576         new_thread_list.AddThread(thread_sp);
577       }
578     }
579   } else {
580     const uint32_t num_threads = old_thread_list.GetSize(false);
581     for (uint32_t i = 0; i < num_threads; ++i)
582       new_thread_list.AddThread(old_thread_list.GetThreadAtIndex(i, false));
583   }
584   return new_thread_list.GetSize(false) > 0;
585 }
586 
587 void ProcessMachCore::RefreshStateAfterStop() {
588   // Let all threads recover from stopping and do any clean up based on the
589   // previous thread state (if any).
590   m_thread_list.RefreshStateAfterStop();
591   // SetThreadStopInfo (m_last_stop_packet);
592 }
593 
594 Status ProcessMachCore::DoDestroy() { return Status(); }
595 
596 // Process Queries
597 
598 bool ProcessMachCore::IsAlive() { return true; }
599 
600 bool ProcessMachCore::WarnBeforeDetach() const { return false; }
601 
602 // Process Memory
603 size_t ProcessMachCore::ReadMemory(addr_t addr, void *buf, size_t size,
604                                    Status &error) {
605   // Don't allow the caching that lldb_private::Process::ReadMemory does since
606   // in core files we have it all cached our our core file anyway.
607   return DoReadMemory(addr, buf, size, error);
608 }
609 
610 size_t ProcessMachCore::DoReadMemory(addr_t addr, void *buf, size_t size,
611                                      Status &error) {
612   ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
613   size_t bytes_read = 0;
614 
615   if (core_objfile) {
616     // Segments are not always contiguous in mach-o core files. We have core
617     // files that have segments like:
618     //            Address    Size       File off   File size
619     //            ---------- ---------- ---------- ----------
620     // LC_SEGMENT 0x000f6000 0x00001000 0x1d509ee8 0x00001000 --- ---   0
621     // 0x00000000 __TEXT LC_SEGMENT 0x0f600000 0x00100000 0x1d50aee8 0x00100000
622     // --- ---   0 0x00000000 __TEXT LC_SEGMENT 0x000f7000 0x00001000
623     // 0x1d60aee8 0x00001000 --- ---   0 0x00000000 __TEXT
624     //
625     // Any if the user executes the following command:
626     //
627     // (lldb) mem read 0xf6ff0
628     //
629     // We would attempt to read 32 bytes from 0xf6ff0 but would only get 16
630     // unless we loop through consecutive memory ranges that are contiguous in
631     // the address space, but not in the file data.
632     while (bytes_read < size) {
633       const addr_t curr_addr = addr + bytes_read;
634       const VMRangeToFileOffset::Entry *core_memory_entry =
635           m_core_aranges.FindEntryThatContains(curr_addr);
636 
637       if (core_memory_entry) {
638         const addr_t offset = curr_addr - core_memory_entry->GetRangeBase();
639         const addr_t bytes_left = core_memory_entry->GetRangeEnd() - curr_addr;
640         const size_t bytes_to_read =
641             std::min(size - bytes_read, (size_t)bytes_left);
642         const size_t curr_bytes_read = core_objfile->CopyData(
643             core_memory_entry->data.GetRangeBase() + offset, bytes_to_read,
644             (char *)buf + bytes_read);
645         if (curr_bytes_read == 0)
646           break;
647         bytes_read += curr_bytes_read;
648       } else {
649         // Only set the error if we didn't read any bytes
650         if (bytes_read == 0)
651           error.SetErrorStringWithFormat(
652               "core file does not contain 0x%" PRIx64, curr_addr);
653         break;
654       }
655     }
656   }
657 
658   return bytes_read;
659 }
660 
661 Status ProcessMachCore::DoGetMemoryRegionInfo(addr_t load_addr,
662                                               MemoryRegionInfo &region_info) {
663   region_info.Clear();
664   const VMRangeToPermissions::Entry *permission_entry =
665       m_core_range_infos.FindEntryThatContainsOrFollows(load_addr);
666   if (permission_entry) {
667     if (permission_entry->Contains(load_addr)) {
668       region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase());
669       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd());
670       const Flags permissions(permission_entry->data);
671       region_info.SetReadable(permissions.Test(ePermissionsReadable)
672                                   ? MemoryRegionInfo::eYes
673                                   : MemoryRegionInfo::eNo);
674       region_info.SetWritable(permissions.Test(ePermissionsWritable)
675                                   ? MemoryRegionInfo::eYes
676                                   : MemoryRegionInfo::eNo);
677       region_info.SetExecutable(permissions.Test(ePermissionsExecutable)
678                                     ? MemoryRegionInfo::eYes
679                                     : MemoryRegionInfo::eNo);
680       region_info.SetMapped(MemoryRegionInfo::eYes);
681     } else if (load_addr < permission_entry->GetRangeBase()) {
682       region_info.GetRange().SetRangeBase(load_addr);
683       region_info.GetRange().SetRangeEnd(permission_entry->GetRangeBase());
684       region_info.SetReadable(MemoryRegionInfo::eNo);
685       region_info.SetWritable(MemoryRegionInfo::eNo);
686       region_info.SetExecutable(MemoryRegionInfo::eNo);
687       region_info.SetMapped(MemoryRegionInfo::eNo);
688     }
689     return Status();
690   }
691 
692   region_info.GetRange().SetRangeBase(load_addr);
693   region_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
694   region_info.SetReadable(MemoryRegionInfo::eNo);
695   region_info.SetWritable(MemoryRegionInfo::eNo);
696   region_info.SetExecutable(MemoryRegionInfo::eNo);
697   region_info.SetMapped(MemoryRegionInfo::eNo);
698   return Status();
699 }
700 
701 void ProcessMachCore::Clear() { m_thread_list.Clear(); }
702 
703 void ProcessMachCore::Initialize() {
704   static llvm::once_flag g_once_flag;
705 
706   llvm::call_once(g_once_flag, []() {
707     PluginManager::RegisterPlugin(GetPluginNameStatic(),
708                                   GetPluginDescriptionStatic(), CreateInstance);
709   });
710 }
711 
712 addr_t ProcessMachCore::GetImageInfoAddress() {
713   // If we found both a user-process dyld and a kernel binary, we need to
714   // decide which to prefer.
715   if (GetCorefilePreference() == eKernelCorefile) {
716     if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
717       return m_mach_kernel_addr;
718     }
719     return m_dyld_addr;
720   } else {
721     if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
722       return m_dyld_addr;
723     }
724     return m_mach_kernel_addr;
725   }
726 }
727 
728 lldb_private::ObjectFile *ProcessMachCore::GetCoreObjectFile() {
729   return m_core_module_sp->GetObjectFile();
730 }
731