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