1 //===-- DynamicLoaderMacOSXDYLD.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 11 #include "llvm/Support/MachO.h" 12 13 #include "lldb/Breakpoint/StoppointCallbackContext.h" 14 #include "lldb/Core/DataBuffer.h" 15 #include "lldb/Core/DataBufferHeap.h" 16 #include "lldb/Core/Log.h" 17 #include "lldb/Core/Module.h" 18 #include "lldb/Core/ModuleSpec.h" 19 #include "lldb/Core/PluginManager.h" 20 #include "lldb/Core/Section.h" 21 #include "lldb/Core/State.h" 22 #include "lldb/Symbol/Function.h" 23 #include "lldb/Symbol/ObjectFile.h" 24 #include "lldb/Target/ObjCLanguageRuntime.h" 25 #include "lldb/Target/RegisterContext.h" 26 #include "lldb/Target/Target.h" 27 #include "lldb/Target/Thread.h" 28 #include "lldb/Target/ThreadPlanRunToAddress.h" 29 #include "lldb/Target/StackFrame.h" 30 31 #include "DynamicLoaderMacOSXDYLD.h" 32 33 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN 34 #ifdef ENABLE_DEBUG_PRINTF 35 #include <stdio.h> 36 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__) 37 #else 38 #define DEBUG_PRINTF(fmt, ...) 39 #endif 40 41 using namespace lldb; 42 using namespace lldb_private; 43 44 /// FIXME - The ObjC Runtime trampoline handler doesn't really belong here. 45 /// I am putting it here so I can invoke it in the Trampoline code here, but 46 /// it should be moved to the ObjC Runtime support when it is set up. 47 48 49 DynamicLoaderMacOSXDYLD::DYLDImageInfo * 50 DynamicLoaderMacOSXDYLD::GetImageInfo (Module *module) 51 { 52 const UUID &module_uuid = module->GetUUID(); 53 DYLDImageInfo::collection::iterator pos, end = m_dyld_image_infos.end(); 54 55 // First try just by UUID as it is the safest. 56 if (module_uuid.IsValid()) 57 { 58 for (pos = m_dyld_image_infos.begin(); pos != end; ++pos) 59 { 60 if (pos->uuid == module_uuid) 61 return &(*pos); 62 } 63 64 if (m_dyld.uuid == module_uuid) 65 return &m_dyld; 66 } 67 68 // Next try by platform path only for things that don't have a valid UUID 69 // since if a file has a valid UUID in real life it should also in the 70 // dyld info. This is the next safest because the paths in the dyld info 71 // are platform paths, not local paths. For local debugging platform == local 72 // paths. 73 const FileSpec &platform_file_spec = module->GetPlatformFileSpec(); 74 for (pos = m_dyld_image_infos.begin(); pos != end; ++pos) 75 { 76 if (pos->file_spec == platform_file_spec && pos->uuid.IsValid() == false) 77 return &(*pos); 78 } 79 80 if (m_dyld.file_spec == platform_file_spec && m_dyld.uuid.IsValid() == false) 81 return &m_dyld; 82 83 return NULL; 84 } 85 86 //---------------------------------------------------------------------- 87 // Create an instance of this class. This function is filled into 88 // the plugin info class that gets handed out by the plugin factory and 89 // allows the lldb to instantiate an instance of this class. 90 //---------------------------------------------------------------------- 91 DynamicLoader * 92 DynamicLoaderMacOSXDYLD::CreateInstance (Process* process, bool force) 93 { 94 bool create = force; 95 if (!create) 96 { 97 create = true; 98 Module* exe_module = process->GetTarget().GetExecutableModulePointer(); 99 if (exe_module) 100 { 101 ObjectFile *object_file = exe_module->GetObjectFile(); 102 if (object_file) 103 { 104 create = (object_file->GetStrata() == ObjectFile::eStrataUser); 105 } 106 } 107 108 if (create) 109 { 110 const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple(); 111 switch (triple_ref.getOS()) 112 { 113 case llvm::Triple::Darwin: 114 case llvm::Triple::MacOSX: 115 case llvm::Triple::IOS: 116 create = triple_ref.getVendor() == llvm::Triple::Apple; 117 break; 118 default: 119 create = false; 120 break; 121 } 122 } 123 } 124 125 if (create) 126 return new DynamicLoaderMacOSXDYLD (process); 127 return NULL; 128 } 129 130 //---------------------------------------------------------------------- 131 // Constructor 132 //---------------------------------------------------------------------- 133 DynamicLoaderMacOSXDYLD::DynamicLoaderMacOSXDYLD (Process* process) : 134 DynamicLoader(process), 135 m_dyld(), 136 m_dyld_all_image_infos_addr(LLDB_INVALID_ADDRESS), 137 m_dyld_all_image_infos(), 138 m_dyld_all_image_infos_stop_id (UINT32_MAX), 139 m_break_id(LLDB_INVALID_BREAK_ID), 140 m_dyld_image_infos(), 141 m_dyld_image_infos_stop_id (UINT32_MAX), 142 m_mutex(Mutex::eMutexTypeRecursive) 143 { 144 } 145 146 //---------------------------------------------------------------------- 147 // Destructor 148 //---------------------------------------------------------------------- 149 DynamicLoaderMacOSXDYLD::~DynamicLoaderMacOSXDYLD() 150 { 151 Clear(true); 152 } 153 154 //------------------------------------------------------------------ 155 /// Called after attaching a process. 156 /// 157 /// Allow DynamicLoader plug-ins to execute some code after 158 /// attaching to a process. 159 //------------------------------------------------------------------ 160 void 161 DynamicLoaderMacOSXDYLD::DidAttach () 162 { 163 PrivateInitialize(m_process); 164 LocateDYLD (); 165 SetNotificationBreakpoint (); 166 } 167 168 //------------------------------------------------------------------ 169 /// Called after attaching a process. 170 /// 171 /// Allow DynamicLoader plug-ins to execute some code after 172 /// attaching to a process. 173 //------------------------------------------------------------------ 174 void 175 DynamicLoaderMacOSXDYLD::DidLaunch () 176 { 177 PrivateInitialize(m_process); 178 LocateDYLD (); 179 SetNotificationBreakpoint (); 180 } 181 182 183 //---------------------------------------------------------------------- 184 // Clear out the state of this class. 185 //---------------------------------------------------------------------- 186 void 187 DynamicLoaderMacOSXDYLD::Clear (bool clear_process) 188 { 189 Mutex::Locker locker(m_mutex); 190 191 if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id)) 192 m_process->ClearBreakpointSiteByID(m_break_id); 193 194 if (clear_process) 195 m_process = NULL; 196 m_dyld.Clear(false); 197 m_dyld_all_image_infos_addr = LLDB_INVALID_ADDRESS; 198 m_dyld_all_image_infos.Clear(); 199 m_break_id = LLDB_INVALID_BREAK_ID; 200 m_dyld_image_infos.clear(); 201 } 202 203 //---------------------------------------------------------------------- 204 // Check if we have found DYLD yet 205 //---------------------------------------------------------------------- 206 bool 207 DynamicLoaderMacOSXDYLD::DidSetNotificationBreakpoint() const 208 { 209 return LLDB_BREAK_ID_IS_VALID (m_break_id); 210 } 211 212 //---------------------------------------------------------------------- 213 // Try and figure out where dyld is by first asking the Process 214 // if it knows (which currently calls down in the the lldb::Process 215 // to get the DYLD info (available on SnowLeopard only). If that fails, 216 // then check in the default addresses. 217 //---------------------------------------------------------------------- 218 bool 219 DynamicLoaderMacOSXDYLD::LocateDYLD() 220 { 221 if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS) 222 { 223 // Check the image info addr as it might point to the 224 // mach header for dyld, or it might point to the 225 // dyld_all_image_infos struct 226 const addr_t shlib_addr = m_process->GetImageInfoAddress (); 227 228 ByteOrder byte_order = m_process->GetTarget().GetArchitecture().GetByteOrder(); 229 uint8_t buf[4]; 230 DataExtractor data (buf, sizeof(buf), byte_order, 4); 231 Error error; 232 if (m_process->ReadMemory (shlib_addr, buf, 4, error) == 4) 233 { 234 uint32_t offset = 0; 235 uint32_t magic = data.GetU32 (&offset); 236 switch (magic) 237 { 238 case llvm::MachO::HeaderMagic32: 239 case llvm::MachO::HeaderMagic64: 240 case llvm::MachO::HeaderMagic32Swapped: 241 case llvm::MachO::HeaderMagic64Swapped: 242 return ReadDYLDInfoFromMemoryAndSetNotificationCallback(shlib_addr); 243 244 default: 245 break; 246 } 247 } 248 // Maybe it points to the all image infos? 249 m_dyld_all_image_infos_addr = shlib_addr; 250 } 251 252 if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) 253 { 254 if (ReadAllImageInfosStructure ()) 255 { 256 if (m_dyld_all_image_infos.dyldImageLoadAddress != LLDB_INVALID_ADDRESS) 257 return ReadDYLDInfoFromMemoryAndSetNotificationCallback (m_dyld_all_image_infos.dyldImageLoadAddress); 258 else 259 return ReadDYLDInfoFromMemoryAndSetNotificationCallback (m_dyld_all_image_infos_addr & 0xfffffffffff00000ull); 260 } 261 } 262 263 // Check some default values 264 Module *executable = m_process->GetTarget().GetExecutableModulePointer(); 265 266 if (executable) 267 { 268 const ArchSpec &exe_arch = executable->GetArchitecture(); 269 if (exe_arch.GetAddressByteSize() == 8) 270 { 271 return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x7fff5fc00000ull); 272 } 273 else if (exe_arch.GetMachine() == llvm::Triple::arm || exe_arch.GetMachine() == llvm::Triple::thumb) 274 { 275 return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x2fe00000); 276 } 277 else 278 { 279 return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x8fe00000); 280 } 281 } 282 return false; 283 } 284 285 ModuleSP 286 DynamicLoaderMacOSXDYLD::FindTargetModuleForDYLDImageInfo (const DYLDImageInfo &image_info, bool can_create, bool *did_create_ptr) 287 { 288 if (did_create_ptr) 289 *did_create_ptr = false; 290 291 292 const ModuleList &target_images = m_process->GetTarget().GetImages(); 293 ModuleSpec module_spec (image_info.file_spec, image_info.GetArchitecture ()); 294 module_spec.GetUUID() = image_info.uuid; 295 ModuleSP module_sp (target_images.FindFirstModule (module_spec)); 296 297 if (module_sp && !module_spec.GetUUID().IsValid() && !module_sp->GetUUID().IsValid()) 298 { 299 // No UUID, we must rely upon the cached module modification 300 // time and the modification time of the file on disk 301 if (module_sp->GetModificationTime() != module_sp->GetFileSpec().GetModificationTime()) 302 module_sp.reset(); 303 } 304 305 if (!module_sp) 306 { 307 if (can_create) 308 { 309 module_sp = m_process->GetTarget().GetSharedModule (module_spec); 310 if (!module_sp || module_sp->GetObjectFile() == NULL) 311 { 312 const bool add_image_to_target = true; 313 const bool load_image_sections_in_target = false; 314 module_sp = m_process->ReadModuleFromMemory (image_info.file_spec, 315 image_info.address, 316 add_image_to_target, 317 load_image_sections_in_target); 318 } 319 320 if (did_create_ptr) 321 *did_create_ptr = (bool) module_sp; 322 } 323 } 324 return module_sp; 325 } 326 327 //---------------------------------------------------------------------- 328 // Assume that dyld is in memory at ADDR and try to parse it's load 329 // commands 330 //---------------------------------------------------------------------- 331 bool 332 DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback(lldb::addr_t addr) 333 { 334 DataExtractor data; // Load command data 335 if (ReadMachHeader (addr, &m_dyld.header, &data)) 336 { 337 if (m_dyld.header.filetype == llvm::MachO::HeaderFileTypeDynamicLinkEditor) 338 { 339 m_dyld.address = addr; 340 ModuleSP dyld_module_sp; 341 if (ParseLoadCommands (data, m_dyld, &m_dyld.file_spec)) 342 { 343 if (m_dyld.file_spec) 344 { 345 dyld_module_sp = FindTargetModuleForDYLDImageInfo (m_dyld, true, NULL); 346 347 if (dyld_module_sp) 348 UpdateImageLoadAddress (dyld_module_sp.get(), m_dyld); 349 } 350 } 351 352 if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS && dyld_module_sp.get()) 353 { 354 static ConstString g_dyld_all_image_infos ("dyld_all_image_infos"); 355 const Symbol *symbol = dyld_module_sp->FindFirstSymbolWithNameAndType (g_dyld_all_image_infos, eSymbolTypeData); 356 if (symbol) 357 m_dyld_all_image_infos_addr = symbol->GetAddress().GetLoadAddress(&m_process->GetTarget()); 358 } 359 360 // Update all image infos 361 InitializeFromAllImageInfos (); 362 363 // If we didn't have an executable before, but now we do, then the 364 // dyld module shared pointer might be unique and we may need to add 365 // it again (since Target::SetExecutableModule() will clear the 366 // images). So append the dyld module back to the list if it is 367 /// unique! 368 if (dyld_module_sp && m_process->GetTarget().GetImages().AppendIfNeeded (dyld_module_sp)) 369 UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld); 370 371 return true; 372 } 373 } 374 return false; 375 } 376 377 bool 378 DynamicLoaderMacOSXDYLD::NeedToLocateDYLD () const 379 { 380 return m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS; 381 } 382 383 bool 384 DynamicLoaderMacOSXDYLD::UpdateCommPageLoadAddress(Module *module) 385 { 386 bool changed = false; 387 if (module) 388 { 389 ObjectFile *image_object_file = module->GetObjectFile(); 390 if (image_object_file) 391 { 392 SectionList *section_list = image_object_file->GetSectionList (); 393 if (section_list) 394 { 395 uint32_t num_sections = section_list->GetSize(); 396 for (uint32_t i=0; i<num_sections; ++i) 397 { 398 SectionSP section_sp (section_list->GetSectionAtIndex (i)); 399 if (section_sp) 400 { 401 const addr_t new_section_load_addr = section_sp->GetFileAddress (); 402 const addr_t old_section_load_addr = m_process->GetTarget().GetSectionLoadList().GetSectionLoadAddress (section_sp); 403 if (old_section_load_addr == LLDB_INVALID_ADDRESS || 404 old_section_load_addr != new_section_load_addr) 405 { 406 if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress ())) 407 changed = true; 408 } 409 } 410 } 411 } 412 } 413 } 414 return changed; 415 } 416 417 //---------------------------------------------------------------------- 418 // Update the load addresses for all segments in MODULE using the 419 // updated INFO that is passed in. 420 //---------------------------------------------------------------------- 421 bool 422 DynamicLoaderMacOSXDYLD::UpdateImageLoadAddress (Module *module, DYLDImageInfo& info) 423 { 424 bool changed = false; 425 if (module) 426 { 427 ObjectFile *image_object_file = module->GetObjectFile(); 428 if (image_object_file) 429 { 430 SectionList *section_list = image_object_file->GetSectionList (); 431 if (section_list) 432 { 433 std::vector<uint32_t> inaccessible_segment_indexes; 434 // We now know the slide amount, so go through all sections 435 // and update the load addresses with the correct values. 436 uint32_t num_segments = info.segments.size(); 437 for (uint32_t i=0; i<num_segments; ++i) 438 { 439 // Only load a segment if it has protections. Things like 440 // __PAGEZERO don't have any protections, and they shouldn't 441 // be slid 442 SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name)); 443 444 if (info.segments[i].maxprot == 0) 445 { 446 inaccessible_segment_indexes.push_back(i); 447 } 448 else 449 { 450 const addr_t new_section_load_addr = info.segments[i].vmaddr + info.slide; 451 static ConstString g_section_name_LINKEDIT ("__LINKEDIT"); 452 453 if (section_sp) 454 { 455 // __LINKEDIT sections from files in the shared cache 456 // can overlap so check to see what the segment name is 457 // and pass "false" so we don't warn of overlapping 458 // "Section" objects, and "true" for all other sections. 459 const bool warn_multiple = section_sp->GetName() != g_section_name_LINKEDIT; 460 461 const addr_t old_section_load_addr = m_process->GetTarget().GetSectionLoadList().GetSectionLoadAddress (section_sp); 462 if (old_section_load_addr == LLDB_INVALID_ADDRESS || 463 old_section_load_addr != new_section_load_addr) 464 { 465 if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section_sp, new_section_load_addr, warn_multiple)) 466 changed = true; 467 } 468 } 469 else 470 { 471 Host::SystemLog (Host::eSystemLogWarning, 472 "warning: unable to find and load segment named '%s' at 0x%llx in '%s/%s' in macosx dynamic loader plug-in.\n", 473 info.segments[i].name.AsCString("<invalid>"), 474 (uint64_t)new_section_load_addr, 475 image_object_file->GetFileSpec().GetDirectory().AsCString(), 476 image_object_file->GetFileSpec().GetFilename().AsCString()); 477 } 478 } 479 } 480 481 // If the loaded the file (it changed) and we have segments that 482 // are not readable or writeable, add them to the invalid memory 483 // region cache for the process. This will typically only be 484 // the __PAGEZERO segment in the main executable. We might be able 485 // to apply this more generally to more sections that have no 486 // protections in the future, but for now we are going to just 487 // do __PAGEZERO. 488 if (changed && !inaccessible_segment_indexes.empty()) 489 { 490 for (uint32_t i=0; i<inaccessible_segment_indexes.size(); ++i) 491 { 492 const uint32_t seg_idx = inaccessible_segment_indexes[i]; 493 SectionSP section_sp(section_list->FindSectionByName(info.segments[seg_idx].name)); 494 495 if (section_sp) 496 { 497 static ConstString g_pagezero_section_name("__PAGEZERO"); 498 if (g_pagezero_section_name == section_sp->GetName()) 499 { 500 // __PAGEZERO never slides... 501 const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr; 502 const lldb::addr_t vmsize = info.segments[seg_idx].vmsize; 503 Process::LoadRange pagezero_range (vmaddr, vmsize); 504 m_process->AddInvalidMemoryRegion(pagezero_range); 505 } 506 } 507 } 508 } 509 } 510 } 511 } 512 return changed; 513 } 514 515 //---------------------------------------------------------------------- 516 // Update the load addresses for all segments in MODULE using the 517 // updated INFO that is passed in. 518 //---------------------------------------------------------------------- 519 bool 520 DynamicLoaderMacOSXDYLD::UnloadImageLoadAddress (Module *module, DYLDImageInfo& info) 521 { 522 bool changed = false; 523 if (module) 524 { 525 ObjectFile *image_object_file = module->GetObjectFile(); 526 if (image_object_file) 527 { 528 SectionList *section_list = image_object_file->GetSectionList (); 529 if (section_list) 530 { 531 uint32_t num_segments = info.segments.size(); 532 for (uint32_t i=0; i<num_segments; ++i) 533 { 534 SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name)); 535 if (section_sp) 536 { 537 const addr_t old_section_load_addr = info.segments[i].vmaddr + info.slide; 538 if (m_process->GetTarget().GetSectionLoadList().SetSectionUnloaded (section_sp, old_section_load_addr)) 539 changed = true; 540 } 541 else 542 { 543 Host::SystemLog (Host::eSystemLogWarning, 544 "warning: unable to find and unload segment named '%s' in '%s/%s' in macosx dynamic loader plug-in.\n", 545 info.segments[i].name.AsCString("<invalid>"), 546 image_object_file->GetFileSpec().GetDirectory().AsCString(), 547 image_object_file->GetFileSpec().GetFilename().AsCString()); 548 } 549 } 550 } 551 } 552 } 553 return changed; 554 } 555 556 557 //---------------------------------------------------------------------- 558 // Static callback function that gets called when our DYLD notification 559 // breakpoint gets hit. We update all of our image infos and then 560 // let our super class DynamicLoader class decide if we should stop 561 // or not (based on global preference). 562 //---------------------------------------------------------------------- 563 bool 564 DynamicLoaderMacOSXDYLD::NotifyBreakpointHit (void *baton, 565 StoppointCallbackContext *context, 566 lldb::user_id_t break_id, 567 lldb::user_id_t break_loc_id) 568 { 569 // Let the event know that the images have changed 570 // DYLD passes three arguments to the notification breakpoint. 571 // Arg1: enum dyld_image_mode mode - 0 = adding, 1 = removing 572 // Arg2: uint32_t infoCount - Number of shared libraries added 573 // Arg3: dyld_image_info info[] - Array of structs of the form: 574 // const struct mach_header *imageLoadAddress 575 // const char *imageFilePath 576 // uintptr_t imageFileModDate (a time_t) 577 578 DynamicLoaderMacOSXDYLD* dyld_instance = (DynamicLoaderMacOSXDYLD*) baton; 579 580 // First step is to see if we've already initialized the all image infos. If we haven't then this function 581 // will do so and return true. In the course of initializing the all_image_infos it will read the complete 582 // current state, so we don't need to figure out what has changed from the data passed in to us. 583 584 if (dyld_instance->InitializeFromAllImageInfos()) 585 return dyld_instance->GetStopWhenImagesChange(); 586 587 ExecutionContext exe_ctx (context->exe_ctx_ref); 588 Process *process = exe_ctx.GetProcessPtr(); 589 const lldb::ABISP &abi = process->GetABI(); 590 if (abi) 591 { 592 // Build up the value array to store the three arguments given above, then get the values from the ABI: 593 594 ClangASTContext *clang_ast_context = process->GetTarget().GetScratchClangASTContext(); 595 ValueList argument_values; 596 Value input_value; 597 598 void *clang_void_ptr_type = clang_ast_context->GetVoidPtrType(false); 599 void *clang_uint32_type = clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(lldb::eEncodingUint, 32); 600 input_value.SetValueType (Value::eValueTypeScalar); 601 input_value.SetContext (Value::eContextTypeClangType, clang_uint32_type); 602 argument_values.PushValue(input_value); 603 argument_values.PushValue(input_value); 604 input_value.SetContext (Value::eContextTypeClangType, clang_void_ptr_type); 605 argument_values.PushValue (input_value); 606 607 if (abi->GetArgumentValues (exe_ctx.GetThreadRef(), argument_values)) 608 { 609 uint32_t dyld_mode = argument_values.GetValueAtIndex(0)->GetScalar().UInt (-1); 610 if (dyld_mode != -1) 611 { 612 // Okay the mode was right, now get the number of elements, and the array of new elements... 613 uint32_t image_infos_count = argument_values.GetValueAtIndex(1)->GetScalar().UInt (-1); 614 if (image_infos_count != -1) 615 { 616 // Got the number added, now go through the array of added elements, putting out the mach header 617 // address, and adding the image. 618 // Note, I'm not putting in logging here, since the AddModules & RemoveModules functions do 619 // all the logging internally. 620 621 lldb::addr_t image_infos_addr = argument_values.GetValueAtIndex(2)->GetScalar().ULongLong(); 622 if (dyld_mode == 0) 623 { 624 // This is add: 625 dyld_instance->AddModulesUsingImageInfosAddress (image_infos_addr, image_infos_count); 626 } 627 else 628 { 629 // This is remove: 630 dyld_instance->RemoveModulesUsingImageInfosAddress (image_infos_addr, image_infos_count); 631 } 632 633 } 634 } 635 } 636 } 637 638 // Return true to stop the target, false to just let the target run 639 return dyld_instance->GetStopWhenImagesChange(); 640 } 641 642 bool 643 DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure () 644 { 645 Mutex::Locker locker(m_mutex); 646 647 // the all image infos is already valid for this process stop ID 648 if (m_process->GetStopID() == m_dyld_all_image_infos_stop_id) 649 return true; 650 651 m_dyld_all_image_infos.Clear(); 652 if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) 653 { 654 ByteOrder byte_order = m_process->GetTarget().GetArchitecture().GetByteOrder(); 655 uint32_t addr_size = 4; 656 if (m_dyld_all_image_infos_addr > UINT32_MAX) 657 addr_size = 8; 658 659 uint8_t buf[256]; 660 DataExtractor data (buf, sizeof(buf), byte_order, addr_size); 661 uint32_t offset = 0; 662 663 const size_t count_v2 = sizeof (uint32_t) + // version 664 sizeof (uint32_t) + // infoArrayCount 665 addr_size + // infoArray 666 addr_size + // notification 667 addr_size + // processDetachedFromSharedRegion + libSystemInitialized + pad 668 addr_size; // dyldImageLoadAddress 669 const size_t count_v11 = count_v2 + 670 addr_size + // jitInfo 671 addr_size + // dyldVersion 672 addr_size + // errorMessage 673 addr_size + // terminationFlags 674 addr_size + // coreSymbolicationShmPage 675 addr_size + // systemOrderFlag 676 addr_size + // uuidArrayCount 677 addr_size + // uuidArray 678 addr_size + // dyldAllImageInfosAddress 679 addr_size + // initialImageCount 680 addr_size + // errorKind 681 addr_size + // errorClientOfDylibPath 682 addr_size + // errorTargetDylibPath 683 addr_size; // errorSymbol 684 assert (sizeof (buf) >= count_v11); 685 686 int count; 687 Error error; 688 if (m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, 4, error) == 4) 689 { 690 m_dyld_all_image_infos.version = data.GetU32(&offset); 691 // If anything in the high byte is set, we probably got the byte 692 // order incorrect (the process might not have it set correctly 693 // yet due to attaching to a program without a specified file). 694 if (m_dyld_all_image_infos.version & 0xff000000) 695 { 696 // We have guessed the wrong byte order. Swap it and try 697 // reading the version again. 698 if (byte_order == eByteOrderLittle) 699 byte_order = eByteOrderBig; 700 else 701 byte_order = eByteOrderLittle; 702 703 data.SetByteOrder (byte_order); 704 offset = 0; 705 m_dyld_all_image_infos.version = data.GetU32(&offset); 706 } 707 } 708 else 709 { 710 return false; 711 } 712 713 if (m_dyld_all_image_infos.version >= 11) 714 count = count_v11; 715 else 716 count = count_v2; 717 718 const size_t bytes_read = m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, count, error); 719 if (bytes_read == count) 720 { 721 offset = 0; 722 m_dyld_all_image_infos.version = data.GetU32(&offset); 723 m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset); 724 m_dyld_all_image_infos.dylib_info_addr = data.GetPointer(&offset); 725 m_dyld_all_image_infos.notification = data.GetPointer(&offset); 726 m_dyld_all_image_infos.processDetachedFromSharedRegion = data.GetU8(&offset); 727 m_dyld_all_image_infos.libSystemInitialized = data.GetU8(&offset); 728 // Adjust for padding. 729 offset += addr_size - 2; 730 m_dyld_all_image_infos.dyldImageLoadAddress = data.GetPointer(&offset); 731 if (m_dyld_all_image_infos.version >= 11) 732 { 733 offset += addr_size * 8; 734 uint64_t dyld_all_image_infos_addr = data.GetPointer(&offset); 735 736 // When we started, we were given the actual address of the all_image_infos 737 // struct (probably via TASK_DYLD_INFO) in memory - this address is stored in 738 // m_dyld_all_image_infos_addr and is the most accurate address we have. 739 740 // We read the dyld_all_image_infos struct from memory; it contains its own address. 741 // If the address in the struct does not match the actual address, 742 // the dyld we're looking at has been loaded at a different location (slid) from 743 // where it intended to load. The addresses in the dyld_all_image_infos struct 744 // are the original, non-slid addresses, and need to be adjusted. Most importantly 745 // the address of dyld and the notification address need to be adjusted. 746 747 if (dyld_all_image_infos_addr != m_dyld_all_image_infos_addr) 748 { 749 uint64_t image_infos_offset = dyld_all_image_infos_addr - m_dyld_all_image_infos.dyldImageLoadAddress; 750 uint64_t notification_offset = m_dyld_all_image_infos.notification - m_dyld_all_image_infos.dyldImageLoadAddress; 751 m_dyld_all_image_infos.dyldImageLoadAddress = m_dyld_all_image_infos_addr - image_infos_offset; 752 m_dyld_all_image_infos.notification = m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset; 753 } 754 } 755 m_dyld_all_image_infos_stop_id = m_process->GetStopID(); 756 return true; 757 } 758 } 759 return false; 760 } 761 762 763 bool 764 DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfosAddress (lldb::addr_t image_infos_addr, uint32_t image_infos_count) 765 { 766 DYLDImageInfo::collection image_infos; 767 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER)); 768 if (log) 769 log->Printf ("Adding %d modules.\n", image_infos_count); 770 771 Mutex::Locker locker(m_mutex); 772 if (m_process->GetStopID() == m_dyld_image_infos_stop_id) 773 return true; 774 775 if (!ReadImageInfos (image_infos_addr, image_infos_count, image_infos)) 776 return false; 777 778 UpdateImageInfosHeaderAndLoadCommands (image_infos, image_infos_count, false); 779 bool return_value = AddModulesUsingImageInfos (image_infos); 780 m_dyld_image_infos_stop_id = m_process->GetStopID(); 781 return return_value; 782 } 783 784 // Adds the modules in image_infos to m_dyld_image_infos. 785 // NB don't call this passing in m_dyld_image_infos. 786 787 bool 788 DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfos (DYLDImageInfo::collection &image_infos) 789 { 790 // Now add these images to the main list. 791 ModuleList loaded_module_list; 792 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER)); 793 794 for (uint32_t idx = 0; idx < image_infos.size(); ++idx) 795 { 796 if (log) 797 { 798 log->Printf ("Adding new image at address=0x%16.16llx.", image_infos[idx].address); 799 image_infos[idx].PutToLog (log.get()); 800 } 801 802 m_dyld_image_infos.push_back(image_infos[idx]); 803 804 ModuleSP image_module_sp (FindTargetModuleForDYLDImageInfo (image_infos[idx], true, NULL)); 805 806 if (image_module_sp) 807 { 808 if (image_infos[idx].header.filetype == llvm::MachO::HeaderFileTypeDynamicLinkEditor) 809 image_module_sp->SetIsDynamicLinkEditor (true); 810 811 ObjectFile *objfile = image_module_sp->GetObjectFile (); 812 if (objfile) 813 { 814 SectionList *sections = objfile->GetSectionList(); 815 if (sections) 816 { 817 ConstString commpage_dbstr("__commpage"); 818 Section *commpage_section = sections->FindSectionByName(commpage_dbstr).get(); 819 if (commpage_section) 820 { 821 const ModuleList& target_images = m_process->GetTarget().GetImages(); 822 ModuleSpec module_spec (objfile->GetFileSpec(), image_infos[idx].GetArchitecture ()); 823 module_spec.GetObjectName() = commpage_dbstr; 824 ModuleSP commpage_image_module_sp(target_images.FindFirstModule (module_spec)); 825 if (!commpage_image_module_sp) 826 { 827 module_spec.SetObjectOffset (objfile->GetOffset() + commpage_section->GetFileOffset()); 828 commpage_image_module_sp = m_process->GetTarget().GetSharedModule (module_spec); 829 if (!commpage_image_module_sp || commpage_image_module_sp->GetObjectFile() == NULL) 830 { 831 const bool add_image_to_target = true; 832 const bool load_image_sections_in_target = false; 833 commpage_image_module_sp = m_process->ReadModuleFromMemory (image_infos[idx].file_spec, 834 image_infos[idx].address, 835 add_image_to_target, 836 load_image_sections_in_target); 837 } 838 } 839 if (commpage_image_module_sp) 840 UpdateCommPageLoadAddress (commpage_image_module_sp.get()); 841 } 842 } 843 } 844 845 // UpdateImageLoadAddress will return true if any segments 846 // change load address. We need to check this so we don't 847 // mention that all loaded shared libraries are newly loaded 848 // each time we hit out dyld breakpoint since dyld will list all 849 // shared libraries each time. 850 if (UpdateImageLoadAddress (image_module_sp.get(), image_infos[idx])) 851 { 852 loaded_module_list.AppendIfNeeded (image_module_sp); 853 } 854 } 855 } 856 857 if (loaded_module_list.GetSize() > 0) 858 { 859 // FIXME: This should really be in the Runtime handlers class, which should get 860 // called by the target's ModulesDidLoad, but we're doing it all locally for now 861 // to save time. 862 // Also, I'm assuming there can be only one libobjc dylib loaded... 863 864 ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime(true); 865 if (objc_runtime != NULL && !objc_runtime->HasReadObjCLibrary()) 866 { 867 size_t num_modules = loaded_module_list.GetSize(); 868 for (int i = 0; i < num_modules; i++) 869 { 870 if (objc_runtime->IsModuleObjCLibrary (loaded_module_list.GetModuleAtIndex (i))) 871 { 872 objc_runtime->ReadObjCLibrary (loaded_module_list.GetModuleAtIndex (i)); 873 break; 874 } 875 } 876 } 877 if (log) 878 loaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderMacOSXDYLD::ModulesDidLoad"); 879 m_process->GetTarget().ModulesDidLoad (loaded_module_list); 880 } 881 return true; 882 } 883 884 bool 885 DynamicLoaderMacOSXDYLD::RemoveModulesUsingImageInfosAddress (lldb::addr_t image_infos_addr, uint32_t image_infos_count) 886 { 887 DYLDImageInfo::collection image_infos; 888 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER)); 889 890 Mutex::Locker locker(m_mutex); 891 if (m_process->GetStopID() == m_dyld_image_infos_stop_id) 892 return true; 893 894 // First read in the image_infos for the removed modules, and their headers & load commands. 895 if (!ReadImageInfos (image_infos_addr, image_infos_count, image_infos)) 896 { 897 if (log) 898 log->PutCString ("Failed reading image infos array."); 899 return false; 900 } 901 902 if (log) 903 log->Printf ("Removing %d modules.", image_infos_count); 904 905 ModuleList unloaded_module_list; 906 for (uint32_t idx = 0; idx < image_infos.size(); ++idx) 907 { 908 if (log) 909 { 910 log->Printf ("Removing module at address=0x%16.16llx.", image_infos[idx].address); 911 image_infos[idx].PutToLog (log.get()); 912 } 913 914 // Remove this image_infos from the m_all_image_infos. We do the comparision by address 915 // rather than by file spec because we can have many modules with the same "file spec" in the 916 // case that they are modules loaded from memory. 917 // 918 // Also copy over the uuid from the old entry to the removed entry so we can 919 // use it to lookup the module in the module list. 920 921 DYLDImageInfo::collection::iterator pos, end = m_dyld_image_infos.end(); 922 for (pos = m_dyld_image_infos.begin(); pos != end; pos++) 923 { 924 if (image_infos[idx].address == (*pos).address) 925 { 926 image_infos[idx].uuid = (*pos).uuid; 927 928 // Add the module from this image_info to the "unloaded_module_list". We'll remove them all at 929 // one go later on. 930 931 ModuleSP unload_image_module_sp (FindTargetModuleForDYLDImageInfo (image_infos[idx], false, NULL)); 932 if (unload_image_module_sp.get()) 933 { 934 // When we unload, be sure to use the image info from the old list, 935 // since that has sections correctly filled in. 936 UnloadImageLoadAddress (unload_image_module_sp.get(), *pos); 937 unloaded_module_list.AppendIfNeeded (unload_image_module_sp); 938 } 939 else 940 { 941 if (log) 942 { 943 log->Printf ("Could not find module for unloading info entry:"); 944 image_infos[idx].PutToLog(log.get()); 945 } 946 } 947 948 // Then remove it from the m_dyld_image_infos: 949 950 m_dyld_image_infos.erase(pos); 951 break; 952 } 953 } 954 955 if (pos == end) 956 { 957 if (log) 958 { 959 log->Printf ("Could not find image_info entry for unloading image:"); 960 image_infos[idx].PutToLog(log.get()); 961 } 962 } 963 } 964 if (unloaded_module_list.GetSize() > 0) 965 { 966 if (log) 967 { 968 log->PutCString("Unloaded:"); 969 unloaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderMacOSXDYLD::ModulesDidUnload"); 970 } 971 m_process->GetTarget().GetImages().Remove (unloaded_module_list); 972 } 973 m_dyld_image_infos_stop_id = m_process->GetStopID(); 974 return true; 975 } 976 977 bool 978 DynamicLoaderMacOSXDYLD::ReadImageInfos (lldb::addr_t image_infos_addr, 979 uint32_t image_infos_count, 980 DYLDImageInfo::collection &image_infos) 981 { 982 const ByteOrder endian = m_dyld.GetByteOrder(); 983 const uint32_t addr_size = m_dyld.GetAddressByteSize(); 984 985 image_infos.resize(image_infos_count); 986 const size_t count = image_infos.size() * 3 * addr_size; 987 DataBufferHeap info_data(count, 0); 988 Error error; 989 const size_t bytes_read = m_process->ReadMemory (image_infos_addr, 990 info_data.GetBytes(), 991 info_data.GetByteSize(), 992 error); 993 if (bytes_read == count) 994 { 995 uint32_t info_data_offset = 0; 996 DataExtractor info_data_ref(info_data.GetBytes(), info_data.GetByteSize(), endian, addr_size); 997 for (int i = 0; i < image_infos.size() && info_data_ref.ValidOffset(info_data_offset); i++) 998 { 999 image_infos[i].address = info_data_ref.GetPointer(&info_data_offset); 1000 lldb::addr_t path_addr = info_data_ref.GetPointer(&info_data_offset); 1001 image_infos[i].mod_date = info_data_ref.GetPointer(&info_data_offset); 1002 1003 char raw_path[PATH_MAX]; 1004 m_process->ReadCStringFromMemory (path_addr, raw_path, sizeof(raw_path), error); 1005 // don't resolve the path 1006 if (error.Success()) 1007 { 1008 const bool resolve_path = false; 1009 image_infos[i].file_spec.SetFile(raw_path, resolve_path); 1010 } 1011 } 1012 return true; 1013 } 1014 else 1015 { 1016 return false; 1017 } 1018 } 1019 1020 //---------------------------------------------------------------------- 1021 // If we have found where the "_dyld_all_image_infos" lives in memory, 1022 // read the current info from it, and then update all image load 1023 // addresses (or lack thereof). Only do this if this is the first time 1024 // we're reading the dyld infos. Return true if we actually read anything, 1025 // and false otherwise. 1026 //---------------------------------------------------------------------- 1027 bool 1028 DynamicLoaderMacOSXDYLD::InitializeFromAllImageInfos () 1029 { 1030 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER)); 1031 1032 Mutex::Locker locker(m_mutex); 1033 if (m_process->GetStopID() == m_dyld_image_infos_stop_id 1034 || m_dyld_image_infos.size() != 0) 1035 return false; 1036 1037 if (ReadAllImageInfosStructure ()) 1038 { 1039 // Nothing to load or unload? 1040 if (m_dyld_all_image_infos.dylib_info_count == 0) 1041 return true; 1042 1043 if (m_dyld_all_image_infos.dylib_info_addr == 0) 1044 { 1045 // DYLD is updating the images now. So we should say we have no images, and then we'll 1046 // figure it out when we hit the added breakpoint. 1047 return false; 1048 } 1049 else 1050 { 1051 if (!AddModulesUsingImageInfosAddress (m_dyld_all_image_infos.dylib_info_addr, 1052 m_dyld_all_image_infos.dylib_info_count)) 1053 { 1054 DEBUG_PRINTF( "unable to read all data for all_dylib_infos."); 1055 m_dyld_image_infos.clear(); 1056 } 1057 } 1058 1059 // Now we have one more bit of business. If there is a library left in the images for our target that 1060 // doesn't have a load address, then it must be something that we were expecting to load (for instance we 1061 // read a load command for it) but it didn't in fact load - probably because DYLD_*_PATH pointed 1062 // to an equivalent version. We don't want it to stay in the target's module list or it will confuse 1063 // us, so unload it here. 1064 Target &target = m_process->GetTarget(); 1065 const ModuleList &target_modules = target.GetImages(); 1066 ModuleList not_loaded_modules; 1067 Mutex::Locker modules_locker(target_modules.GetMutex()); 1068 1069 size_t num_modules = target_modules.GetSize(); 1070 for (size_t i = 0; i < num_modules; i++) 1071 { 1072 ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked (i); 1073 if (!module_sp->IsLoadedInTarget (&target)) 1074 { 1075 if (log) 1076 { 1077 StreamString s; 1078 module_sp->GetDescription (&s); 1079 log->Printf ("Unloading pre-run module: %s.", s.GetData ()); 1080 } 1081 not_loaded_modules.Append (module_sp); 1082 } 1083 } 1084 1085 if (not_loaded_modules.GetSize() != 0) 1086 { 1087 target.GetImages().Remove(not_loaded_modules); 1088 } 1089 1090 return true; 1091 } 1092 else 1093 return false; 1094 } 1095 1096 //---------------------------------------------------------------------- 1097 // Read a mach_header at ADDR into HEADER, and also fill in the load 1098 // command data into LOAD_COMMAND_DATA if it is non-NULL. 1099 // 1100 // Returns true if we succeed, false if we fail for any reason. 1101 //---------------------------------------------------------------------- 1102 bool 1103 DynamicLoaderMacOSXDYLD::ReadMachHeader (lldb::addr_t addr, llvm::MachO::mach_header *header, DataExtractor *load_command_data) 1104 { 1105 DataBufferHeap header_bytes(sizeof(llvm::MachO::mach_header), 0); 1106 Error error; 1107 size_t bytes_read = m_process->ReadMemory (addr, 1108 header_bytes.GetBytes(), 1109 header_bytes.GetByteSize(), 1110 error); 1111 if (bytes_read == sizeof(llvm::MachO::mach_header)) 1112 { 1113 uint32_t offset = 0; 1114 ::memset (header, 0, sizeof(llvm::MachO::mach_header)); 1115 1116 // Get the magic byte unswapped so we can figure out what we are dealing with 1117 DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(), lldb::endian::InlHostByteOrder(), 4); 1118 header->magic = data.GetU32(&offset); 1119 lldb::addr_t load_cmd_addr = addr; 1120 data.SetByteOrder(DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header->magic)); 1121 switch (header->magic) 1122 { 1123 case llvm::MachO::HeaderMagic32: 1124 case llvm::MachO::HeaderMagic32Swapped: 1125 data.SetAddressByteSize(4); 1126 load_cmd_addr += sizeof(llvm::MachO::mach_header); 1127 break; 1128 1129 case llvm::MachO::HeaderMagic64: 1130 case llvm::MachO::HeaderMagic64Swapped: 1131 data.SetAddressByteSize(8); 1132 load_cmd_addr += sizeof(llvm::MachO::mach_header_64); 1133 break; 1134 1135 default: 1136 return false; 1137 } 1138 1139 // Read the rest of dyld's mach header 1140 if (data.GetU32(&offset, &header->cputype, (sizeof(llvm::MachO::mach_header)/sizeof(uint32_t)) - 1)) 1141 { 1142 if (load_command_data == NULL) 1143 return true; // We were able to read the mach_header and weren't asked to read the load command bytes 1144 1145 DataBufferSP load_cmd_data_sp(new DataBufferHeap(header->sizeofcmds, 0)); 1146 1147 size_t load_cmd_bytes_read = m_process->ReadMemory (load_cmd_addr, 1148 load_cmd_data_sp->GetBytes(), 1149 load_cmd_data_sp->GetByteSize(), 1150 error); 1151 1152 if (load_cmd_bytes_read == header->sizeofcmds) 1153 { 1154 // Set the load command data and also set the correct endian 1155 // swap settings and the correct address size 1156 load_command_data->SetData(load_cmd_data_sp, 0, header->sizeofcmds); 1157 load_command_data->SetByteOrder(data.GetByteOrder()); 1158 load_command_data->SetAddressByteSize(data.GetAddressByteSize()); 1159 return true; // We successfully read the mach_header and the load command data 1160 } 1161 1162 return false; // We weren't able to read the load command data 1163 } 1164 } 1165 return false; // We failed the read the mach_header 1166 } 1167 1168 1169 //---------------------------------------------------------------------- 1170 // Parse the load commands for an image 1171 //---------------------------------------------------------------------- 1172 uint32_t 1173 DynamicLoaderMacOSXDYLD::ParseLoadCommands (const DataExtractor& data, DYLDImageInfo& dylib_info, FileSpec *lc_id_dylinker) 1174 { 1175 uint32_t offset = 0; 1176 uint32_t cmd_idx; 1177 Segment segment; 1178 dylib_info.Clear (true); 1179 1180 for (cmd_idx = 0; cmd_idx < dylib_info.header.ncmds; cmd_idx++) 1181 { 1182 // Clear out any load command specific data from DYLIB_INFO since 1183 // we are about to read it. 1184 1185 if (data.ValidOffsetForDataOfSize (offset, sizeof(llvm::MachO::load_command))) 1186 { 1187 llvm::MachO::load_command load_cmd; 1188 uint32_t load_cmd_offset = offset; 1189 load_cmd.cmd = data.GetU32 (&offset); 1190 load_cmd.cmdsize = data.GetU32 (&offset); 1191 switch (load_cmd.cmd) 1192 { 1193 case llvm::MachO::LoadCommandSegment32: 1194 { 1195 segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16); 1196 // We are putting 4 uint32_t values 4 uint64_t values so 1197 // we have to use multiple 32 bit gets below. 1198 segment.vmaddr = data.GetU32 (&offset); 1199 segment.vmsize = data.GetU32 (&offset); 1200 segment.fileoff = data.GetU32 (&offset); 1201 segment.filesize = data.GetU32 (&offset); 1202 // Extract maxprot, initprot, nsects and flags all at once 1203 data.GetU32(&offset, &segment.maxprot, 4); 1204 dylib_info.segments.push_back (segment); 1205 } 1206 break; 1207 1208 case llvm::MachO::LoadCommandSegment64: 1209 { 1210 segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16); 1211 // Extract vmaddr, vmsize, fileoff, and filesize all at once 1212 data.GetU64(&offset, &segment.vmaddr, 4); 1213 // Extract maxprot, initprot, nsects and flags all at once 1214 data.GetU32(&offset, &segment.maxprot, 4); 1215 dylib_info.segments.push_back (segment); 1216 } 1217 break; 1218 1219 case llvm::MachO::LoadCommandDynamicLinkerIdent: 1220 if (lc_id_dylinker) 1221 { 1222 uint32_t name_offset = load_cmd_offset + data.GetU32 (&offset); 1223 const char *path = data.PeekCStr (name_offset); 1224 lc_id_dylinker->SetFile (path, true); 1225 } 1226 break; 1227 1228 case llvm::MachO::LoadCommandUUID: 1229 dylib_info.uuid.SetBytes(data.GetData (&offset, 16)); 1230 break; 1231 1232 default: 1233 break; 1234 } 1235 // Set offset to be the beginning of the next load command. 1236 offset = load_cmd_offset + load_cmd.cmdsize; 1237 } 1238 } 1239 1240 // All sections listed in the dyld image info structure will all 1241 // either be fixed up already, or they will all be off by a single 1242 // slide amount that is determined by finding the first segment 1243 // that is at file offset zero which also has bytes (a file size 1244 // that is greater than zero) in the object file. 1245 1246 // Determine the slide amount (if any) 1247 const size_t num_sections = dylib_info.segments.size(); 1248 for (size_t i = 0; i < num_sections; ++i) 1249 { 1250 // Iterate through the object file sections to find the 1251 // first section that starts of file offset zero and that 1252 // has bytes in the file... 1253 if (dylib_info.segments[i].fileoff == 0 && dylib_info.segments[i].filesize > 0) 1254 { 1255 dylib_info.slide = dylib_info.address - dylib_info.segments[i].vmaddr; 1256 // We have found the slide amount, so we can exit 1257 // this for loop. 1258 break; 1259 } 1260 } 1261 return cmd_idx; 1262 } 1263 1264 //---------------------------------------------------------------------- 1265 // Read the mach_header and load commands for each image that the 1266 // _dyld_all_image_infos structure points to and cache the results. 1267 //---------------------------------------------------------------------- 1268 1269 void 1270 DynamicLoaderMacOSXDYLD::UpdateImageInfosHeaderAndLoadCommands(DYLDImageInfo::collection &image_infos, 1271 uint32_t infos_count, 1272 bool update_executable) 1273 { 1274 uint32_t exe_idx = UINT32_MAX; 1275 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER)); 1276 // Read any UUID values that we can get 1277 for (uint32_t i = 0; i < infos_count; i++) 1278 { 1279 if (!image_infos[i].UUIDValid()) 1280 { 1281 DataExtractor data; // Load command data 1282 if (!ReadMachHeader (image_infos[i].address, &image_infos[i].header, &data)) 1283 continue; 1284 1285 ParseLoadCommands (data, image_infos[i], NULL); 1286 1287 if (image_infos[i].header.filetype == llvm::MachO::HeaderFileTypeExecutable) 1288 exe_idx = i; 1289 1290 } 1291 } 1292 1293 if (exe_idx < image_infos.size()) 1294 { 1295 const bool can_create = true; 1296 ModuleSP exe_module_sp (FindTargetModuleForDYLDImageInfo (image_infos[exe_idx], can_create, NULL)); 1297 1298 if (!exe_module_sp) 1299 { 1300 ArchSpec exe_arch_spec (image_infos[exe_idx].GetArchitecture ()); 1301 ModuleSpec module_spec (image_infos[exe_idx].file_spec, 1302 image_infos[exe_idx].GetArchitecture ()); 1303 module_spec.GetUUID() = image_infos[exe_idx].uuid; 1304 exe_module_sp = m_process->GetTarget().GetSharedModule (module_spec); 1305 if (!exe_module_sp || exe_module_sp->GetObjectFile() == NULL) 1306 { 1307 const bool add_image_to_target = true; 1308 const bool load_image_sections_in_target = false; 1309 exe_module_sp = m_process->ReadModuleFromMemory (image_infos[exe_idx].file_spec, 1310 image_infos[exe_idx].address, 1311 add_image_to_target, 1312 load_image_sections_in_target); 1313 } 1314 } 1315 1316 if (exe_module_sp) 1317 { 1318 if (exe_module_sp.get() != m_process->GetTarget().GetExecutableModulePointer()) 1319 { 1320 // Don't load dependent images since we are in dyld where we will know 1321 // and find out about all images that are loaded 1322 const bool get_dependent_images = false; 1323 m_process->GetTarget().SetExecutableModule (exe_module_sp, 1324 get_dependent_images); 1325 } 1326 } 1327 } 1328 } 1329 1330 //---------------------------------------------------------------------- 1331 // On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch 1332 // functions written in hand-written assembly, and also have hand-written unwind 1333 // information in the eh_frame section. Normally we prefer analyzing the 1334 // assembly instructions of a curently executing frame to unwind from that frame -- 1335 // but on hand-written functions this profiling can fail. We should use the 1336 // eh_frame instructions for these functions all the time. 1337 // 1338 // As an aside, it would be better if the eh_frame entries had a flag (or were 1339 // extensible so they could have an Apple-specific flag) which indicates that 1340 // the instructions are asynchronous -- accurate at every instruction, instead 1341 // of our normal default assumption that they are not. 1342 //---------------------------------------------------------------------- 1343 1344 bool 1345 DynamicLoaderMacOSXDYLD::AlwaysRelyOnEHUnwindInfo (SymbolContext &sym_ctx) 1346 { 1347 ModuleSP module_sp; 1348 if (sym_ctx.symbol) 1349 { 1350 module_sp = sym_ctx.symbol->GetAddress().GetModule(); 1351 } 1352 if (module_sp.get() == NULL && sym_ctx.function) 1353 { 1354 module_sp = sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule(); 1355 } 1356 if (module_sp.get() == NULL) 1357 return false; 1358 1359 ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime(); 1360 if (objc_runtime != NULL && objc_runtime->IsModuleObjCLibrary (module_sp)) 1361 { 1362 return true; 1363 } 1364 1365 return false; 1366 } 1367 1368 1369 1370 //---------------------------------------------------------------------- 1371 // Dump a Segment to the file handle provided. 1372 //---------------------------------------------------------------------- 1373 void 1374 DynamicLoaderMacOSXDYLD::Segment::PutToLog (Log *log, lldb::addr_t slide) const 1375 { 1376 if (log) 1377 { 1378 if (slide == 0) 1379 log->Printf ("\t\t%16s [0x%16.16llx - 0x%16.16llx)", 1380 name.AsCString(""), 1381 vmaddr + slide, 1382 vmaddr + slide + vmsize); 1383 else 1384 log->Printf ("\t\t%16s [0x%16.16llx - 0x%16.16llx) slide = 0x%llx", 1385 name.AsCString(""), 1386 vmaddr + slide, 1387 vmaddr + slide + vmsize, 1388 slide); 1389 } 1390 } 1391 1392 const DynamicLoaderMacOSXDYLD::Segment * 1393 DynamicLoaderMacOSXDYLD::DYLDImageInfo::FindSegment (const ConstString &name) const 1394 { 1395 const size_t num_segments = segments.size(); 1396 for (size_t i=0; i<num_segments; ++i) 1397 { 1398 if (segments[i].name == name) 1399 return &segments[i]; 1400 } 1401 return NULL; 1402 } 1403 1404 1405 //---------------------------------------------------------------------- 1406 // Dump an image info structure to the file handle provided. 1407 //---------------------------------------------------------------------- 1408 void 1409 DynamicLoaderMacOSXDYLD::DYLDImageInfo::PutToLog (Log *log) const 1410 { 1411 if (log == NULL) 1412 return; 1413 uint8_t *u = (uint8_t *)uuid.GetBytes(); 1414 1415 if (address == LLDB_INVALID_ADDRESS) 1416 { 1417 if (u) 1418 { 1419 log->Printf("\t modtime=0x%8.8llx 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 path='%s/%s' (UNLOADED)", 1420 mod_date, 1421 u[ 0], u[ 1], u[ 2], u[ 3], 1422 u[ 4], u[ 5], u[ 6], u[ 7], 1423 u[ 8], u[ 9], u[10], u[11], 1424 u[12], u[13], u[14], u[15], 1425 file_spec.GetDirectory().AsCString(), 1426 file_spec.GetFilename().AsCString()); 1427 } 1428 else 1429 log->Printf("\t modtime=0x%8.8llx path='%s/%s' (UNLOADED)", 1430 mod_date, 1431 file_spec.GetDirectory().AsCString(), 1432 file_spec.GetFilename().AsCString()); 1433 } 1434 else 1435 { 1436 if (u) 1437 { 1438 log->Printf("\taddress=0x%16.16llx modtime=0x%8.8llx 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 path='%s/%s'", 1439 address, 1440 mod_date, 1441 u[ 0], u[ 1], u[ 2], u[ 3], 1442 u[ 4], u[ 5], u[ 6], u[ 7], 1443 u[ 8], u[ 9], u[10], u[11], 1444 u[12], u[13], u[14], u[15], 1445 file_spec.GetDirectory().AsCString(), 1446 file_spec.GetFilename().AsCString()); 1447 } 1448 else 1449 { 1450 log->Printf("\taddress=0x%16.16llx modtime=0x%8.8llx path='%s/%s'", 1451 address, 1452 mod_date, 1453 file_spec.GetDirectory().AsCString(), 1454 file_spec.GetFilename().AsCString()); 1455 1456 } 1457 for (uint32_t i=0; i<segments.size(); ++i) 1458 segments[i].PutToLog(log, slide); 1459 } 1460 } 1461 1462 //---------------------------------------------------------------------- 1463 // Dump the _dyld_all_image_infos members and all current image infos 1464 // that we have parsed to the file handle provided. 1465 //---------------------------------------------------------------------- 1466 void 1467 DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const 1468 { 1469 if (log == NULL) 1470 return; 1471 1472 Mutex::Locker locker(m_mutex); 1473 log->Printf("dyld_all_image_infos = { version=%d, count=%d, addr=0x%8.8llx, notify=0x%8.8llx }", 1474 m_dyld_all_image_infos.version, 1475 m_dyld_all_image_infos.dylib_info_count, 1476 (uint64_t)m_dyld_all_image_infos.dylib_info_addr, 1477 (uint64_t)m_dyld_all_image_infos.notification); 1478 size_t i; 1479 const size_t count = m_dyld_image_infos.size(); 1480 if (count > 0) 1481 { 1482 log->PutCString("Loaded:"); 1483 for (i = 0; i<count; i++) 1484 m_dyld_image_infos[i].PutToLog(log); 1485 } 1486 } 1487 1488 void 1489 DynamicLoaderMacOSXDYLD::PrivateInitialize(Process *process) 1490 { 1491 DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState())); 1492 Clear(true); 1493 m_process = process; 1494 m_process->GetTarget().GetSectionLoadList().Clear(); 1495 } 1496 1497 bool 1498 DynamicLoaderMacOSXDYLD::SetNotificationBreakpoint () 1499 { 1500 DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState())); 1501 if (m_break_id == LLDB_INVALID_BREAK_ID) 1502 { 1503 if (m_dyld_all_image_infos.notification != LLDB_INVALID_ADDRESS) 1504 { 1505 Address so_addr; 1506 // Set the notification breakpoint and install a breakpoint 1507 // callback function that will get called each time the 1508 // breakpoint gets hit. We will use this to track when shared 1509 // libraries get loaded/unloaded. 1510 1511 if (m_process->GetTarget().GetSectionLoadList().ResolveLoadAddress(m_dyld_all_image_infos.notification, so_addr)) 1512 { 1513 Breakpoint *dyld_break = m_process->GetTarget().CreateBreakpoint (so_addr, true).get(); 1514 dyld_break->SetCallback (DynamicLoaderMacOSXDYLD::NotifyBreakpointHit, this, true); 1515 m_break_id = dyld_break->GetID(); 1516 } 1517 } 1518 } 1519 return m_break_id != LLDB_INVALID_BREAK_ID; 1520 } 1521 1522 //---------------------------------------------------------------------- 1523 // Member function that gets called when the process state changes. 1524 //---------------------------------------------------------------------- 1525 void 1526 DynamicLoaderMacOSXDYLD::PrivateProcessStateChanged (Process *process, StateType state) 1527 { 1528 DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s(%s)\n", __FUNCTION__, StateAsCString(state)); 1529 switch (state) 1530 { 1531 case eStateConnected: 1532 case eStateAttaching: 1533 case eStateLaunching: 1534 case eStateInvalid: 1535 case eStateUnloaded: 1536 case eStateExited: 1537 case eStateDetached: 1538 Clear(false); 1539 break; 1540 1541 case eStateStopped: 1542 // Keep trying find dyld and set our notification breakpoint each time 1543 // we stop until we succeed 1544 if (!DidSetNotificationBreakpoint () && m_process->IsAlive()) 1545 { 1546 if (NeedToLocateDYLD ()) 1547 LocateDYLD (); 1548 1549 SetNotificationBreakpoint (); 1550 } 1551 break; 1552 1553 case eStateRunning: 1554 case eStateStepping: 1555 case eStateCrashed: 1556 case eStateSuspended: 1557 break; 1558 1559 default: 1560 break; 1561 } 1562 } 1563 1564 // This bit in the n_desc field of the mach file means that this is a 1565 // stub that runs arbitrary code to determine the trampoline target. 1566 // We've established a naming convention with the CoreOS folks for the 1567 // equivalent symbols they will use for this (which the objc guys didn't follow...) 1568 // For now we'll just look for all symbols matching that naming convention... 1569 1570 #define MACH_O_N_SYMBOL_RESOLVER 0x100 1571 1572 ThreadPlanSP 1573 DynamicLoaderMacOSXDYLD::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others) 1574 { 1575 ThreadPlanSP thread_plan_sp; 1576 StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get(); 1577 const SymbolContext ¤t_context = current_frame->GetSymbolContext(eSymbolContextSymbol); 1578 Symbol *current_symbol = current_context.symbol; 1579 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 1580 1581 if (current_symbol != NULL) 1582 { 1583 if (current_symbol->IsTrampoline()) 1584 { 1585 const ConstString &trampoline_name = current_symbol->GetMangled().GetName(Mangled::ePreferMangled); 1586 1587 if (trampoline_name) 1588 { 1589 SymbolContextList target_symbols; 1590 TargetSP target_sp (thread.CalculateTarget()); 1591 const ModuleList &images = target_sp->GetImages(); 1592 1593 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode, target_symbols); 1594 1595 size_t num_original_symbols = target_symbols.GetSize(); 1596 // FIXME: The resolver symbol is only valid in object files. In binaries it is reused for the 1597 // shared library slot number. So we'll have to look this up in the dyld info. 1598 // For now, just turn this off. 1599 1600 // bool orig_is_resolver = (current_symbol->GetFlags() & MACH_O_N_SYMBOL_RESOLVER) == MACH_O_N_SYMBOL_RESOLVER; 1601 // FIXME: Actually that isn't true, the N_SYMBOL_RESOLVER bit is only valid in .o files. You can't use 1602 // the symbol flags to tell whether something is a symbol resolver in a linked image. 1603 bool orig_is_resolver = false; 1604 1605 if (num_original_symbols > 0) 1606 { 1607 // We found symbols that look like they are the targets to our symbol. Now look through the 1608 // modules containing our symbols to see if there are any for our symbol. 1609 1610 ModuleList modules_to_search; 1611 1612 for (size_t i = 0; i < num_original_symbols; i++) 1613 { 1614 SymbolContext sc; 1615 target_symbols.GetContextAtIndex(i, sc); 1616 1617 ModuleSP module_sp (sc.symbol->CalculateSymbolContextModule()); 1618 if (module_sp) 1619 modules_to_search.AppendIfNeeded(module_sp); 1620 } 1621 1622 // If the original stub symbol is a resolver, then we don't want to break on the symbol with the 1623 // original name, but instead on all the symbols it could resolve to since otherwise we would stop 1624 // in the middle of the resolution... 1625 // Note that the stub is not of the resolver type it will point to the equivalent symbol, 1626 // not the original name, so in that case we don't need to do anything. 1627 1628 if (orig_is_resolver) 1629 { 1630 target_symbols.Clear(); 1631 1632 FindEquivalentSymbols (current_symbol, modules_to_search, target_symbols); 1633 } 1634 1635 // FIXME - Make the Run to Address take multiple addresses, and 1636 // run to any of them. 1637 uint32_t num_symbols = target_symbols.GetSize(); 1638 if (num_symbols > 0) 1639 { 1640 std::vector<lldb::addr_t> addresses; 1641 addresses.resize (num_symbols); 1642 for (uint32_t i = 0; i < num_symbols; i++) 1643 { 1644 SymbolContext context; 1645 AddressRange addr_range; 1646 if (target_symbols.GetContextAtIndex(i, context)) 1647 { 1648 context.GetAddressRange (eSymbolContextEverything, 0, false, addr_range); 1649 lldb::addr_t load_addr = addr_range.GetBaseAddress().GetLoadAddress(target_sp.get()); 1650 addresses[i] = load_addr; 1651 } 1652 } 1653 if (addresses.size() > 0) 1654 thread_plan_sp.reset (new ThreadPlanRunToAddress (thread, addresses, stop_others)); 1655 else 1656 { 1657 if (log) 1658 log->Printf ("Couldn't resolve the symbol contexts."); 1659 } 1660 } 1661 else 1662 { 1663 if (log) 1664 { 1665 log->Printf ("Found a resolver stub for: \"%s\" but could not find any symbols it resolves to.", 1666 trampoline_name.AsCString()); 1667 } 1668 } 1669 } 1670 else 1671 { 1672 if (log) 1673 { 1674 log->Printf ("Could not find symbol for trampoline target: \"%s\"", trampoline_name.AsCString()); 1675 } 1676 } 1677 } 1678 } 1679 } 1680 else 1681 { 1682 if (log) 1683 log->Printf ("Could not find symbol for step through."); 1684 } 1685 1686 return thread_plan_sp; 1687 } 1688 1689 size_t 1690 DynamicLoaderMacOSXDYLD::FindEquivalentSymbols (lldb_private::Symbol *original_symbol, 1691 lldb_private::ModuleList &images, 1692 lldb_private::SymbolContextList &equivalent_symbols) 1693 { 1694 const ConstString &trampoline_name = original_symbol->GetMangled().GetName(Mangled::ePreferMangled); 1695 if (!trampoline_name) 1696 return 0; 1697 1698 size_t initial_size = equivalent_symbols.GetSize(); 1699 1700 static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Z0-9]+)$"; 1701 std::string equivalent_regex_buf("^"); 1702 equivalent_regex_buf.append (trampoline_name.GetCString()); 1703 equivalent_regex_buf.append (resolver_name_regex); 1704 1705 RegularExpression equivalent_name_regex (equivalent_regex_buf.c_str()); 1706 const bool append = true; 1707 images.FindSymbolsMatchingRegExAndType (equivalent_name_regex, eSymbolTypeCode, equivalent_symbols, append); 1708 1709 return equivalent_symbols.GetSize() - initial_size; 1710 } 1711 1712 Error 1713 DynamicLoaderMacOSXDYLD::CanLoadImage () 1714 { 1715 Error error; 1716 // In order for us to tell if we can load a shared library we verify that 1717 // the dylib_info_addr isn't zero (which means no shared libraries have 1718 // been set yet, or dyld is currently mucking with the shared library list). 1719 if (ReadAllImageInfosStructure ()) 1720 { 1721 // TODO: also check the _dyld_global_lock_held variable in libSystem.B.dylib? 1722 // TODO: check the malloc lock? 1723 // TODO: check the objective C lock? 1724 if (m_dyld_all_image_infos.dylib_info_addr != 0) 1725 return error; // Success 1726 } 1727 1728 error.SetErrorString("unsafe to load or unload shared libraries"); 1729 return error; 1730 } 1731 1732 void 1733 DynamicLoaderMacOSXDYLD::Initialize() 1734 { 1735 PluginManager::RegisterPlugin (GetPluginNameStatic(), 1736 GetPluginDescriptionStatic(), 1737 CreateInstance); 1738 } 1739 1740 void 1741 DynamicLoaderMacOSXDYLD::Terminate() 1742 { 1743 PluginManager::UnregisterPlugin (CreateInstance); 1744 } 1745 1746 1747 const char * 1748 DynamicLoaderMacOSXDYLD::GetPluginNameStatic() 1749 { 1750 return "dynamic-loader.macosx-dyld"; 1751 } 1752 1753 const char * 1754 DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic() 1755 { 1756 return "Dynamic loader plug-in that watches for shared library loads/unloads in MacOSX user processes."; 1757 } 1758 1759 1760 //------------------------------------------------------------------ 1761 // PluginInterface protocol 1762 //------------------------------------------------------------------ 1763 const char * 1764 DynamicLoaderMacOSXDYLD::GetPluginName() 1765 { 1766 return "DynamicLoaderMacOSXDYLD"; 1767 } 1768 1769 const char * 1770 DynamicLoaderMacOSXDYLD::GetShortPluginName() 1771 { 1772 return GetPluginNameStatic(); 1773 } 1774 1775 uint32_t 1776 DynamicLoaderMacOSXDYLD::GetPluginVersion() 1777 { 1778 return 1; 1779 } 1780 1781 uint32_t 1782 DynamicLoaderMacOSXDYLD::AddrByteSize() 1783 { 1784 switch (m_dyld.header.magic) 1785 { 1786 case llvm::MachO::HeaderMagic32: 1787 case llvm::MachO::HeaderMagic32Swapped: 1788 return 4; 1789 1790 case llvm::MachO::HeaderMagic64: 1791 case llvm::MachO::HeaderMagic64Swapped: 1792 return 8; 1793 1794 default: 1795 break; 1796 } 1797 return 0; 1798 } 1799 1800 lldb::ByteOrder 1801 DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic (uint32_t magic) 1802 { 1803 switch (magic) 1804 { 1805 case llvm::MachO::HeaderMagic32: 1806 case llvm::MachO::HeaderMagic64: 1807 return lldb::endian::InlHostByteOrder(); 1808 1809 case llvm::MachO::HeaderMagic32Swapped: 1810 case llvm::MachO::HeaderMagic64Swapped: 1811 if (lldb::endian::InlHostByteOrder() == lldb::eByteOrderBig) 1812 return lldb::eByteOrderLittle; 1813 else 1814 return lldb::eByteOrderBig; 1815 1816 default: 1817 break; 1818 } 1819 return lldb::eByteOrderInvalid; 1820 } 1821 1822 lldb::ByteOrder 1823 DynamicLoaderMacOSXDYLD::DYLDImageInfo::GetByteOrder() 1824 { 1825 return DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header.magic); 1826 } 1827 1828