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