1 //===-- DynamicLoaderHexagonDYLD.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 // C Includes 11 // C++ Includes 12 // Other libraries and framework includes 13 #include "lldb/Breakpoint/BreakpointLocation.h" 14 #include "lldb/Core/Module.h" 15 #include "lldb/Core/ModuleSpec.h" 16 #include "lldb/Core/PluginManager.h" 17 #include "lldb/Core/Section.h" 18 #include "lldb/Symbol/ObjectFile.h" 19 #include "lldb/Target/Process.h" 20 #include "lldb/Target/Target.h" 21 #include "lldb/Target/Thread.h" 22 #include "lldb/Target/ThreadPlanRunToAddress.h" 23 #include "lldb/Utility/Log.h" 24 25 #include "DynamicLoaderHexagonDYLD.h" 26 27 using namespace lldb; 28 using namespace lldb_private; 29 30 // Aidan 21/05/2014 31 // 32 // Notes about hexagon dynamic loading: 33 // 34 // When we connect to a target we find the dyld breakpoint address. We put 35 // a 36 // breakpoint there with a callback 'RendezvousBreakpointHit()'. 37 // 38 // It is possible to find the dyld structure address from the ELF symbol 39 // table, 40 // but in the case of the simulator it has not been initialized before the 41 // target calls dlinit(). 42 // 43 // We can only safely parse the dyld structure after we hit the dyld 44 // breakpoint 45 // since at that time we know dlinit() must have been called. 46 // 47 48 // Find the load address of a symbol 49 static lldb::addr_t findSymbolAddress(Process *proc, ConstString findName) { 50 assert(proc != nullptr); 51 52 ModuleSP module = proc->GetTarget().GetExecutableModule(); 53 assert(module.get() != nullptr); 54 55 ObjectFile *exe = module->GetObjectFile(); 56 assert(exe != nullptr); 57 58 lldb_private::Symtab *symtab = exe->GetSymtab(); 59 assert(symtab != nullptr); 60 61 for (size_t i = 0; i < symtab->GetNumSymbols(); i++) { 62 const Symbol *sym = symtab->SymbolAtIndex(i); 63 assert(sym != nullptr); 64 const ConstString &symName = sym->GetName(); 65 66 if (ConstString::Compare(findName, symName) == 0) { 67 Address addr = sym->GetAddress(); 68 return addr.GetLoadAddress(&proc->GetTarget()); 69 } 70 } 71 return LLDB_INVALID_ADDRESS; 72 } 73 74 void DynamicLoaderHexagonDYLD::Initialize() { 75 PluginManager::RegisterPlugin(GetPluginNameStatic(), 76 GetPluginDescriptionStatic(), CreateInstance); 77 } 78 79 void DynamicLoaderHexagonDYLD::Terminate() {} 80 81 lldb_private::ConstString DynamicLoaderHexagonDYLD::GetPluginName() { 82 return GetPluginNameStatic(); 83 } 84 85 lldb_private::ConstString DynamicLoaderHexagonDYLD::GetPluginNameStatic() { 86 static ConstString g_name("hexagon-dyld"); 87 return g_name; 88 } 89 90 const char *DynamicLoaderHexagonDYLD::GetPluginDescriptionStatic() { 91 return "Dynamic loader plug-in that watches for shared library " 92 "loads/unloads in Hexagon processes."; 93 } 94 95 uint32_t DynamicLoaderHexagonDYLD::GetPluginVersion() { return 1; } 96 97 DynamicLoader *DynamicLoaderHexagonDYLD::CreateInstance(Process *process, 98 bool force) { 99 bool create = force; 100 if (!create) { 101 const llvm::Triple &triple_ref = 102 process->GetTarget().GetArchitecture().GetTriple(); 103 if (triple_ref.getArch() == llvm::Triple::hexagon) 104 create = true; 105 } 106 107 if (create) 108 return new DynamicLoaderHexagonDYLD(process); 109 return NULL; 110 } 111 112 DynamicLoaderHexagonDYLD::DynamicLoaderHexagonDYLD(Process *process) 113 : DynamicLoader(process), m_rendezvous(process), 114 m_load_offset(LLDB_INVALID_ADDRESS), m_entry_point(LLDB_INVALID_ADDRESS), 115 m_dyld_bid(LLDB_INVALID_BREAK_ID) {} 116 117 DynamicLoaderHexagonDYLD::~DynamicLoaderHexagonDYLD() { 118 if (m_dyld_bid != LLDB_INVALID_BREAK_ID) { 119 m_process->GetTarget().RemoveBreakpointByID(m_dyld_bid); 120 m_dyld_bid = LLDB_INVALID_BREAK_ID; 121 } 122 } 123 124 void DynamicLoaderHexagonDYLD::DidAttach() { 125 ModuleSP executable; 126 addr_t load_offset; 127 128 executable = GetTargetExecutable(); 129 130 // Find the difference between the desired load address in the elf file and 131 // the real load address in memory 132 load_offset = ComputeLoadOffset(); 133 134 // Check that there is a valid executable 135 if (executable.get() == nullptr) 136 return; 137 138 // Disable JIT for hexagon targets because its not supported 139 m_process->SetCanJIT(false); 140 141 // Enable Interpreting of function call expressions 142 m_process->SetCanInterpretFunctionCalls(true); 143 144 // Add the current executable to the module list 145 ModuleList module_list; 146 module_list.Append(executable); 147 148 // Map the loaded sections of this executable 149 if (load_offset != LLDB_INVALID_ADDRESS) 150 UpdateLoadedSections(executable, LLDB_INVALID_ADDRESS, load_offset, true); 151 152 // AD: confirm this? 153 // Load into LLDB all of the currently loaded executables in the stub 154 LoadAllCurrentModules(); 155 156 // AD: confirm this? 157 // Callback for the target to give it the loaded module list 158 m_process->GetTarget().ModulesDidLoad(module_list); 159 160 // Try to set a breakpoint at the rendezvous breakpoint. DidLaunch uses 161 // ProbeEntry() instead. That sets a breakpoint, at the dyld breakpoint 162 // address, with a callback so that when hit, the dyld structure can be 163 // parsed. 164 if (!SetRendezvousBreakpoint()) { 165 // fail 166 } 167 } 168 169 void DynamicLoaderHexagonDYLD::DidLaunch() {} 170 171 /// Checks to see if the target module has changed, updates the target 172 /// accordingly and returns the target executable module. 173 ModuleSP DynamicLoaderHexagonDYLD::GetTargetExecutable() { 174 Target &target = m_process->GetTarget(); 175 ModuleSP executable = target.GetExecutableModule(); 176 177 // There is no executable 178 if (!executable.get()) 179 return executable; 180 181 // The target executable file does not exits 182 if (!executable->GetFileSpec().Exists()) 183 return executable; 184 185 // Prep module for loading 186 ModuleSpec module_spec(executable->GetFileSpec(), 187 executable->GetArchitecture()); 188 ModuleSP module_sp(new Module(module_spec)); 189 190 // Check if the executable has changed and set it to the target executable if 191 // they differ. 192 if (module_sp.get() && module_sp->GetUUID().IsValid() && 193 executable->GetUUID().IsValid()) { 194 // if the executable has changed ?? 195 if (module_sp->GetUUID() != executable->GetUUID()) 196 executable.reset(); 197 } else if (executable->FileHasChanged()) 198 executable.reset(); 199 200 if (executable.get()) 201 return executable; 202 203 // TODO: What case is this code used? 204 executable = target.GetSharedModule(module_spec); 205 if (executable.get() != target.GetExecutableModulePointer()) { 206 // Don't load dependent images since we are in dyld where we will know and 207 // find out about all images that are loaded 208 target.SetExecutableModule(executable, eLoadDependentsNo); 209 } 210 211 return executable; 212 } 213 214 // AD: Needs to be updated? 215 Status DynamicLoaderHexagonDYLD::CanLoadImage() { return Status(); } 216 217 void DynamicLoaderHexagonDYLD::UpdateLoadedSections(ModuleSP module, 218 addr_t link_map_addr, 219 addr_t base_addr, 220 bool base_addr_is_offset) { 221 Target &target = m_process->GetTarget(); 222 const SectionList *sections = GetSectionListFromModule(module); 223 224 assert(sections && "SectionList missing from loaded module."); 225 226 m_loaded_modules[module] = link_map_addr; 227 228 const size_t num_sections = sections->GetSize(); 229 230 for (unsigned i = 0; i < num_sections; ++i) { 231 SectionSP section_sp(sections->GetSectionAtIndex(i)); 232 lldb::addr_t new_load_addr = section_sp->GetFileAddress() + base_addr; 233 234 // AD: 02/05/14 235 // since our memory map starts from address 0, we must not ignore 236 // sections that load to address 0. This violates the reference 237 // ELF spec, however is used for Hexagon. 238 239 // If the file address of the section is zero then this is not an 240 // allocatable/loadable section (property of ELF sh_addr). Skip it. 241 // if (new_load_addr == base_addr) 242 // continue; 243 244 target.SetSectionLoadAddress(section_sp, new_load_addr); 245 } 246 } 247 248 /// Removes the loaded sections from the target in @p module. 249 /// 250 /// @param module The module to traverse. 251 void DynamicLoaderHexagonDYLD::UnloadSections(const ModuleSP module) { 252 Target &target = m_process->GetTarget(); 253 const SectionList *sections = GetSectionListFromModule(module); 254 255 assert(sections && "SectionList missing from unloaded module."); 256 257 m_loaded_modules.erase(module); 258 259 const size_t num_sections = sections->GetSize(); 260 for (size_t i = 0; i < num_sections; ++i) { 261 SectionSP section_sp(sections->GetSectionAtIndex(i)); 262 target.SetSectionUnloaded(section_sp); 263 } 264 } 265 266 // Place a breakpoint on <_rtld_debug_state> 267 bool DynamicLoaderHexagonDYLD::SetRendezvousBreakpoint() { 268 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 269 270 // This is the original code, which want to look in the rendezvous structure 271 // to find the breakpoint address. Its backwards for us, since we can easily 272 // find the breakpoint address, since it is exported in our executable. We 273 // however know that we cant read the Rendezvous structure until we have hit 274 // the breakpoint once. 275 const ConstString dyldBpName("_rtld_debug_state"); 276 addr_t break_addr = findSymbolAddress(m_process, dyldBpName); 277 278 Target &target = m_process->GetTarget(); 279 280 // Do not try to set the breakpoint if we don't know where to put it 281 if (break_addr == LLDB_INVALID_ADDRESS) { 282 if (log) 283 log->Printf("Unable to locate _rtld_debug_state breakpoint address"); 284 285 return false; 286 } 287 288 // Save the address of the rendezvous structure 289 m_rendezvous.SetBreakAddress(break_addr); 290 291 // If we haven't set the breakpoint before then set it 292 if (m_dyld_bid == LLDB_INVALID_BREAK_ID) { 293 Breakpoint *dyld_break = 294 target.CreateBreakpoint(break_addr, true, false).get(); 295 dyld_break->SetCallback(RendezvousBreakpointHit, this, true); 296 dyld_break->SetBreakpointKind("shared-library-event"); 297 m_dyld_bid = dyld_break->GetID(); 298 299 // Make sure our breakpoint is at the right address. 300 assert(target.GetBreakpointByID(m_dyld_bid) 301 ->FindLocationByAddress(break_addr) 302 ->GetBreakpoint() 303 .GetID() == m_dyld_bid); 304 305 if (log && dyld_break == nullptr) 306 log->Printf("Failed to create _rtld_debug_state breakpoint"); 307 308 // check we have successfully set bp 309 return (dyld_break != nullptr); 310 } else 311 // rendezvous already set 312 return true; 313 } 314 315 // We have just hit our breakpoint at <_rtld_debug_state> 316 bool DynamicLoaderHexagonDYLD::RendezvousBreakpointHit( 317 void *baton, StoppointCallbackContext *context, user_id_t break_id, 318 user_id_t break_loc_id) { 319 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 320 321 if (log) 322 log->Printf("Rendezvous breakpoint hit!"); 323 324 DynamicLoaderHexagonDYLD *dyld_instance = nullptr; 325 dyld_instance = static_cast<DynamicLoaderHexagonDYLD *>(baton); 326 327 // if the dyld_instance is still not valid then try to locate it on the 328 // symbol table 329 if (!dyld_instance->m_rendezvous.IsValid()) { 330 Process *proc = dyld_instance->m_process; 331 332 const ConstString dyldStructName("_rtld_debug"); 333 addr_t structAddr = findSymbolAddress(proc, dyldStructName); 334 335 if (structAddr != LLDB_INVALID_ADDRESS) { 336 dyld_instance->m_rendezvous.SetRendezvousAddress(structAddr); 337 338 if (log) 339 log->Printf("Found _rtld_debug structure @ 0x%08" PRIx64, structAddr); 340 } else { 341 if (log) 342 log->Printf("Unable to resolve the _rtld_debug structure"); 343 } 344 } 345 346 dyld_instance->RefreshModules(); 347 348 // Return true to stop the target, false to just let the target run. 349 return dyld_instance->GetStopWhenImagesChange(); 350 } 351 352 /// Helper method for RendezvousBreakpointHit. Updates LLDB's current set 353 /// of loaded modules. 354 void DynamicLoaderHexagonDYLD::RefreshModules() { 355 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 356 357 if (!m_rendezvous.Resolve()) 358 return; 359 360 HexagonDYLDRendezvous::iterator I; 361 HexagonDYLDRendezvous::iterator E; 362 363 ModuleList &loaded_modules = m_process->GetTarget().GetImages(); 364 365 if (m_rendezvous.ModulesDidLoad()) { 366 ModuleList new_modules; 367 368 E = m_rendezvous.loaded_end(); 369 for (I = m_rendezvous.loaded_begin(); I != E; ++I) { 370 FileSpec file(I->path, true); 371 ModuleSP module_sp = 372 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true); 373 if (module_sp.get()) { 374 loaded_modules.AppendIfNeeded(module_sp); 375 new_modules.Append(module_sp); 376 } 377 378 if (log) { 379 log->Printf("Target is loading '%s'", I->path.c_str()); 380 if (!module_sp.get()) 381 log->Printf("LLDB failed to load '%s'", I->path.c_str()); 382 else 383 log->Printf("LLDB successfully loaded '%s'", I->path.c_str()); 384 } 385 } 386 m_process->GetTarget().ModulesDidLoad(new_modules); 387 } 388 389 if (m_rendezvous.ModulesDidUnload()) { 390 ModuleList old_modules; 391 392 E = m_rendezvous.unloaded_end(); 393 for (I = m_rendezvous.unloaded_begin(); I != E; ++I) { 394 FileSpec file(I->path, true); 395 ModuleSpec module_spec(file); 396 ModuleSP module_sp = loaded_modules.FindFirstModule(module_spec); 397 398 if (module_sp.get()) { 399 old_modules.Append(module_sp); 400 UnloadSections(module_sp); 401 } 402 403 if (log) 404 log->Printf("Target is unloading '%s'", I->path.c_str()); 405 } 406 loaded_modules.Remove(old_modules); 407 m_process->GetTarget().ModulesDidUnload(old_modules, false); 408 } 409 } 410 411 // AD: This is very different to the Static Loader code. 412 // It may be wise to look over this and its relation to stack 413 // unwinding. 414 ThreadPlanSP 415 DynamicLoaderHexagonDYLD::GetStepThroughTrampolinePlan(Thread &thread, 416 bool stop) { 417 ThreadPlanSP thread_plan_sp; 418 419 StackFrame *frame = thread.GetStackFrameAtIndex(0).get(); 420 const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol); 421 Symbol *sym = context.symbol; 422 423 if (sym == NULL || !sym->IsTrampoline()) 424 return thread_plan_sp; 425 426 const ConstString sym_name = sym->GetMangled().GetName( 427 lldb::eLanguageTypeUnknown, Mangled::ePreferMangled); 428 if (!sym_name) 429 return thread_plan_sp; 430 431 SymbolContextList target_symbols; 432 Target &target = thread.GetProcess()->GetTarget(); 433 const ModuleList &images = target.GetImages(); 434 435 images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols); 436 size_t num_targets = target_symbols.GetSize(); 437 if (!num_targets) 438 return thread_plan_sp; 439 440 typedef std::vector<lldb::addr_t> AddressVector; 441 AddressVector addrs; 442 for (size_t i = 0; i < num_targets; ++i) { 443 SymbolContext context; 444 AddressRange range; 445 if (target_symbols.GetContextAtIndex(i, context)) { 446 context.GetAddressRange(eSymbolContextEverything, 0, false, range); 447 lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target); 448 if (addr != LLDB_INVALID_ADDRESS) 449 addrs.push_back(addr); 450 } 451 } 452 453 if (addrs.size() > 0) { 454 AddressVector::iterator start = addrs.begin(); 455 AddressVector::iterator end = addrs.end(); 456 457 std::sort(start, end); 458 addrs.erase(std::unique(start, end), end); 459 thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop)); 460 } 461 462 return thread_plan_sp; 463 } 464 465 /// Helper for the entry breakpoint callback. Resolves the load addresses 466 /// of all dependent modules. 467 void DynamicLoaderHexagonDYLD::LoadAllCurrentModules() { 468 HexagonDYLDRendezvous::iterator I; 469 HexagonDYLDRendezvous::iterator E; 470 ModuleList module_list; 471 472 if (!m_rendezvous.Resolve()) { 473 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 474 if (log) 475 log->Printf( 476 "DynamicLoaderHexagonDYLD::%s unable to resolve rendezvous address", 477 __FUNCTION__); 478 return; 479 } 480 481 // The rendezvous class doesn't enumerate the main module, so track that 482 // ourselves here. 483 ModuleSP executable = GetTargetExecutable(); 484 m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress(); 485 486 for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I) { 487 const char *module_path = I->path.c_str(); 488 FileSpec file(module_path, false); 489 ModuleSP module_sp = 490 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true); 491 if (module_sp.get()) { 492 module_list.Append(module_sp); 493 } else { 494 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 495 if (log) 496 log->Printf("DynamicLoaderHexagonDYLD::%s failed loading module %s at " 497 "0x%" PRIx64, 498 __FUNCTION__, module_path, I->base_addr); 499 } 500 } 501 502 m_process->GetTarget().ModulesDidLoad(module_list); 503 } 504 505 /// Computes a value for m_load_offset returning the computed address on 506 /// success and LLDB_INVALID_ADDRESS on failure. 507 addr_t DynamicLoaderHexagonDYLD::ComputeLoadOffset() { 508 // Here we could send a GDB packet to know the load offset 509 // 510 // send: $qOffsets#4b 511 // get: Text=0;Data=0;Bss=0 512 // 513 // Currently qOffsets is not supported by pluginProcessGDBRemote 514 // 515 return 0; 516 } 517 518 // Here we must try to read the entry point directly from the elf header. This 519 // is possible if the process is not relocatable or dynamically linked. 520 // 521 // an alternative is to look at the PC if we can be sure that we have connected 522 // when the process is at the entry point. 523 // I dont think that is reliable for us. 524 addr_t DynamicLoaderHexagonDYLD::GetEntryPoint() { 525 if (m_entry_point != LLDB_INVALID_ADDRESS) 526 return m_entry_point; 527 // check we have a valid process 528 if (m_process == nullptr) 529 return LLDB_INVALID_ADDRESS; 530 // Get the current executable module 531 Module &module = *(m_process->GetTarget().GetExecutableModule().get()); 532 // Get the object file (elf file) for this module 533 lldb_private::ObjectFile &object = *(module.GetObjectFile()); 534 // Check if the file is executable (ie, not shared object or relocatable) 535 if (object.IsExecutable()) { 536 // Get the entry point address for this object 537 lldb_private::Address entry = object.GetEntryPointAddress(); 538 // Return the entry point address 539 return entry.GetFileAddress(); 540 } 541 // No idea so back out 542 return LLDB_INVALID_ADDRESS; 543 } 544 545 const SectionList *DynamicLoaderHexagonDYLD::GetSectionListFromModule( 546 const ModuleSP module) const { 547 SectionList *sections = nullptr; 548 if (module.get()) { 549 ObjectFile *obj_file = module->GetObjectFile(); 550 if (obj_file) { 551 sections = obj_file->GetSectionList(); 552 } 553 } 554 return sections; 555 } 556 557 static int ReadInt(Process *process, addr_t addr) { 558 Status error; 559 int value = (int)process->ReadUnsignedIntegerFromMemory( 560 addr, sizeof(uint32_t), 0, error); 561 if (error.Fail()) 562 return -1; 563 else 564 return value; 565 } 566 567 lldb::addr_t 568 DynamicLoaderHexagonDYLD::GetThreadLocalData(const lldb::ModuleSP module, 569 const lldb::ThreadSP thread, 570 lldb::addr_t tls_file_addr) { 571 auto it = m_loaded_modules.find(module); 572 if (it == m_loaded_modules.end()) 573 return LLDB_INVALID_ADDRESS; 574 575 addr_t link_map = it->second; 576 if (link_map == LLDB_INVALID_ADDRESS) 577 return LLDB_INVALID_ADDRESS; 578 579 const HexagonDYLDRendezvous::ThreadInfo &metadata = 580 m_rendezvous.GetThreadInfo(); 581 if (!metadata.valid) 582 return LLDB_INVALID_ADDRESS; 583 584 // Get the thread pointer. 585 addr_t tp = thread->GetThreadPointer(); 586 if (tp == LLDB_INVALID_ADDRESS) 587 return LLDB_INVALID_ADDRESS; 588 589 // Find the module's modid. 590 int modid = ReadInt(m_process, link_map + metadata.modid_offset); 591 if (modid == -1) 592 return LLDB_INVALID_ADDRESS; 593 594 // Lookup the DTV structure for this thread. 595 addr_t dtv_ptr = tp + metadata.dtv_offset; 596 addr_t dtv = ReadPointer(dtv_ptr); 597 if (dtv == LLDB_INVALID_ADDRESS) 598 return LLDB_INVALID_ADDRESS; 599 600 // Find the TLS block for this module. 601 addr_t dtv_slot = dtv + metadata.dtv_slot_size * modid; 602 addr_t tls_block = ReadPointer(dtv_slot + metadata.tls_offset); 603 604 Module *mod = module.get(); 605 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 606 if (log) 607 log->Printf("DynamicLoaderHexagonDYLD::Performed TLS lookup: " 608 "module=%s, link_map=0x%" PRIx64 ", tp=0x%" PRIx64 609 ", modid=%i, tls_block=0x%" PRIx64, 610 mod->GetObjectName().AsCString(""), link_map, tp, modid, 611 tls_block); 612 613 if (tls_block == LLDB_INVALID_ADDRESS) 614 return LLDB_INVALID_ADDRESS; 615 else 616 return tls_block + tls_file_addr; 617 } 618