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