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