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