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