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