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