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