Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / lldb / source / Plugins / Process / mach-core / ProcessMachCore.cpp
blobb11062a0224abc2f71f85eb47106b56a41de2643
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 //===----------------------------------------------------------------------===//
9 #include <cerrno>
10 #include <cstdlib>
12 #include "llvm/Support/MathExtras.h"
13 #include "llvm/Support/Threading.h"
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/AppleUuidCompatibility.h"
28 #include "lldb/Utility/DataBuffer.h"
29 #include "lldb/Utility/LLDBLog.h"
30 #include "lldb/Utility/Log.h"
31 #include "lldb/Utility/State.h"
32 #include "lldb/Utility/UUID.h"
34 #include "ProcessMachCore.h"
35 #include "Plugins/Process/Utility/StopInfoMachException.h"
36 #include "ThreadMachCore.h"
38 // Needed for the plug-in names for the dynamic loaders.
39 #include "lldb/Host/SafeMachO.h"
41 #include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
42 #include "Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h"
43 #include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
44 #include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
45 #include "Plugins/Platform/MacOSX/PlatformDarwinKernel.h"
47 #include <memory>
48 #include <mutex>
50 using namespace lldb;
51 using namespace lldb_private;
53 LLDB_PLUGIN_DEFINE(ProcessMachCore)
55 llvm::StringRef ProcessMachCore::GetPluginDescriptionStatic() {
56 return "Mach-O core file debugging plug-in.";
59 void ProcessMachCore::Terminate() {
60 PluginManager::UnregisterPlugin(ProcessMachCore::CreateInstance);
63 lldb::ProcessSP ProcessMachCore::CreateInstance(lldb::TargetSP target_sp,
64 ListenerSP listener_sp,
65 const FileSpec *crash_file,
66 bool can_connect) {
67 lldb::ProcessSP process_sp;
68 if (crash_file && !can_connect) {
69 const size_t header_size = sizeof(llvm::MachO::mach_header);
70 auto data_sp = FileSystem::Instance().CreateDataBuffer(
71 crash_file->GetPath(), header_size, 0);
72 if (data_sp && data_sp->GetByteSize() == header_size) {
73 DataExtractor data(data_sp, lldb::eByteOrderLittle, 4);
75 lldb::offset_t data_offset = 0;
76 llvm::MachO::mach_header mach_header;
77 if (ObjectFileMachO::ParseHeader(data, &data_offset, mach_header)) {
78 if (mach_header.filetype == llvm::MachO::MH_CORE)
79 process_sp = std::make_shared<ProcessMachCore>(target_sp, listener_sp,
80 *crash_file);
84 return process_sp;
87 bool ProcessMachCore::CanDebug(lldb::TargetSP target_sp,
88 bool plugin_specified_by_name) {
89 if (plugin_specified_by_name)
90 return true;
92 // For now we are just making sure the file exists for a given module
93 if (!m_core_module_sp && FileSystem::Instance().Exists(m_core_file)) {
94 // Don't add the Target's architecture to the ModuleSpec - we may be
95 // working with a core file that doesn't have the correct cpusubtype in the
96 // header but we should still try to use it -
97 // ModuleSpecList::FindMatchingModuleSpec enforces a strict arch mach.
98 ModuleSpec core_module_spec(m_core_file);
99 Status error(ModuleList::GetSharedModule(core_module_spec, m_core_module_sp,
100 nullptr, nullptr, nullptr));
102 if (m_core_module_sp) {
103 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
104 if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile)
105 return true;
108 return false;
111 // ProcessMachCore constructor
112 ProcessMachCore::ProcessMachCore(lldb::TargetSP target_sp,
113 ListenerSP listener_sp,
114 const FileSpec &core_file)
115 : PostMortemProcess(target_sp, listener_sp), m_core_aranges(),
116 m_core_range_infos(), m_core_module_sp(), m_core_file(core_file),
117 m_dyld_addr(LLDB_INVALID_ADDRESS),
118 m_mach_kernel_addr(LLDB_INVALID_ADDRESS) {}
120 // Destructor
121 ProcessMachCore::~ProcessMachCore() {
122 Clear();
123 // We need to call finalize on the process before destroying ourselves to
124 // make sure all of the broadcaster cleanup goes as planned. If we destruct
125 // this class, then Process::~Process() might have problems trying to fully
126 // destroy the broadcaster.
127 Finalize();
130 bool ProcessMachCore::CheckAddressForDyldOrKernel(lldb::addr_t addr,
131 addr_t &dyld,
132 addr_t &kernel) {
133 Log *log(GetLog(LLDBLog::DynamicLoader | LLDBLog::Process));
134 llvm::MachO::mach_header header;
135 Status error;
136 dyld = kernel = LLDB_INVALID_ADDRESS;
137 if (DoReadMemory(addr, &header, sizeof(header), error) != sizeof(header))
138 return false;
139 if (header.magic == llvm::MachO::MH_CIGAM ||
140 header.magic == llvm::MachO::MH_CIGAM_64) {
141 header.magic = llvm::byteswap<uint32_t>(header.magic);
142 header.cputype = llvm::byteswap<uint32_t>(header.cputype);
143 header.cpusubtype = llvm::byteswap<uint32_t>(header.cpusubtype);
144 header.filetype = llvm::byteswap<uint32_t>(header.filetype);
145 header.ncmds = llvm::byteswap<uint32_t>(header.ncmds);
146 header.sizeofcmds = llvm::byteswap<uint32_t>(header.sizeofcmds);
147 header.flags = llvm::byteswap<uint32_t>(header.flags);
150 if (header.magic == llvm::MachO::MH_MAGIC ||
151 header.magic == llvm::MachO::MH_MAGIC_64) {
152 // Check MH_EXECUTABLE to see if we can find the mach image that contains
153 // the shared library list. The dynamic loader (dyld) is what contains the
154 // list for user applications, and the mach kernel contains a global that
155 // has the list of kexts to load
156 switch (header.filetype) {
157 case llvm::MachO::MH_DYLINKER:
158 LLDB_LOGF(log,
159 "ProcessMachCore::%s found a user "
160 "process dyld binary image at 0x%" PRIx64,
161 __FUNCTION__, addr);
162 dyld = addr;
163 return true;
165 case llvm::MachO::MH_EXECUTE:
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::%s found a mach "
171 "kernel binary image at 0x%" PRIx64,
172 __FUNCTION__, addr);
173 // Address of the mach kernel "struct mach_header" in the core file.
174 kernel = addr;
175 return true;
177 break;
180 return false;
183 void ProcessMachCore::CreateMemoryRegions() {
184 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
185 SectionList *section_list = core_objfile->GetSectionList();
186 const uint32_t num_sections = section_list->GetNumSections(0);
188 bool ranges_are_sorted = true;
189 addr_t vm_addr = 0;
190 for (uint32_t i = 0; i < num_sections; ++i) {
191 Section *section = section_list->GetSectionAtIndex(i).get();
192 if (section && section->GetFileSize() > 0) {
193 lldb::addr_t section_vm_addr = section->GetFileAddress();
194 FileRange file_range(section->GetFileOffset(), section->GetFileSize());
195 VMRangeToFileOffset::Entry range_entry(
196 section_vm_addr, section->GetByteSize(), file_range);
198 if (vm_addr > section_vm_addr)
199 ranges_are_sorted = false;
200 vm_addr = section->GetFileAddress();
201 VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back();
203 if (last_entry &&
204 last_entry->GetRangeEnd() == range_entry.GetRangeBase() &&
205 last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase()) {
206 last_entry->SetRangeEnd(range_entry.GetRangeEnd());
207 last_entry->data.SetRangeEnd(range_entry.data.GetRangeEnd());
208 } else {
209 m_core_aranges.Append(range_entry);
211 // Some core files don't fill in the permissions correctly. If that is
212 // the case assume read + execute so clients don't think the memory is
213 // not readable, or executable. The memory isn't writable since this
214 // plug-in doesn't implement DoWriteMemory.
215 uint32_t permissions = section->GetPermissions();
216 if (permissions == 0)
217 permissions = lldb::ePermissionsReadable | lldb::ePermissionsExecutable;
218 m_core_range_infos.Append(VMRangeToPermissions::Entry(
219 section_vm_addr, section->GetByteSize(), permissions));
222 if (!ranges_are_sorted) {
223 m_core_aranges.Sort();
224 m_core_range_infos.Sort();
228 // Some corefiles have a UUID stored in a low memory
229 // address. We inspect a set list of addresses for
230 // the characters 'uuid' and 16 bytes later there will
231 // be a uuid_t UUID. If we can find a binary that
232 // matches the UUID, it is loaded with no slide in the target.
233 bool ProcessMachCore::LoadBinaryViaLowmemUUID() {
234 Log *log(GetLog(LLDBLog::DynamicLoader | LLDBLog::Process));
235 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
237 uint64_t lowmem_uuid_addresses[] = {0x2000204, 0x1000204, 0x1000020, 0x4204,
238 0x1204, 0x1020, 0x4020, 0xc00,
239 0xC0, 0};
241 for (uint64_t addr : lowmem_uuid_addresses) {
242 const VMRangeToFileOffset::Entry *core_memory_entry =
243 m_core_aranges.FindEntryThatContains(addr);
244 if (core_memory_entry) {
245 const addr_t offset = addr - core_memory_entry->GetRangeBase();
246 const addr_t bytes_left = core_memory_entry->GetRangeEnd() - addr;
247 // (4-bytes 'uuid' + 12 bytes pad for align + 16 bytes uuid_t) == 32 bytes
248 if (bytes_left >= 32) {
249 char strbuf[4];
250 if (core_objfile->CopyData(
251 core_memory_entry->data.GetRangeBase() + offset, 4, &strbuf) &&
252 strncmp("uuid", (char *)&strbuf, 4) == 0) {
253 uuid_t uuid_bytes;
254 if (core_objfile->CopyData(core_memory_entry->data.GetRangeBase() +
255 offset + 16,
256 sizeof(uuid_t), uuid_bytes)) {
257 UUID uuid(uuid_bytes, sizeof(uuid_t));
258 if (uuid.IsValid()) {
259 LLDB_LOGF(log,
260 "ProcessMachCore::LoadBinaryViaLowmemUUID: found "
261 "binary uuid %s at low memory address 0x%" PRIx64,
262 uuid.GetAsString().c_str(), addr);
263 // We have no address specified, only a UUID. Load it at the file
264 // address.
265 const bool value_is_offset = true;
266 const bool force_symbol_search = true;
267 const bool notify = true;
268 const bool set_address_in_target = true;
269 const bool allow_memory_image_last_resort = false;
270 if (DynamicLoader::LoadBinaryWithUUIDAndAddress(
271 this, llvm::StringRef(), uuid, 0, value_is_offset,
272 force_symbol_search, notify, set_address_in_target,
273 allow_memory_image_last_resort)) {
274 m_dyld_plugin_name = DynamicLoaderStatic::GetPluginNameStatic();
276 // We found metadata saying which binary should be loaded; don't
277 // try an exhaustive search.
278 return true;
285 return false;
288 bool ProcessMachCore::LoadBinariesViaMetadata() {
289 Log *log(GetLog(LLDBLog::DynamicLoader | LLDBLog::Process));
290 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
292 addr_t objfile_binary_value;
293 bool objfile_binary_value_is_offset;
294 UUID objfile_binary_uuid;
295 ObjectFile::BinaryType type;
297 // This will be set to true if we had a metadata hint
298 // specifying a UUID or address -- and we should not fall back
299 // to doing an exhaustive search.
300 bool found_binary_spec_in_metadata = false;
302 if (core_objfile->GetCorefileMainBinaryInfo(objfile_binary_value,
303 objfile_binary_value_is_offset,
304 objfile_binary_uuid, type)) {
305 if (log) {
306 log->Printf("ProcessMachCore::LoadBinariesViaMetadata: using binary hint "
307 "from 'main bin spec' "
308 "LC_NOTE with UUID %s value 0x%" PRIx64
309 " value is offset %d and type %d",
310 objfile_binary_uuid.GetAsString().c_str(),
311 objfile_binary_value, objfile_binary_value_is_offset, type);
313 found_binary_spec_in_metadata = true;
315 // If this is the xnu kernel, don't load it now. Note the correct
316 // DynamicLoader plugin to use, and the address of the kernel, and
317 // let the DynamicLoader handle the finding & loading of the binary.
318 if (type == ObjectFile::eBinaryTypeKernel) {
319 m_mach_kernel_addr = objfile_binary_value;
320 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
321 } else if (type == ObjectFile::eBinaryTypeUser) {
322 m_dyld_addr = objfile_binary_value;
323 m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
324 } else {
325 const bool force_symbol_search = true;
326 const bool notify = true;
327 const bool set_address_in_target = true;
328 const bool allow_memory_image_last_resort = false;
329 if (DynamicLoader::LoadBinaryWithUUIDAndAddress(
330 this, llvm::StringRef(), objfile_binary_uuid,
331 objfile_binary_value, objfile_binary_value_is_offset,
332 force_symbol_search, notify, set_address_in_target,
333 allow_memory_image_last_resort)) {
334 m_dyld_plugin_name = DynamicLoaderStatic::GetPluginNameStatic();
339 // This checks for the presence of an LC_IDENT string in a core file;
340 // LC_IDENT is very obsolete and should not be used in new code, but if the
341 // load command is present, let's use the contents.
342 UUID ident_uuid;
343 addr_t ident_binary_addr = LLDB_INVALID_ADDRESS;
344 std::string corefile_identifier = core_objfile->GetIdentifierString();
346 // Search for UUID= and stext= strings in the identifier str.
347 if (corefile_identifier.find("UUID=") != std::string::npos) {
348 size_t p = corefile_identifier.find("UUID=") + strlen("UUID=");
349 std::string uuid_str = corefile_identifier.substr(p, 36);
350 ident_uuid.SetFromStringRef(uuid_str);
351 if (log)
352 log->Printf("Got a UUID from LC_IDENT/kern ver str LC_NOTE: %s",
353 ident_uuid.GetAsString().c_str());
354 found_binary_spec_in_metadata = true;
356 if (corefile_identifier.find("stext=") != std::string::npos) {
357 size_t p = corefile_identifier.find("stext=") + strlen("stext=");
358 if (corefile_identifier[p] == '0' && corefile_identifier[p + 1] == 'x') {
359 ident_binary_addr =
360 ::strtoul(corefile_identifier.c_str() + p, nullptr, 16);
361 if (log)
362 log->Printf("Got a load address from LC_IDENT/kern ver str "
363 "LC_NOTE: 0x%" PRIx64,
364 ident_binary_addr);
365 found_binary_spec_in_metadata = true;
369 // Search for a "Darwin Kernel" str indicating kernel; else treat as
370 // standalone
371 if (corefile_identifier.find("Darwin Kernel") != std::string::npos &&
372 ident_uuid.IsValid() && ident_binary_addr != LLDB_INVALID_ADDRESS) {
373 if (log)
374 log->Printf(
375 "ProcessMachCore::LoadBinariesViaMetadata: Found kernel binary via "
376 "LC_IDENT/kern ver str LC_NOTE");
377 m_mach_kernel_addr = ident_binary_addr;
378 found_binary_spec_in_metadata = true;
379 } else if (ident_uuid.IsValid()) {
380 // We have no address specified, only a UUID. Load it at the file
381 // address.
382 const bool value_is_offset = false;
383 const bool force_symbol_search = true;
384 const bool notify = true;
385 const bool set_address_in_target = true;
386 const bool allow_memory_image_last_resort = false;
387 if (DynamicLoader::LoadBinaryWithUUIDAndAddress(
388 this, llvm::StringRef(), ident_uuid, ident_binary_addr,
389 value_is_offset, force_symbol_search, notify,
390 set_address_in_target, allow_memory_image_last_resort)) {
391 found_binary_spec_in_metadata = true;
392 m_dyld_plugin_name = DynamicLoaderStatic::GetPluginNameStatic();
396 // Finally, load any binaries noted by "load binary" LC_NOTEs in the
397 // corefile
398 if (core_objfile->LoadCoreFileImages(*this)) {
399 found_binary_spec_in_metadata = true;
400 m_dyld_plugin_name = DynamicLoaderStatic::GetPluginNameStatic();
403 if (!found_binary_spec_in_metadata && LoadBinaryViaLowmemUUID())
404 found_binary_spec_in_metadata = true;
406 // LoadCoreFileImges may have set the dynamic loader, e.g. in
407 // PlatformDarwinKernel::LoadPlatformBinaryAndSetup().
408 // If we now have a dynamic loader, save its name so we don't
409 // un-set it later.
410 if (m_dyld_up)
411 m_dyld_plugin_name = GetDynamicLoader()->GetPluginName();
413 return found_binary_spec_in_metadata;
416 void ProcessMachCore::LoadBinariesViaExhaustiveSearch() {
417 Log *log(GetLog(LLDBLog::DynamicLoader | LLDBLog::Process));
419 // Search the pages of the corefile for dyld or mach kernel
420 // binaries. There may be multiple things that look like a kernel
421 // in the corefile; disambiguating to the correct one can be difficult.
423 std::vector<addr_t> dylds_found;
424 std::vector<addr_t> kernels_found;
426 const size_t num_core_aranges = m_core_aranges.GetSize();
427 for (size_t i = 0; i < num_core_aranges; ++i) {
428 const VMRangeToFileOffset::Entry *entry = m_core_aranges.GetEntryAtIndex(i);
429 lldb::addr_t section_vm_addr_start = entry->GetRangeBase();
430 lldb::addr_t section_vm_addr_end = entry->GetRangeEnd();
431 for (lldb::addr_t section_vm_addr = section_vm_addr_start;
432 section_vm_addr < section_vm_addr_end; section_vm_addr += 0x1000) {
433 addr_t dyld, kernel;
434 if (CheckAddressForDyldOrKernel(section_vm_addr, dyld, kernel)) {
435 if (dyld != LLDB_INVALID_ADDRESS)
436 dylds_found.push_back(dyld);
437 if (kernel != LLDB_INVALID_ADDRESS)
438 kernels_found.push_back(kernel);
443 // If we found more than one dyld mach-o header in the corefile,
444 // pick the first one.
445 if (dylds_found.size() > 0)
446 m_dyld_addr = dylds_found[0];
447 if (kernels_found.size() > 0)
448 m_mach_kernel_addr = kernels_found[0];
450 // Zero or one kernels found, we're done.
451 if (kernels_found.size() < 2)
452 return;
454 // In the case of multiple kernel images found in the core file via
455 // exhaustive search, we may not pick the correct one. See if the
456 // DynamicLoaderDarwinKernel's search heuristics might identify the correct
457 // one.
459 // SearchForDarwinKernel will call this class' GetImageInfoAddress method
460 // which will give it the addresses we already have.
461 // Save those aside and set
462 // m_mach_kernel_addr/m_dyld_addr to an invalid address temporarily so
463 // DynamicLoaderDarwinKernel does a real search for the kernel using its
464 // own heuristics.
466 addr_t saved_mach_kernel_addr = m_mach_kernel_addr;
467 addr_t saved_user_dyld_addr = m_dyld_addr;
468 m_mach_kernel_addr = LLDB_INVALID_ADDRESS;
469 m_dyld_addr = LLDB_INVALID_ADDRESS;
471 addr_t better_kernel_address =
472 DynamicLoaderDarwinKernel::SearchForDarwinKernel(this);
474 m_mach_kernel_addr = saved_mach_kernel_addr;
475 m_dyld_addr = saved_user_dyld_addr;
477 if (better_kernel_address != LLDB_INVALID_ADDRESS) {
478 LLDB_LOGF(log,
479 "ProcessMachCore::%s: Using "
480 "the kernel address "
481 "from DynamicLoaderDarwinKernel",
482 __FUNCTION__);
483 m_mach_kernel_addr = better_kernel_address;
487 void ProcessMachCore::LoadBinariesAndSetDYLD() {
488 Log *log(GetLog(LLDBLog::DynamicLoader | LLDBLog::Process));
490 bool found_binary_spec_in_metadata = LoadBinariesViaMetadata();
491 if (!found_binary_spec_in_metadata)
492 LoadBinariesViaExhaustiveSearch();
494 if (m_dyld_plugin_name.empty()) {
495 // If we found both a user-process dyld and a kernel binary, we need to
496 // decide which to prefer.
497 if (GetCorefilePreference() == eKernelCorefile) {
498 if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
499 LLDB_LOGF(log,
500 "ProcessMachCore::%s: Using kernel "
501 "corefile image "
502 "at 0x%" PRIx64,
503 __FUNCTION__, m_mach_kernel_addr);
504 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
505 } else if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
506 LLDB_LOGF(log,
507 "ProcessMachCore::%s: Using user process dyld "
508 "image at 0x%" PRIx64,
509 __FUNCTION__, m_dyld_addr);
510 m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
512 } else {
513 if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
514 LLDB_LOGF(log,
515 "ProcessMachCore::%s: Using user process dyld "
516 "image at 0x%" PRIx64,
517 __FUNCTION__, m_dyld_addr);
518 m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
519 } else if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
520 LLDB_LOGF(log,
521 "ProcessMachCore::%s: Using kernel "
522 "corefile image "
523 "at 0x%" PRIx64,
524 __FUNCTION__, m_mach_kernel_addr);
525 m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
531 void ProcessMachCore::CleanupMemoryRegionPermissions() {
532 if (m_dyld_plugin_name != DynamicLoaderMacOSXDYLD::GetPluginNameStatic()) {
533 // For non-user process core files, the permissions on the core file
534 // segments are usually meaningless, they may be just "read", because we're
535 // dealing with kernel coredumps or early startup coredumps and the dumper
536 // is grabbing pages of memory without knowing what they are. If they
537 // aren't marked as "executable", that can break the unwinder which will
538 // check a pc value to see if it is in an executable segment and stop the
539 // backtrace early if it is not ("executable" and "unknown" would both be
540 // fine, but "not executable" will break the unwinder).
541 size_t core_range_infos_size = m_core_range_infos.GetSize();
542 for (size_t i = 0; i < core_range_infos_size; i++) {
543 VMRangeToPermissions::Entry *ent =
544 m_core_range_infos.GetMutableEntryAtIndex(i);
545 ent->data = lldb::ePermissionsReadable | lldb::ePermissionsExecutable;
550 // Process Control
551 Status ProcessMachCore::DoLoadCore() {
552 Status error;
553 if (!m_core_module_sp) {
554 error.SetErrorString("invalid core module");
555 return error;
558 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
559 if (core_objfile == nullptr) {
560 error.SetErrorString("invalid core object file");
561 return error;
564 SetCanJIT(false);
566 // The corefile's architecture is our best starting point.
567 ArchSpec arch(m_core_module_sp->GetArchitecture());
568 if (arch.IsValid())
569 GetTarget().SetArchitecture(arch);
571 CreateMemoryRegions();
573 LoadBinariesAndSetDYLD();
575 CleanupMemoryRegionPermissions();
577 AddressableBits addressable_bits = core_objfile->GetAddressableBits();
578 addressable_bits.SetProcessMasks(*this);
580 return error;
583 lldb_private::DynamicLoader *ProcessMachCore::GetDynamicLoader() {
584 if (m_dyld_up.get() == nullptr)
585 m_dyld_up.reset(DynamicLoader::FindPlugin(this, m_dyld_plugin_name));
586 return m_dyld_up.get();
589 bool ProcessMachCore::DoUpdateThreadList(ThreadList &old_thread_list,
590 ThreadList &new_thread_list) {
591 if (old_thread_list.GetSize(false) == 0) {
592 // Make up the thread the first time this is called so we can setup our one
593 // and only core thread state.
594 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
596 if (core_objfile) {
597 std::set<tid_t> used_tids;
598 const uint32_t num_threads = core_objfile->GetNumThreadContexts();
599 std::vector<tid_t> tids;
600 if (core_objfile->GetCorefileThreadExtraInfos(tids)) {
601 assert(tids.size() == num_threads);
603 // Find highest tid value.
604 tid_t highest_tid = 0;
605 for (uint32_t i = 0; i < num_threads; i++) {
606 if (tids[i] != LLDB_INVALID_THREAD_ID && tids[i] > highest_tid)
607 highest_tid = tids[i];
609 tid_t current_unused_tid = highest_tid + 1;
610 for (uint32_t i = 0; i < num_threads; i++) {
611 if (tids[i] == LLDB_INVALID_THREAD_ID) {
612 tids[i] = current_unused_tid++;
615 } else {
616 // No metadata, insert numbers sequentially from 0.
617 for (uint32_t i = 0; i < num_threads; i++) {
618 tids.push_back(i);
622 for (uint32_t i = 0; i < num_threads; i++) {
623 ThreadSP thread_sp =
624 std::make_shared<ThreadMachCore>(*this, tids[i], i);
625 new_thread_list.AddThread(thread_sp);
628 } else {
629 const uint32_t num_threads = old_thread_list.GetSize(false);
630 for (uint32_t i = 0; i < num_threads; ++i)
631 new_thread_list.AddThread(old_thread_list.GetThreadAtIndex(i, false));
633 return new_thread_list.GetSize(false) > 0;
636 void ProcessMachCore::RefreshStateAfterStop() {
637 // Let all threads recover from stopping and do any clean up based on the
638 // previous thread state (if any).
639 m_thread_list.RefreshStateAfterStop();
640 // SetThreadStopInfo (m_last_stop_packet);
643 Status ProcessMachCore::DoDestroy() { return Status(); }
645 // Process Queries
647 bool ProcessMachCore::IsAlive() { return true; }
649 bool ProcessMachCore::WarnBeforeDetach() const { return false; }
651 // Process Memory
652 size_t ProcessMachCore::ReadMemory(addr_t addr, void *buf, size_t size,
653 Status &error) {
654 // Don't allow the caching that lldb_private::Process::ReadMemory does since
655 // in core files we have it all cached our our core file anyway.
656 return DoReadMemory(addr, buf, size, error);
659 size_t ProcessMachCore::DoReadMemory(addr_t addr, void *buf, size_t size,
660 Status &error) {
661 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
662 size_t bytes_read = 0;
664 if (core_objfile) {
665 // Segments are not always contiguous in mach-o core files. We have core
666 // files that have segments like:
667 // Address Size File off File size
668 // ---------- ---------- ---------- ----------
669 // LC_SEGMENT 0x000f6000 0x00001000 0x1d509ee8 0x00001000 --- --- 0
670 // 0x00000000 __TEXT LC_SEGMENT 0x0f600000 0x00100000 0x1d50aee8 0x00100000
671 // --- --- 0 0x00000000 __TEXT LC_SEGMENT 0x000f7000 0x00001000
672 // 0x1d60aee8 0x00001000 --- --- 0 0x00000000 __TEXT
674 // Any if the user executes the following command:
676 // (lldb) mem read 0xf6ff0
678 // We would attempt to read 32 bytes from 0xf6ff0 but would only get 16
679 // unless we loop through consecutive memory ranges that are contiguous in
680 // the address space, but not in the file data.
681 while (bytes_read < size) {
682 const addr_t curr_addr = addr + bytes_read;
683 const VMRangeToFileOffset::Entry *core_memory_entry =
684 m_core_aranges.FindEntryThatContains(curr_addr);
686 if (core_memory_entry) {
687 const addr_t offset = curr_addr - core_memory_entry->GetRangeBase();
688 const addr_t bytes_left = core_memory_entry->GetRangeEnd() - curr_addr;
689 const size_t bytes_to_read =
690 std::min(size - bytes_read, (size_t)bytes_left);
691 const size_t curr_bytes_read = core_objfile->CopyData(
692 core_memory_entry->data.GetRangeBase() + offset, bytes_to_read,
693 (char *)buf + bytes_read);
694 if (curr_bytes_read == 0)
695 break;
696 bytes_read += curr_bytes_read;
697 } else {
698 // Only set the error if we didn't read any bytes
699 if (bytes_read == 0)
700 error.SetErrorStringWithFormat(
701 "core file does not contain 0x%" PRIx64, curr_addr);
702 break;
707 return bytes_read;
710 Status ProcessMachCore::DoGetMemoryRegionInfo(addr_t load_addr,
711 MemoryRegionInfo &region_info) {
712 region_info.Clear();
713 const VMRangeToPermissions::Entry *permission_entry =
714 m_core_range_infos.FindEntryThatContainsOrFollows(load_addr);
715 if (permission_entry) {
716 if (permission_entry->Contains(load_addr)) {
717 region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase());
718 region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd());
719 const Flags permissions(permission_entry->data);
720 region_info.SetReadable(permissions.Test(ePermissionsReadable)
721 ? MemoryRegionInfo::eYes
722 : MemoryRegionInfo::eNo);
723 region_info.SetWritable(permissions.Test(ePermissionsWritable)
724 ? MemoryRegionInfo::eYes
725 : MemoryRegionInfo::eNo);
726 region_info.SetExecutable(permissions.Test(ePermissionsExecutable)
727 ? MemoryRegionInfo::eYes
728 : MemoryRegionInfo::eNo);
729 region_info.SetMapped(MemoryRegionInfo::eYes);
730 } else if (load_addr < permission_entry->GetRangeBase()) {
731 region_info.GetRange().SetRangeBase(load_addr);
732 region_info.GetRange().SetRangeEnd(permission_entry->GetRangeBase());
733 region_info.SetReadable(MemoryRegionInfo::eNo);
734 region_info.SetWritable(MemoryRegionInfo::eNo);
735 region_info.SetExecutable(MemoryRegionInfo::eNo);
736 region_info.SetMapped(MemoryRegionInfo::eNo);
738 return Status();
741 region_info.GetRange().SetRangeBase(load_addr);
742 region_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
743 region_info.SetReadable(MemoryRegionInfo::eNo);
744 region_info.SetWritable(MemoryRegionInfo::eNo);
745 region_info.SetExecutable(MemoryRegionInfo::eNo);
746 region_info.SetMapped(MemoryRegionInfo::eNo);
747 return Status();
750 void ProcessMachCore::Clear() { m_thread_list.Clear(); }
752 void ProcessMachCore::Initialize() {
753 static llvm::once_flag g_once_flag;
755 llvm::call_once(g_once_flag, []() {
756 PluginManager::RegisterPlugin(GetPluginNameStatic(),
757 GetPluginDescriptionStatic(), CreateInstance);
761 addr_t ProcessMachCore::GetImageInfoAddress() {
762 // If we found both a user-process dyld and a kernel binary, we need to
763 // decide which to prefer.
764 if (GetCorefilePreference() == eKernelCorefile) {
765 if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS) {
766 return m_mach_kernel_addr;
768 return m_dyld_addr;
769 } else {
770 if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
771 return m_dyld_addr;
773 return m_mach_kernel_addr;
777 lldb_private::ObjectFile *ProcessMachCore::GetCoreObjectFile() {
778 return m_core_module_sp->GetObjectFile();