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