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