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/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/Symbol/ObjectFile.h" 20 #include "lldb/Target/Process.h" 21 #include "lldb/Target/Target.h" 22 #include "lldb/Target/Thread.h" 23 #include "lldb/Target/ThreadPlanRunToAddress.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 131 // and 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. 161 // DidLaunch uses ProbeEntry() instead. That sets a breakpoint, 162 // at the dyld breakpoint address, with a callback so that when hit, 163 // the dyld structure can be 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 207 // and find out about all images that are loaded 208 const bool get_dependent_images = false; 209 target.SetExecutableModule(executable, get_dependent_images); 210 } 211 212 return executable; 213 } 214 215 // AD: Needs to be updated? 216 Error DynamicLoaderHexagonDYLD::CanLoadImage() { return Error(); } 217 218 void DynamicLoaderHexagonDYLD::UpdateLoadedSections(ModuleSP module, 219 addr_t link_map_addr, 220 addr_t base_addr, 221 bool base_addr_is_offset) { 222 Target &target = m_process->GetTarget(); 223 const SectionList *sections = GetSectionListFromModule(module); 224 225 assert(sections && "SectionList missing from loaded module."); 226 227 m_loaded_modules[module] = link_map_addr; 228 229 const size_t num_sections = sections->GetSize(); 230 231 for (unsigned i = 0; i < num_sections; ++i) { 232 SectionSP section_sp(sections->GetSectionAtIndex(i)); 233 lldb::addr_t new_load_addr = section_sp->GetFileAddress() + base_addr; 234 235 // AD: 02/05/14 236 // since our memory map starts from address 0, we must not ignore 237 // sections that load to address 0. This violates the reference 238 // ELF spec, however is used for Hexagon. 239 240 // If the file address of the section is zero then this is not an 241 // allocatable/loadable section (property of ELF sh_addr). Skip it. 242 // if (new_load_addr == base_addr) 243 // continue; 244 245 target.SetSectionLoadAddress(section_sp, new_load_addr); 246 } 247 } 248 249 /// Removes the loaded sections from the target in @p module. 250 /// 251 /// @param module The module to traverse. 252 void DynamicLoaderHexagonDYLD::UnloadSections(const ModuleSP module) { 253 Target &target = m_process->GetTarget(); 254 const SectionList *sections = GetSectionListFromModule(module); 255 256 assert(sections && "SectionList missing from unloaded module."); 257 258 m_loaded_modules.erase(module); 259 260 const size_t num_sections = sections->GetSize(); 261 for (size_t i = 0; i < num_sections; ++i) { 262 SectionSP section_sp(sections->GetSectionAtIndex(i)); 263 target.SetSectionUnloaded(section_sp); 264 } 265 } 266 267 // Place a breakpoint on <_rtld_debug_state> 268 bool DynamicLoaderHexagonDYLD::SetRendezvousBreakpoint() { 269 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 270 271 // This is the original code, which want to look in the rendezvous structure 272 // to find the breakpoint address. Its backwards for us, since we can easily 273 // find the breakpoint address, since it is exported in our executable. 274 // We however know that we cant read the Rendezvous structure until we have 275 // hit 276 // the breakpoint once. 277 const ConstString dyldBpName("_rtld_debug_state"); 278 addr_t break_addr = findSymbolAddress(m_process, dyldBpName); 279 280 Target &target = m_process->GetTarget(); 281 282 // Do not try to set the breakpoint if we don't know where to put it 283 if (break_addr == LLDB_INVALID_ADDRESS) { 284 if (log) 285 log->Printf("Unable to locate _rtld_debug_state breakpoint address"); 286 287 return false; 288 } 289 290 // Save the address of the rendezvous structure 291 m_rendezvous.SetBreakAddress(break_addr); 292 293 // If we haven't set the breakpoint before then set it 294 if (m_dyld_bid == LLDB_INVALID_BREAK_ID) { 295 Breakpoint *dyld_break = 296 target.CreateBreakpoint(break_addr, true, false).get(); 297 dyld_break->SetCallback(RendezvousBreakpointHit, this, true); 298 dyld_break->SetBreakpointKind("shared-library-event"); 299 m_dyld_bid = dyld_break->GetID(); 300 301 // Make sure our breakpoint is at the right address. 302 assert(target.GetBreakpointByID(m_dyld_bid) 303 ->FindLocationByAddress(break_addr) 304 ->GetBreakpoint() 305 .GetID() == m_dyld_bid); 306 307 if (log && dyld_break == nullptr) 308 log->Printf("Failed to create _rtld_debug_state breakpoint"); 309 310 // check we have successfully set bp 311 return (dyld_break != nullptr); 312 } else 313 // rendezvous already set 314 return true; 315 } 316 317 // We have just hit our breakpoint at <_rtld_debug_state> 318 bool DynamicLoaderHexagonDYLD::RendezvousBreakpointHit( 319 void *baton, StoppointCallbackContext *context, user_id_t break_id, 320 user_id_t break_loc_id) { 321 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 322 323 if (log) 324 log->Printf("Rendezvous breakpoint hit!"); 325 326 DynamicLoaderHexagonDYLD *dyld_instance = nullptr; 327 dyld_instance = static_cast<DynamicLoaderHexagonDYLD *>(baton); 328 329 // if the dyld_instance is still not valid then 330 // try to locate it on the symbol table 331 if (!dyld_instance->m_rendezvous.IsValid()) { 332 Process *proc = dyld_instance->m_process; 333 334 const ConstString dyldStructName("_rtld_debug"); 335 addr_t structAddr = findSymbolAddress(proc, dyldStructName); 336 337 if (structAddr != LLDB_INVALID_ADDRESS) { 338 dyld_instance->m_rendezvous.SetRendezvousAddress(structAddr); 339 340 if (log) 341 log->Printf("Found _rtld_debug structure @ 0x%08" PRIx64, structAddr); 342 } else { 343 if (log) 344 log->Printf("Unable to resolve the _rtld_debug structure"); 345 } 346 } 347 348 dyld_instance->RefreshModules(); 349 350 // Return true to stop the target, false to just let the target run. 351 return dyld_instance->GetStopWhenImagesChange(); 352 } 353 354 /// Helper method for RendezvousBreakpointHit. Updates LLDB's current set 355 /// of loaded modules. 356 void DynamicLoaderHexagonDYLD::RefreshModules() { 357 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 358 359 if (!m_rendezvous.Resolve()) 360 return; 361 362 HexagonDYLDRendezvous::iterator I; 363 HexagonDYLDRendezvous::iterator E; 364 365 ModuleList &loaded_modules = m_process->GetTarget().GetImages(); 366 367 if (m_rendezvous.ModulesDidLoad()) { 368 ModuleList new_modules; 369 370 E = m_rendezvous.loaded_end(); 371 for (I = m_rendezvous.loaded_begin(); I != E; ++I) { 372 FileSpec file(I->path, true); 373 ModuleSP module_sp = 374 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true); 375 if (module_sp.get()) { 376 loaded_modules.AppendIfNeeded(module_sp); 377 new_modules.Append(module_sp); 378 } 379 380 if (log) { 381 log->Printf("Target is loading '%s'", I->path.c_str()); 382 if (!module_sp.get()) 383 log->Printf("LLDB failed to load '%s'", I->path.c_str()); 384 else 385 log->Printf("LLDB successfully loaded '%s'", I->path.c_str()); 386 } 387 } 388 m_process->GetTarget().ModulesDidLoad(new_modules); 389 } 390 391 if (m_rendezvous.ModulesDidUnload()) { 392 ModuleList old_modules; 393 394 E = m_rendezvous.unloaded_end(); 395 for (I = m_rendezvous.unloaded_begin(); I != E; ++I) { 396 FileSpec file(I->path, true); 397 ModuleSpec module_spec(file); 398 ModuleSP module_sp = loaded_modules.FindFirstModule(module_spec); 399 400 if (module_sp.get()) { 401 old_modules.Append(module_sp); 402 UnloadSections(module_sp); 403 } 404 405 if (log) 406 log->Printf("Target is unloading '%s'", I->path.c_str()); 407 } 408 loaded_modules.Remove(old_modules); 409 m_process->GetTarget().ModulesDidUnload(old_modules, false); 410 } 411 } 412 413 // AD: This is very different to the Static Loader code. 414 // It may be wise to look over this and its relation to stack 415 // unwinding. 416 ThreadPlanSP 417 DynamicLoaderHexagonDYLD::GetStepThroughTrampolinePlan(Thread &thread, 418 bool stop) { 419 ThreadPlanSP thread_plan_sp; 420 421 StackFrame *frame = thread.GetStackFrameAtIndex(0).get(); 422 const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol); 423 Symbol *sym = context.symbol; 424 425 if (sym == NULL || !sym->IsTrampoline()) 426 return thread_plan_sp; 427 428 const ConstString sym_name = sym->GetMangled().GetName( 429 lldb::eLanguageTypeUnknown, Mangled::ePreferMangled); 430 if (!sym_name) 431 return thread_plan_sp; 432 433 SymbolContextList target_symbols; 434 Target &target = thread.GetProcess()->GetTarget(); 435 const ModuleList &images = target.GetImages(); 436 437 images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols); 438 size_t num_targets = target_symbols.GetSize(); 439 if (!num_targets) 440 return thread_plan_sp; 441 442 typedef std::vector<lldb::addr_t> AddressVector; 443 AddressVector addrs; 444 for (size_t i = 0; i < num_targets; ++i) { 445 SymbolContext context; 446 AddressRange range; 447 if (target_symbols.GetContextAtIndex(i, context)) { 448 context.GetAddressRange(eSymbolContextEverything, 0, false, range); 449 lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target); 450 if (addr != LLDB_INVALID_ADDRESS) 451 addrs.push_back(addr); 452 } 453 } 454 455 if (addrs.size() > 0) { 456 AddressVector::iterator start = addrs.begin(); 457 AddressVector::iterator end = addrs.end(); 458 459 std::sort(start, end); 460 addrs.erase(std::unique(start, end), end); 461 thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop)); 462 } 463 464 return thread_plan_sp; 465 } 466 467 /// Helper for the entry breakpoint callback. Resolves the load addresses 468 /// of all dependent modules. 469 void DynamicLoaderHexagonDYLD::LoadAllCurrentModules() { 470 HexagonDYLDRendezvous::iterator I; 471 HexagonDYLDRendezvous::iterator E; 472 ModuleList module_list; 473 474 if (!m_rendezvous.Resolve()) { 475 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 476 if (log) 477 log->Printf( 478 "DynamicLoaderHexagonDYLD::%s unable to resolve rendezvous address", 479 __FUNCTION__); 480 return; 481 } 482 483 // The rendezvous class doesn't enumerate the main module, so track 484 // that ourselves here. 485 ModuleSP executable = GetTargetExecutable(); 486 m_loaded_modules[executable] = m_rendezvous.GetLinkMapAddress(); 487 488 for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I) { 489 const char *module_path = I->path.c_str(); 490 FileSpec file(module_path, false); 491 ModuleSP module_sp = 492 LoadModuleAtAddress(file, I->link_addr, I->base_addr, true); 493 if (module_sp.get()) { 494 module_list.Append(module_sp); 495 } else { 496 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 497 if (log) 498 log->Printf("DynamicLoaderHexagonDYLD::%s failed loading module %s at " 499 "0x%" PRIx64, 500 __FUNCTION__, module_path, I->base_addr); 501 } 502 } 503 504 m_process->GetTarget().ModulesDidLoad(module_list); 505 } 506 507 /// Computes a value for m_load_offset returning the computed address on 508 /// success and LLDB_INVALID_ADDRESS on failure. 509 addr_t DynamicLoaderHexagonDYLD::ComputeLoadOffset() { 510 // Here we could send a GDB packet to know the load offset 511 // 512 // send: $qOffsets#4b 513 // get: Text=0;Data=0;Bss=0 514 // 515 // Currently qOffsets is not supported by pluginProcessGDBRemote 516 // 517 return 0; 518 } 519 520 // Here we must try to read the entry point directly from 521 // the elf header. This is possible if the process is not 522 // relocatable or dynamically linked. 523 // 524 // an alternative is to look at the PC if we can be sure 525 // that we have connected when the process is at the entry point. 526 // I dont think that is reliable for us. 527 addr_t DynamicLoaderHexagonDYLD::GetEntryPoint() { 528 if (m_entry_point != LLDB_INVALID_ADDRESS) 529 return m_entry_point; 530 // check we have a valid process 531 if (m_process == nullptr) 532 return LLDB_INVALID_ADDRESS; 533 // Get the current executable module 534 Module &module = *(m_process->GetTarget().GetExecutableModule().get()); 535 // Get the object file (elf file) for this module 536 lldb_private::ObjectFile &object = *(module.GetObjectFile()); 537 // Check if the file is executable (ie, not shared object or relocatable) 538 if (object.IsExecutable()) { 539 // Get the entry point address for this object 540 lldb_private::Address entry = object.GetEntryPointAddress(); 541 // Return the entry point address 542 return entry.GetFileAddress(); 543 } 544 // No idea so back out 545 return LLDB_INVALID_ADDRESS; 546 } 547 548 const SectionList *DynamicLoaderHexagonDYLD::GetSectionListFromModule( 549 const ModuleSP module) const { 550 SectionList *sections = nullptr; 551 if (module.get()) { 552 ObjectFile *obj_file = module->GetObjectFile(); 553 if (obj_file) { 554 sections = obj_file->GetSectionList(); 555 } 556 } 557 return sections; 558 } 559 560 static int ReadInt(Process *process, addr_t addr) { 561 Error error; 562 int value = (int)process->ReadUnsignedIntegerFromMemory( 563 addr, sizeof(uint32_t), 0, error); 564 if (error.Fail()) 565 return -1; 566 else 567 return value; 568 } 569 570 lldb::addr_t 571 DynamicLoaderHexagonDYLD::GetThreadLocalData(const lldb::ModuleSP module, 572 const lldb::ThreadSP thread, 573 lldb::addr_t tls_file_addr) { 574 auto it = m_loaded_modules.find(module); 575 if (it == m_loaded_modules.end()) 576 return LLDB_INVALID_ADDRESS; 577 578 addr_t link_map = it->second; 579 if (link_map == LLDB_INVALID_ADDRESS) 580 return LLDB_INVALID_ADDRESS; 581 582 const HexagonDYLDRendezvous::ThreadInfo &metadata = 583 m_rendezvous.GetThreadInfo(); 584 if (!metadata.valid) 585 return LLDB_INVALID_ADDRESS; 586 587 // Get the thread pointer. 588 addr_t tp = thread->GetThreadPointer(); 589 if (tp == LLDB_INVALID_ADDRESS) 590 return LLDB_INVALID_ADDRESS; 591 592 // Find the module's modid. 593 int modid = ReadInt(m_process, link_map + metadata.modid_offset); 594 if (modid == -1) 595 return LLDB_INVALID_ADDRESS; 596 597 // Lookup the DTV structure for this thread. 598 addr_t dtv_ptr = tp + metadata.dtv_offset; 599 addr_t dtv = ReadPointer(dtv_ptr); 600 if (dtv == LLDB_INVALID_ADDRESS) 601 return LLDB_INVALID_ADDRESS; 602 603 // Find the TLS block for this module. 604 addr_t dtv_slot = dtv + metadata.dtv_slot_size * modid; 605 addr_t tls_block = ReadPointer(dtv_slot + metadata.tls_offset); 606 607 Module *mod = module.get(); 608 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 609 if (log) 610 log->Printf("DynamicLoaderHexagonDYLD::Performed TLS lookup: " 611 "module=%s, link_map=0x%" PRIx64 ", tp=0x%" PRIx64 612 ", modid=%i, tls_block=0x%" PRIx64, 613 mod->GetObjectName().AsCString(""), link_map, tp, modid, 614 tls_block); 615 616 if (tls_block == LLDB_INVALID_ADDRESS) 617 return LLDB_INVALID_ADDRESS; 618 else 619 return tls_block + tls_file_addr; 620 } 621