1 //===-- DynamicLoaderDarwinKernel.cpp -----------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "lldb/Breakpoint/StoppointCallbackContext.h" 11 #include "lldb/Core/DataBuffer.h" 12 #include "lldb/Core/DataBufferHeap.h" 13 #include "lldb/Core/Debugger.h" 14 #include "lldb/Core/Log.h" 15 #include "lldb/Core/Module.h" 16 #include "lldb/Core/PluginManager.h" 17 #include "lldb/Core/State.h" 18 #include "lldb/Symbol/ObjectFile.h" 19 #include "lldb/Target/ObjCLanguageRuntime.h" 20 #include "lldb/Target/RegisterContext.h" 21 #include "lldb/Target/Target.h" 22 #include "lldb/Target/Thread.h" 23 #include "lldb/Target/ThreadPlanRunToAddress.h" 24 #include "lldb/Target/StackFrame.h" 25 26 #include "DynamicLoaderDarwinKernel.h" 27 28 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN 29 #ifdef ENABLE_DEBUG_PRINTF 30 #include <stdio.h> 31 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__) 32 #else 33 #define DEBUG_PRINTF(fmt, ...) 34 #endif 35 36 using namespace lldb; 37 using namespace lldb_private; 38 39 /// FIXME - The ObjC Runtime trampoline handler doesn't really belong here. 40 /// I am putting it here so I can invoke it in the Trampoline code here, but 41 /// it should be moved to the ObjC Runtime support when it is set up. 42 43 44 //---------------------------------------------------------------------- 45 // Create an instance of this class. This function is filled into 46 // the plugin info class that gets handed out by the plugin factory and 47 // allows the lldb to instantiate an instance of this class. 48 //---------------------------------------------------------------------- 49 DynamicLoader * 50 DynamicLoaderDarwinKernel::CreateInstance (Process* process, bool force) 51 { 52 bool create = force; 53 if (!create) 54 { 55 Module* exe_module = process->GetTarget().GetExecutableModulePointer(); 56 if (exe_module) 57 { 58 ObjectFile *object_file = exe_module->GetObjectFile(); 59 if (object_file) 60 { 61 create = (object_file->GetStrata() == ObjectFile::eStrataKernel); 62 } 63 } 64 65 if (create) 66 { 67 const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple(); 68 create = triple_ref.getOS() == llvm::Triple::Darwin && triple_ref.getVendor() == llvm::Triple::Apple; 69 } 70 } 71 72 if (create) 73 { 74 process->SetCanJIT(false); 75 return new DynamicLoaderDarwinKernel (process); 76 } 77 return NULL; 78 } 79 80 //---------------------------------------------------------------------- 81 // Constructor 82 //---------------------------------------------------------------------- 83 DynamicLoaderDarwinKernel::DynamicLoaderDarwinKernel (Process* process) : 84 DynamicLoader(process), 85 m_kernel(), 86 m_kext_summary_header_ptr_addr (), 87 m_kext_summary_header_addr (), 88 m_kext_summary_header (), 89 m_kext_summaries(), 90 m_mutex(Mutex::eMutexTypeRecursive), 91 m_break_id (LLDB_INVALID_BREAK_ID) 92 { 93 } 94 95 //---------------------------------------------------------------------- 96 // Destructor 97 //---------------------------------------------------------------------- 98 DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel() 99 { 100 Clear(true); 101 } 102 103 void 104 DynamicLoaderDarwinKernel::UpdateIfNeeded() 105 { 106 LoadKernelModuleIfNeeded(); 107 SetNotificationBreakpointIfNeeded (); 108 } 109 //------------------------------------------------------------------ 110 /// Called after attaching a process. 111 /// 112 /// Allow DynamicLoader plug-ins to execute some code after 113 /// attaching to a process. 114 //------------------------------------------------------------------ 115 void 116 DynamicLoaderDarwinKernel::DidAttach () 117 { 118 PrivateInitialize(m_process); 119 UpdateIfNeeded(); 120 } 121 122 //------------------------------------------------------------------ 123 /// Called after attaching a process. 124 /// 125 /// Allow DynamicLoader plug-ins to execute some code after 126 /// attaching to a process. 127 //------------------------------------------------------------------ 128 void 129 DynamicLoaderDarwinKernel::DidLaunch () 130 { 131 PrivateInitialize(m_process); 132 UpdateIfNeeded(); 133 } 134 135 136 //---------------------------------------------------------------------- 137 // Clear out the state of this class. 138 //---------------------------------------------------------------------- 139 void 140 DynamicLoaderDarwinKernel::Clear (bool clear_process) 141 { 142 Mutex::Locker locker(m_mutex); 143 144 if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id)) 145 m_process->ClearBreakpointSiteByID(m_break_id); 146 147 if (clear_process) 148 m_process = NULL; 149 m_kernel.Clear(false); 150 m_kext_summary_header_ptr_addr.Clear(); 151 m_kext_summary_header_addr.Clear(); 152 m_kext_summaries.clear(); 153 m_break_id = LLDB_INVALID_BREAK_ID; 154 } 155 156 157 //---------------------------------------------------------------------- 158 // Load the kernel module and initialize the "m_kernel" member. Return 159 // true _only_ if the kernel is loaded the first time through (subsequent 160 // calls to this function should return false after the kernel has been 161 // already loaded). 162 //---------------------------------------------------------------------- 163 void 164 DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded() 165 { 166 if (!m_kext_summary_header_ptr_addr.IsValid()) 167 { 168 m_kernel.Clear(false); 169 m_kernel.module_sp = m_process->GetTarget().GetExecutableModule(); 170 if (m_kernel.module_sp) 171 { 172 static ConstString mach_header_name ("_mh_execute_header"); 173 static ConstString kext_summary_symbol ("gLoadedKextSummaries"); 174 const Symbol *symbol = NULL; 175 symbol = m_kernel.module_sp->FindFirstSymbolWithNameAndType (kext_summary_symbol, eSymbolTypeData); 176 if (symbol) 177 m_kext_summary_header_ptr_addr = symbol->GetValue(); 178 179 symbol = m_kernel.module_sp->FindFirstSymbolWithNameAndType (mach_header_name, eSymbolTypeAbsolute); 180 if (symbol) 181 { 182 // The "_mh_execute_header" symbol is absolute and not a section based 183 // symbol that will have a valid address, so we need to resolve it... 184 m_process->GetTarget().GetImages().ResolveFileAddress (symbol->GetValue().GetFileAddress(), m_kernel.so_address); 185 DataExtractor data; // Load command data 186 if (ReadMachHeader (m_kernel, &data)) 187 { 188 if (m_kernel.header.filetype == llvm::MachO::HeaderFileTypeExecutable) 189 { 190 if (ParseLoadCommands (data, m_kernel)) 191 UpdateImageLoadAddress (m_kernel); 192 193 // Update all image infos 194 ReadAllKextSummaries (); 195 } 196 } 197 else 198 { 199 m_kernel.Clear(false); 200 } 201 } 202 } 203 } 204 } 205 206 bool 207 DynamicLoaderDarwinKernel::FindTargetModule (OSKextLoadedKextSummary &image_info, bool can_create, bool *did_create_ptr) 208 { 209 if (did_create_ptr) 210 *did_create_ptr = false; 211 212 const bool image_info_uuid_is_valid = image_info.uuid.IsValid(); 213 214 if (image_info.module_sp) 215 { 216 if (image_info_uuid_is_valid) 217 { 218 if (image_info.module_sp->GetUUID() == image_info.uuid) 219 return true; 220 else 221 image_info.module_sp.reset(); 222 } 223 else 224 return true; 225 } 226 227 ModuleList &target_images = m_process->GetTarget().GetImages(); 228 if (image_info_uuid_is_valid) 229 image_info.module_sp = target_images.FindModule(image_info.uuid); 230 231 if (image_info.module_sp) 232 return true; 233 234 ArchSpec arch (image_info.GetArchitecture ()); 235 if (can_create) 236 { 237 if (image_info_uuid_is_valid) 238 { 239 image_info.module_sp = m_process->GetTarget().GetSharedModule (FileSpec(), 240 arch, 241 &image_info.uuid); 242 if (did_create_ptr) 243 *did_create_ptr = image_info.module_sp; 244 } 245 } 246 return image_info.module_sp; 247 } 248 249 bool 250 DynamicLoaderDarwinKernel::UpdateCommPageLoadAddress(Module *module) 251 { 252 bool changed = false; 253 if (module) 254 { 255 ObjectFile *image_object_file = module->GetObjectFile(); 256 if (image_object_file) 257 { 258 SectionList *section_list = image_object_file->GetSectionList (); 259 if (section_list) 260 { 261 uint32_t num_sections = section_list->GetSize(); 262 for (uint32_t i=0; i<num_sections; ++i) 263 { 264 Section* section = section_list->GetSectionAtIndex (i).get(); 265 if (section) 266 { 267 const addr_t new_section_load_addr = section->GetFileAddress (); 268 const addr_t old_section_load_addr = m_process->GetTarget().GetSectionLoadList().GetSectionLoadAddress (section); 269 if (old_section_load_addr == LLDB_INVALID_ADDRESS || 270 old_section_load_addr != new_section_load_addr) 271 { 272 if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section, section->GetFileAddress ())) 273 changed = true; 274 } 275 } 276 } 277 } 278 } 279 } 280 return changed; 281 } 282 283 //---------------------------------------------------------------------- 284 // Update the load addresses for all segments in MODULE using the 285 // updated INFO that is passed in. 286 //---------------------------------------------------------------------- 287 bool 288 DynamicLoaderDarwinKernel::UpdateImageLoadAddress (OSKextLoadedKextSummary& info) 289 { 290 Module *module = info.module_sp.get(); 291 bool changed = false; 292 if (module) 293 { 294 ObjectFile *image_object_file = module->GetObjectFile(); 295 if (image_object_file) 296 { 297 SectionList *section_list = image_object_file->GetSectionList (); 298 if (section_list) 299 { 300 // We now know the slide amount, so go through all sections 301 // and update the load addresses with the correct values. 302 uint32_t num_segments = info.segments.size(); 303 for (uint32_t i=0; i<num_segments; ++i) 304 { 305 const addr_t new_section_load_addr = info.segments[i].vmaddr; 306 if (section_list->FindSectionByName(info.segments[i].name)) 307 { 308 SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name)); 309 if (section_sp) 310 { 311 const addr_t old_section_load_addr = m_process->GetTarget().GetSectionLoadList().GetSectionLoadAddress (section_sp.get()); 312 if (old_section_load_addr == LLDB_INVALID_ADDRESS || 313 old_section_load_addr != new_section_load_addr) 314 { 315 if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section_sp.get(), new_section_load_addr)) 316 changed = true; 317 } 318 } 319 else 320 { 321 Host::SystemLog (Host::eSystemLogWarning, "warning: unable to find and load segment named '%s' at 0x%llx in '%s/%s' in macosx dynamic loader plug-in.\n", 322 info.segments[i].name.AsCString("<invalid>"), 323 (uint64_t)new_section_load_addr, 324 image_object_file->GetFileSpec().GetDirectory().AsCString(), 325 image_object_file->GetFileSpec().GetFilename().AsCString()); 326 } 327 } 328 else 329 { 330 // The segment name is empty which means this is a .o file. 331 // Object files in LLDB end up getting reorganized so that 332 // the segment name that is in the section is promoted into 333 // an actual segment, so we just need to go through all sections 334 // and slide them by a single amount. 335 336 uint32_t num_sections = section_list->GetSize(); 337 for (uint32_t i=0; i<num_sections; ++i) 338 { 339 Section* section = section_list->GetSectionAtIndex (i).get(); 340 if (section) 341 { 342 if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section, section->GetFileAddress() + new_section_load_addr)) 343 changed = true; 344 } 345 } 346 } 347 } 348 } 349 } 350 } 351 return changed; 352 } 353 354 //---------------------------------------------------------------------- 355 // Update the load addresses for all segments in MODULE using the 356 // updated INFO that is passed in. 357 //---------------------------------------------------------------------- 358 bool 359 DynamicLoaderDarwinKernel::UnloadImageLoadAddress (OSKextLoadedKextSummary& info) 360 { 361 Module *module = info.module_sp.get(); 362 bool changed = false; 363 if (module) 364 { 365 ObjectFile *image_object_file = module->GetObjectFile(); 366 if (image_object_file) 367 { 368 SectionList *section_list = image_object_file->GetSectionList (); 369 if (section_list) 370 { 371 uint32_t num_segments = info.segments.size(); 372 for (uint32_t i=0; i<num_segments; ++i) 373 { 374 SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name)); 375 if (section_sp) 376 { 377 const addr_t old_section_load_addr = info.segments[i].vmaddr; 378 if (m_process->GetTarget().GetSectionLoadList().SetSectionUnloaded (section_sp.get(), old_section_load_addr)) 379 changed = true; 380 } 381 else 382 { 383 Host::SystemLog (Host::eSystemLogWarning, 384 "warning: unable to find and unload segment named '%s' in '%s/%s' in macosx dynamic loader plug-in.\n", 385 info.segments[i].name.AsCString("<invalid>"), 386 image_object_file->GetFileSpec().GetDirectory().AsCString(), 387 image_object_file->GetFileSpec().GetFilename().AsCString()); 388 } 389 } 390 } 391 } 392 } 393 return changed; 394 } 395 396 397 //---------------------------------------------------------------------- 398 // Static callback function that gets called when our DYLD notification 399 // breakpoint gets hit. We update all of our image infos and then 400 // let our super class DynamicLoader class decide if we should stop 401 // or not (based on global preference). 402 //---------------------------------------------------------------------- 403 bool 404 DynamicLoaderDarwinKernel::BreakpointHitCallback (void *baton, 405 StoppointCallbackContext *context, 406 user_id_t break_id, 407 user_id_t break_loc_id) 408 { 409 return static_cast<DynamicLoaderDarwinKernel*>(baton)->BreakpointHit (context, break_id, break_loc_id); 410 } 411 412 bool 413 DynamicLoaderDarwinKernel::BreakpointHit (StoppointCallbackContext *context, 414 user_id_t break_id, 415 user_id_t break_loc_id) 416 { 417 LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER)); 418 if (log) 419 log->Printf ("DynamicLoaderDarwinKernel::BreakpointHit (...)\n"); 420 421 ReadAllKextSummaries (); 422 423 if (log) 424 PutToLog(log.get()); 425 426 return GetStopWhenImagesChange(); 427 } 428 429 430 bool 431 DynamicLoaderDarwinKernel::ReadKextSummaryHeader () 432 { 433 Mutex::Locker locker(m_mutex); 434 435 // the all image infos is already valid for this process stop ID 436 437 m_kext_summaries.clear(); 438 if (m_kext_summary_header_ptr_addr.IsValid()) 439 { 440 const uint32_t addr_size = m_kernel.GetAddressByteSize (); 441 const ByteOrder byte_order = m_kernel.GetByteOrder(); 442 Error error; 443 // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure 444 // which is currenty 4 uint32_t and a pointer. 445 uint8_t buf[24]; 446 DataExtractor data (buf, sizeof(buf), byte_order, addr_size); 447 const size_t count = 4 * sizeof(uint32_t) + addr_size; 448 const bool prefer_file_cache = false; 449 if (m_process->GetTarget().ReadPointerFromMemory (m_kext_summary_header_ptr_addr, 450 prefer_file_cache, 451 error, 452 m_kext_summary_header_addr)) 453 { 454 // We got a valid address for our kext summary header and make sure it isn't NULL 455 if (m_kext_summary_header_addr.IsValid() && 456 m_kext_summary_header_addr.GetFileAddress() != 0) 457 { 458 const size_t bytes_read = m_process->GetTarget().ReadMemory (m_kext_summary_header_addr, prefer_file_cache, buf, count, error); 459 if (bytes_read == count) 460 { 461 uint32_t offset = 0; 462 m_kext_summary_header.version = data.GetU32(&offset); 463 if (m_kext_summary_header.version >= 2) 464 { 465 m_kext_summary_header.entry_size = data.GetU32(&offset); 466 } 467 else 468 { 469 // Versions less than 2 didn't have an entry size, it was hard coded 470 m_kext_summary_header.entry_size = KERNEL_MODULE_ENTRY_SIZE_VERSION_1; 471 } 472 m_kext_summary_header.entry_count = data.GetU32(&offset); 473 return true; 474 } 475 } 476 } 477 } 478 m_kext_summary_header_addr.Clear(); 479 return false; 480 } 481 482 483 bool 484 DynamicLoaderDarwinKernel::ParseKextSummaries (const Address &kext_summary_addr, 485 uint32_t count) 486 { 487 OSKextLoadedKextSummary::collection kext_summaries; 488 LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER)); 489 if (log) 490 log->Printf ("Adding %d modules.\n", count); 491 492 Mutex::Locker locker(m_mutex); 493 494 if (!ReadKextSummaries (kext_summary_addr, count, kext_summaries)) 495 return false; 496 497 Stream *s = &m_process->GetTarget().GetDebugger().GetOutputStream(); 498 for (uint32_t i = 0; i < count; i++) 499 { 500 if (s) 501 { 502 const uint8_t *u = (const uint8_t *)kext_summaries[i].uuid.GetBytes(); 503 if (u) 504 { 505 s->Printf("Loading kext: %2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X 0x%16.16llx \"%s\"...", 506 u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7], 507 u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15], 508 kext_summaries[i].address, kext_summaries[i].name); 509 } 510 else 511 { 512 s->Printf("0x%16.16llx \"%s\"...", kext_summaries[i].address, kext_summaries[i].name); 513 } 514 } 515 516 DataExtractor data; // Load command data 517 if (ReadMachHeader (kext_summaries[i], &data)) 518 { 519 ParseLoadCommands (data, kext_summaries[i]); 520 } 521 522 if (s) 523 { 524 if (kext_summaries[i].module_sp) 525 s->Printf("\n found kext: %s/%s\n", 526 kext_summaries[i].module_sp->GetFileSpec().GetDirectory().AsCString(), 527 kext_summaries[i].module_sp->GetFileSpec().GetFilename().AsCString()); 528 else 529 s->Printf (" failed to locate/load.\n"); 530 } 531 532 if (log) 533 kext_summaries[i].PutToLog (log.get()); 534 } 535 bool return_value = AddModulesUsingImageInfos (kext_summaries); 536 return return_value; 537 } 538 539 // Adds the modules in image_infos to m_kext_summaries. 540 // NB don't call this passing in m_kext_summaries. 541 542 bool 543 DynamicLoaderDarwinKernel::AddModulesUsingImageInfos (OSKextLoadedKextSummary::collection &image_infos) 544 { 545 // Now add these images to the main list. 546 ModuleList loaded_module_list; 547 548 for (uint32_t idx = 0; idx < image_infos.size(); ++idx) 549 { 550 m_kext_summaries.push_back(image_infos[idx]); 551 552 if (FindTargetModule (image_infos[idx], true, NULL)) 553 { 554 // UpdateImageLoadAddress will return true if any segments 555 // change load address. We need to check this so we don't 556 // mention that all loaded shared libraries are newly loaded 557 // each time we hit out dyld breakpoint since dyld will list all 558 // shared libraries each time. 559 if (UpdateImageLoadAddress (image_infos[idx])) 560 { 561 loaded_module_list.AppendIfNeeded (image_infos[idx].module_sp); 562 } 563 } 564 } 565 566 if (loaded_module_list.GetSize() > 0) 567 { 568 // FIXME: This should really be in the Runtime handlers class, which should get 569 // called by the target's ModulesDidLoad, but we're doing it all locally for now 570 // to save time. 571 // Also, I'm assuming there can be only one libobjc dylib loaded... 572 573 ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime(); 574 if (objc_runtime != NULL && !objc_runtime->HasReadObjCLibrary()) 575 { 576 size_t num_modules = loaded_module_list.GetSize(); 577 for (int i = 0; i < num_modules; i++) 578 { 579 if (objc_runtime->IsModuleObjCLibrary (loaded_module_list.GetModuleAtIndex (i))) 580 { 581 objc_runtime->ReadObjCLibrary (loaded_module_list.GetModuleAtIndex (i)); 582 break; 583 } 584 } 585 } 586 // if (log) 587 // loaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderDarwinKernel::ModulesDidLoad"); 588 m_process->GetTarget().ModulesDidLoad (loaded_module_list); 589 } 590 return true; 591 } 592 593 594 uint32_t 595 DynamicLoaderDarwinKernel::ReadKextSummaries (const Address &kext_summary_addr, 596 uint32_t image_infos_count, 597 OSKextLoadedKextSummary::collection &image_infos) 598 { 599 const ByteOrder endian = m_kernel.GetByteOrder(); 600 const uint32_t addr_size = m_kernel.GetAddressByteSize(); 601 602 image_infos.resize(image_infos_count); 603 const size_t count = image_infos.size() * m_kext_summary_header.entry_size; 604 DataBufferHeap data(count, 0); 605 Error error; 606 607 Stream *s = &m_process->GetTarget().GetDebugger().GetOutputStream(); 608 609 if (s) 610 s->Printf ("Reading %u kext summaries...\n", image_infos_count); 611 const bool prefer_file_cache = false; 612 const size_t bytes_read = m_process->GetTarget().ReadMemory (kext_summary_addr, 613 prefer_file_cache, 614 data.GetBytes(), 615 data.GetByteSize(), 616 error); 617 if (bytes_read == count) 618 { 619 620 DataExtractor extractor (data.GetBytes(), data.GetByteSize(), endian, addr_size); 621 uint32_t i=0; 622 for (uint32_t kext_summary_offset = 0; 623 i < image_infos.size() && extractor.ValidOffsetForDataOfSize(kext_summary_offset, m_kext_summary_header.entry_size); 624 ++i, kext_summary_offset += m_kext_summary_header.entry_size) 625 { 626 uint32_t offset = kext_summary_offset; 627 const void *name_data = extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME); 628 if (name_data == NULL) 629 break; 630 memcpy (image_infos[i].name, name_data, KERNEL_MODULE_MAX_NAME); 631 image_infos[i].uuid.SetBytes(extractor.GetData (&offset, 16)); 632 image_infos[i].address = extractor.GetU64(&offset); 633 if (!image_infos[i].so_address.SetLoadAddress (image_infos[i].address, &m_process->GetTarget())) 634 m_process->GetTarget().GetImages().ResolveFileAddress (image_infos[i].address, image_infos[i].so_address); 635 image_infos[i].size = extractor.GetU64(&offset); 636 image_infos[i].version = extractor.GetU64(&offset); 637 image_infos[i].load_tag = extractor.GetU32(&offset); 638 image_infos[i].flags = extractor.GetU32(&offset); 639 if ((offset - kext_summary_offset) < m_kext_summary_header.entry_size) 640 { 641 image_infos[i].reference_list = extractor.GetU64(&offset); 642 } 643 else 644 { 645 image_infos[i].reference_list = 0; 646 } 647 } 648 if (i < image_infos.size()) 649 image_infos.resize(i); 650 } 651 else 652 { 653 image_infos.clear(); 654 } 655 return image_infos.size(); 656 } 657 658 bool 659 DynamicLoaderDarwinKernel::ReadAllKextSummaries () 660 { 661 LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER)); 662 663 Mutex::Locker locker(m_mutex); 664 665 if (ReadKextSummaryHeader ()) 666 { 667 if (m_kext_summary_header.entry_count > 0 && m_kext_summary_header_addr.IsValid()) 668 { 669 Address summary_addr (m_kext_summary_header_addr); 670 summary_addr.Slide(m_kext_summary_header.GetSize()); 671 if (!ParseKextSummaries (summary_addr, m_kext_summary_header.entry_count)) 672 { 673 m_kext_summaries.clear(); 674 } 675 return true; 676 } 677 } 678 return false; 679 } 680 681 //---------------------------------------------------------------------- 682 // Read a mach_header at ADDR into HEADER, and also fill in the load 683 // command data into LOAD_COMMAND_DATA if it is non-NULL. 684 // 685 // Returns true if we succeed, false if we fail for any reason. 686 //---------------------------------------------------------------------- 687 bool 688 DynamicLoaderDarwinKernel::ReadMachHeader (OSKextLoadedKextSummary& kext_summary, DataExtractor *load_command_data) 689 { 690 DataBufferHeap header_bytes(sizeof(llvm::MachO::mach_header), 0); 691 Error error; 692 const bool prefer_file_cache = false; 693 size_t bytes_read = m_process->GetTarget().ReadMemory (kext_summary.so_address, 694 prefer_file_cache, 695 header_bytes.GetBytes(), 696 header_bytes.GetByteSize(), 697 error); 698 if (bytes_read == sizeof(llvm::MachO::mach_header)) 699 { 700 uint32_t offset = 0; 701 ::memset (&kext_summary.header, 0, sizeof(kext_summary.header)); 702 703 // Get the magic byte unswapped so we can figure out what we are dealing with 704 DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(), endian::InlHostByteOrder(), 4); 705 kext_summary.header.magic = data.GetU32(&offset); 706 Address load_cmd_addr = kext_summary.so_address; 707 data.SetByteOrder(DynamicLoaderDarwinKernel::GetByteOrderFromMagic(kext_summary.header.magic)); 708 switch (kext_summary.header.magic) 709 { 710 case llvm::MachO::HeaderMagic32: 711 case llvm::MachO::HeaderMagic32Swapped: 712 data.SetAddressByteSize(4); 713 load_cmd_addr.Slide (sizeof(llvm::MachO::mach_header)); 714 break; 715 716 case llvm::MachO::HeaderMagic64: 717 case llvm::MachO::HeaderMagic64Swapped: 718 data.SetAddressByteSize(8); 719 load_cmd_addr.Slide (sizeof(llvm::MachO::mach_header_64)); 720 break; 721 722 default: 723 return false; 724 } 725 726 // Read the rest of dyld's mach header 727 if (data.GetU32(&offset, &kext_summary.header.cputype, (sizeof(llvm::MachO::mach_header)/sizeof(uint32_t)) - 1)) 728 { 729 if (load_command_data == NULL) 730 return true; // We were able to read the mach_header and weren't asked to read the load command bytes 731 732 DataBufferSP load_cmd_data_sp(new DataBufferHeap(kext_summary.header.sizeofcmds, 0)); 733 734 size_t load_cmd_bytes_read = m_process->GetTarget().ReadMemory (load_cmd_addr, 735 prefer_file_cache, 736 load_cmd_data_sp->GetBytes(), 737 load_cmd_data_sp->GetByteSize(), 738 error); 739 740 if (load_cmd_bytes_read == kext_summary.header.sizeofcmds) 741 { 742 // Set the load command data and also set the correct endian 743 // swap settings and the correct address size 744 load_command_data->SetData(load_cmd_data_sp, 0, kext_summary.header.sizeofcmds); 745 load_command_data->SetByteOrder(data.GetByteOrder()); 746 load_command_data->SetAddressByteSize(data.GetAddressByteSize()); 747 return true; // We successfully read the mach_header and the load command data 748 } 749 750 return false; // We weren't able to read the load command data 751 } 752 } 753 return false; // We failed the read the mach_header 754 } 755 756 757 //---------------------------------------------------------------------- 758 // Parse the load commands for an image 759 //---------------------------------------------------------------------- 760 uint32_t 761 DynamicLoaderDarwinKernel::ParseLoadCommands (const DataExtractor& data, OSKextLoadedKextSummary& image_info) 762 { 763 uint32_t offset = 0; 764 uint32_t cmd_idx; 765 Segment segment; 766 image_info.Clear (true); 767 768 for (cmd_idx = 0; cmd_idx < image_info.header.ncmds; cmd_idx++) 769 { 770 // Clear out any load command specific data from image_info since 771 // we are about to read it. 772 773 if (data.ValidOffsetForDataOfSize (offset, sizeof(llvm::MachO::load_command))) 774 { 775 llvm::MachO::load_command load_cmd; 776 uint32_t load_cmd_offset = offset; 777 load_cmd.cmd = data.GetU32 (&offset); 778 load_cmd.cmdsize = data.GetU32 (&offset); 779 switch (load_cmd.cmd) 780 { 781 case llvm::MachO::LoadCommandSegment32: 782 { 783 segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16); 784 // We are putting 4 uint32_t values 4 uint64_t values so 785 // we have to use multiple 32 bit gets below. 786 segment.vmaddr = data.GetU32 (&offset); 787 segment.vmsize = data.GetU32 (&offset); 788 segment.fileoff = data.GetU32 (&offset); 789 segment.filesize = data.GetU32 (&offset); 790 // Extract maxprot, initprot, nsects and flags all at once 791 data.GetU32(&offset, &segment.maxprot, 4); 792 image_info.segments.push_back (segment); 793 } 794 break; 795 796 case llvm::MachO::LoadCommandSegment64: 797 { 798 segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16); 799 // Extract vmaddr, vmsize, fileoff, and filesize all at once 800 data.GetU64(&offset, &segment.vmaddr, 4); 801 // Extract maxprot, initprot, nsects and flags all at once 802 data.GetU32(&offset, &segment.maxprot, 4); 803 image_info.segments.push_back (segment); 804 } 805 break; 806 807 case llvm::MachO::LoadCommandUUID: 808 image_info.uuid.SetBytes(data.GetData (&offset, 16)); 809 break; 810 811 default: 812 break; 813 } 814 // Set offset to be the beginning of the next load command. 815 offset = load_cmd_offset + load_cmd.cmdsize; 816 } 817 } 818 #if 0 819 // No slide in the kernel... 820 821 // All sections listed in the dyld image info structure will all 822 // either be fixed up already, or they will all be off by a single 823 // slide amount that is determined by finding the first segment 824 // that is at file offset zero which also has bytes (a file size 825 // that is greater than zero) in the object file. 826 827 // Determine the slide amount (if any) 828 const size_t num_sections = image_info.segments.size(); 829 for (size_t i = 0; i < num_sections; ++i) 830 { 831 // Iterate through the object file sections to find the 832 // first section that starts of file offset zero and that 833 // has bytes in the file... 834 if (image_info.segments[i].fileoff == 0 && image_info.segments[i].filesize > 0) 835 { 836 image_info.slide = image_info.address - image_info.segments[i].vmaddr; 837 // We have found the slide amount, so we can exit 838 // this for loop. 839 break; 840 } 841 } 842 #endif 843 if (image_info.uuid.IsValid()) 844 { 845 bool did_create = false; 846 if (FindTargetModule(image_info, true, &did_create)) 847 { 848 if (did_create) 849 image_info.module_create_stop_id = m_process->GetStopID(); 850 } 851 } 852 return cmd_idx; 853 } 854 855 //---------------------------------------------------------------------- 856 // Dump a Segment to the file handle provided. 857 //---------------------------------------------------------------------- 858 void 859 DynamicLoaderDarwinKernel::Segment::PutToLog (Log *log, addr_t slide) const 860 { 861 if (log) 862 { 863 if (slide == 0) 864 log->Printf ("\t\t%16s [0x%16.16llx - 0x%16.16llx)", 865 name.AsCString(""), 866 vmaddr + slide, 867 vmaddr + slide + vmsize); 868 else 869 log->Printf ("\t\t%16s [0x%16.16llx - 0x%16.16llx) slide = 0x%llx", 870 name.AsCString(""), 871 vmaddr + slide, 872 vmaddr + slide + vmsize, 873 slide); 874 } 875 } 876 877 const DynamicLoaderDarwinKernel::Segment * 878 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::FindSegment (const ConstString &name) const 879 { 880 const size_t num_segments = segments.size(); 881 for (size_t i=0; i<num_segments; ++i) 882 { 883 if (segments[i].name == name) 884 return &segments[i]; 885 } 886 return NULL; 887 } 888 889 890 //---------------------------------------------------------------------- 891 // Dump an image info structure to the file handle provided. 892 //---------------------------------------------------------------------- 893 void 894 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::PutToLog (Log *log) const 895 { 896 if (log == NULL) 897 return; 898 const uint8_t *u = (uint8_t *)uuid.GetBytes(); 899 900 if (address == LLDB_INVALID_ADDRESS) 901 { 902 if (u) 903 { 904 log->Printf("\tuuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X name=\"%s\" (UNLOADED)", 905 u[ 0], u[ 1], u[ 2], u[ 3], 906 u[ 4], u[ 5], u[ 6], u[ 7], 907 u[ 8], u[ 9], u[10], u[11], 908 u[12], u[13], u[14], u[15], 909 name); 910 } 911 else 912 log->Printf("\tname=\"%s\" (UNLOADED)", name); 913 } 914 else 915 { 916 if (u) 917 { 918 log->Printf("\taddr=0x%16.16llx size=0x%16.16llx version=0x%16.16llx load-tag=0x%8.8x flags=0x%8.8x ref-list=0x%16.16llx uuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X name=\"%s\"", 919 address, size, version, load_tag, flags, reference_list, 920 u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7], 921 u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15], 922 name); 923 } 924 else 925 { 926 log->Printf("\t[0x%16.16llx - 0x%16.16llx) version=0x%16.16llx load-tag=0x%8.8x flags=0x%8.8x ref-list=0x%16.16llx name=\"%s\"", 927 address, address+size, version, load_tag, flags, reference_list, 928 name); 929 } 930 for (uint32_t i=0; i<segments.size(); ++i) 931 segments[i].PutToLog(log, 0); 932 } 933 } 934 935 //---------------------------------------------------------------------- 936 // Dump the _dyld_all_image_infos members and all current image infos 937 // that we have parsed to the file handle provided. 938 //---------------------------------------------------------------------- 939 void 940 DynamicLoaderDarwinKernel::PutToLog(Log *log) const 941 { 942 if (log == NULL) 943 return; 944 945 Mutex::Locker locker(m_mutex); 946 log->Printf("gLoadedKextSummaries = 0x%16.16llx { version=%u, entry_size=%u, entry_count=%u }", 947 m_kext_summary_header_addr.GetFileAddress(), 948 m_kext_summary_header.version, 949 m_kext_summary_header.entry_size, 950 m_kext_summary_header.entry_count); 951 952 size_t i; 953 const size_t count = m_kext_summaries.size(); 954 if (count > 0) 955 { 956 log->PutCString("Loaded:"); 957 for (i = 0; i<count; i++) 958 m_kext_summaries[i].PutToLog(log); 959 } 960 } 961 962 void 963 DynamicLoaderDarwinKernel::PrivateInitialize(Process *process) 964 { 965 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState())); 966 Clear(true); 967 m_process = process; 968 m_process->GetTarget().GetSectionLoadList().Clear(); 969 } 970 971 void 972 DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded () 973 { 974 if (m_break_id == LLDB_INVALID_BREAK_ID) 975 { 976 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState())); 977 978 979 const bool internal_bp = false; 980 const LazyBool skip_prologue = eLazyBoolNo; 981 FileSpecList module_spec_list; 982 module_spec_list.Append (m_kernel.module_sp->GetFileSpec()); 983 Breakpoint *bp = m_process->GetTarget().CreateBreakpoint (&module_spec_list, 984 NULL, 985 "OSKextLoadedKextSummariesUpdated", 986 eFunctionNameTypeFull, 987 internal_bp, 988 skip_prologue).get(); 989 990 bp->SetCallback (DynamicLoaderDarwinKernel::BreakpointHitCallback, this, true); 991 m_break_id = bp->GetID(); 992 } 993 } 994 995 //---------------------------------------------------------------------- 996 // Member function that gets called when the process state changes. 997 //---------------------------------------------------------------------- 998 void 999 DynamicLoaderDarwinKernel::PrivateProcessStateChanged (Process *process, StateType state) 1000 { 1001 DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__, StateAsCString(state)); 1002 switch (state) 1003 { 1004 case eStateConnected: 1005 case eStateAttaching: 1006 case eStateLaunching: 1007 case eStateInvalid: 1008 case eStateUnloaded: 1009 case eStateExited: 1010 case eStateDetached: 1011 Clear(false); 1012 break; 1013 1014 case eStateStopped: 1015 UpdateIfNeeded(); 1016 break; 1017 1018 case eStateRunning: 1019 case eStateStepping: 1020 case eStateCrashed: 1021 case eStateSuspended: 1022 break; 1023 1024 default: 1025 break; 1026 } 1027 } 1028 1029 ThreadPlanSP 1030 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others) 1031 { 1032 ThreadPlanSP thread_plan_sp; 1033 LogSP log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 1034 if (log) 1035 log->Printf ("Could not find symbol for step through."); 1036 return thread_plan_sp; 1037 } 1038 1039 Error 1040 DynamicLoaderDarwinKernel::CanLoadImage () 1041 { 1042 Error error; 1043 error.SetErrorString("always unsafe to load or unload shared libraries in the darwin kernel"); 1044 return error; 1045 } 1046 1047 void 1048 DynamicLoaderDarwinKernel::Initialize() 1049 { 1050 PluginManager::RegisterPlugin (GetPluginNameStatic(), 1051 GetPluginDescriptionStatic(), 1052 CreateInstance); 1053 } 1054 1055 void 1056 DynamicLoaderDarwinKernel::Terminate() 1057 { 1058 PluginManager::UnregisterPlugin (CreateInstance); 1059 } 1060 1061 1062 const char * 1063 DynamicLoaderDarwinKernel::GetPluginNameStatic() 1064 { 1065 return "dynamic-loader.macosx-kernel"; 1066 } 1067 1068 const char * 1069 DynamicLoaderDarwinKernel::GetPluginDescriptionStatic() 1070 { 1071 return "Dynamic loader plug-in that watches for shared library loads/unloads in the MacOSX kernel."; 1072 } 1073 1074 1075 //------------------------------------------------------------------ 1076 // PluginInterface protocol 1077 //------------------------------------------------------------------ 1078 const char * 1079 DynamicLoaderDarwinKernel::GetPluginName() 1080 { 1081 return "DynamicLoaderDarwinKernel"; 1082 } 1083 1084 const char * 1085 DynamicLoaderDarwinKernel::GetShortPluginName() 1086 { 1087 return GetPluginNameStatic(); 1088 } 1089 1090 uint32_t 1091 DynamicLoaderDarwinKernel::GetPluginVersion() 1092 { 1093 return 1; 1094 } 1095 1096