1 //===-- Module.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/Core/Module.h" 11 12 // C Includes 13 // C++ Includes 14 // Other libraries and framework includes 15 #include "llvm/Support/Signals.h" 16 #include "llvm/Support/raw_os_ostream.h" 17 18 // Project includes 19 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" 20 #include "Plugins/Language/ObjC/ObjCLanguage.h" 21 #include "lldb/Core/AddressResolverFileLine.h" 22 #include "lldb/Core/DataBuffer.h" 23 #include "lldb/Core/DataBufferHeap.h" 24 #include "lldb/Core/Error.h" 25 #include "lldb/Core/Log.h" 26 #include "lldb/Core/ModuleList.h" 27 #include "lldb/Core/ModuleSpec.h" 28 #include "lldb/Core/PluginManager.h" 29 #include "lldb/Core/RegularExpression.h" 30 #include "lldb/Core/Section.h" 31 #include "lldb/Core/StreamString.h" 32 #include "lldb/Core/Timer.h" 33 #include "lldb/Host/FileSystem.h" 34 #include "lldb/Host/Host.h" 35 #include "lldb/Host/Symbols.h" 36 #include "lldb/Interpreter/CommandInterpreter.h" 37 #include "lldb/Interpreter/ScriptInterpreter.h" 38 #include "lldb/Symbol/CompileUnit.h" 39 #include "lldb/Symbol/ObjectFile.h" 40 #include "lldb/Symbol/SymbolContext.h" 41 #include "lldb/Symbol/SymbolFile.h" 42 #include "lldb/Symbol/SymbolVendor.h" 43 #include "lldb/Symbol/TypeMap.h" 44 #include "lldb/Symbol/TypeSystem.h" 45 #include "lldb/Target/Language.h" 46 #include "lldb/Target/Process.h" 47 #include "lldb/Target/SectionLoadList.h" 48 #include "lldb/Target/Target.h" 49 50 #include "Plugins/ObjectFile/JIT/ObjectFileJIT.h" 51 52 using namespace lldb; 53 using namespace lldb_private; 54 55 // Shared pointers to modules track module lifetimes in 56 // targets and in the global module, but this collection 57 // will track all module objects that are still alive 58 typedef std::vector<Module *> ModuleCollection; 59 60 static ModuleCollection &GetModuleCollection() { 61 // This module collection needs to live past any module, so we could either 62 // make it a 63 // shared pointer in each module or just leak is. Since it is only an empty 64 // vector by 65 // the time all the modules have gone away, we just leak it for now. If we 66 // decide this 67 // is a big problem we can introduce a Finalize method that will tear 68 // everything down in 69 // a predictable order. 70 71 static ModuleCollection *g_module_collection = nullptr; 72 if (g_module_collection == nullptr) 73 g_module_collection = new ModuleCollection(); 74 75 return *g_module_collection; 76 } 77 78 std::recursive_mutex &Module::GetAllocationModuleCollectionMutex() { 79 // NOTE: The mutex below must be leaked since the global module list in 80 // the ModuleList class will get torn at some point, and we can't know 81 // if it will tear itself down before the "g_module_collection_mutex" below 82 // will. So we leak a Mutex object below to safeguard against that 83 84 static std::recursive_mutex *g_module_collection_mutex = nullptr; 85 if (g_module_collection_mutex == nullptr) 86 g_module_collection_mutex = new std::recursive_mutex; // NOTE: known leak 87 return *g_module_collection_mutex; 88 } 89 90 size_t Module::GetNumberAllocatedModules() { 91 std::lock_guard<std::recursive_mutex> guard( 92 GetAllocationModuleCollectionMutex()); 93 return GetModuleCollection().size(); 94 } 95 96 Module *Module::GetAllocatedModuleAtIndex(size_t idx) { 97 std::lock_guard<std::recursive_mutex> guard( 98 GetAllocationModuleCollectionMutex()); 99 ModuleCollection &modules = GetModuleCollection(); 100 if (idx < modules.size()) 101 return modules[idx]; 102 return nullptr; 103 } 104 105 #if 0 106 // These functions help us to determine if modules are still loaded, yet don't require that 107 // you have a command interpreter and can easily be called from an external debugger. 108 namespace lldb { 109 110 void 111 ClearModuleInfo (void) 112 { 113 const bool mandatory = true; 114 ModuleList::RemoveOrphanSharedModules(mandatory); 115 } 116 117 void 118 DumpModuleInfo (void) 119 { 120 Mutex::Locker locker (Module::GetAllocationModuleCollectionMutex()); 121 ModuleCollection &modules = GetModuleCollection(); 122 const size_t count = modules.size(); 123 printf ("%s: %" PRIu64 " modules:\n", LLVM_PRETTY_FUNCTION, (uint64_t)count); 124 for (size_t i = 0; i < count; ++i) 125 { 126 127 StreamString strm; 128 Module *module = modules[i]; 129 const bool in_shared_module_list = ModuleList::ModuleIsInCache (module); 130 module->GetDescription(&strm, eDescriptionLevelFull); 131 printf ("%p: shared = %i, ref_count = %3u, module = %s\n", 132 module, 133 in_shared_module_list, 134 (uint32_t)module->use_count(), 135 strm.GetString().c_str()); 136 } 137 } 138 } 139 140 #endif 141 142 Module::Module(const ModuleSpec &module_spec) 143 : m_object_offset(0), m_file_has_changed(false), 144 m_first_file_changed_log(false) { 145 // Scope for locker below... 146 { 147 std::lock_guard<std::recursive_mutex> guard( 148 GetAllocationModuleCollectionMutex()); 149 GetModuleCollection().push_back(this); 150 } 151 152 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT | 153 LIBLLDB_LOG_MODULES)); 154 if (log != nullptr) 155 log->Printf("%p Module::Module((%s) '%s%s%s%s')", static_cast<void *>(this), 156 module_spec.GetArchitecture().GetArchitectureName(), 157 module_spec.GetFileSpec().GetPath().c_str(), 158 module_spec.GetObjectName().IsEmpty() ? "" : "(", 159 module_spec.GetObjectName().IsEmpty() 160 ? "" 161 : module_spec.GetObjectName().AsCString(""), 162 module_spec.GetObjectName().IsEmpty() ? "" : ")"); 163 164 // First extract all module specifications from the file using the local 165 // file path. If there are no specifications, then don't fill anything in 166 ModuleSpecList modules_specs; 167 if (ObjectFile::GetModuleSpecifications(module_spec.GetFileSpec(), 0, 0, 168 modules_specs) == 0) 169 return; 170 171 // Now make sure that one of the module specifications matches what we just 172 // extract. We might have a module specification that specifies a file 173 // "/usr/lib/dyld" 174 // with UUID XXX, but we might have a local version of "/usr/lib/dyld" that 175 // has 176 // UUID YYY and we don't want those to match. If they don't match, just don't 177 // fill any ivars in so we don't accidentally grab the wrong file later since 178 // they don't match... 179 ModuleSpec matching_module_spec; 180 if (modules_specs.FindMatchingModuleSpec(module_spec, matching_module_spec) == 181 0) 182 return; 183 184 if (module_spec.GetFileSpec()) 185 m_mod_time = FileSystem::GetModificationTime(module_spec.GetFileSpec()); 186 else if (matching_module_spec.GetFileSpec()) 187 m_mod_time = 188 FileSystem::GetModificationTime(matching_module_spec.GetFileSpec()); 189 190 // Copy the architecture from the actual spec if we got one back, else use the 191 // one that was specified 192 if (matching_module_spec.GetArchitecture().IsValid()) 193 m_arch = matching_module_spec.GetArchitecture(); 194 else if (module_spec.GetArchitecture().IsValid()) 195 m_arch = module_spec.GetArchitecture(); 196 197 // Copy the file spec over and use the specified one (if there was one) so we 198 // don't use a path that might have gotten resolved a path in 199 // 'matching_module_spec' 200 if (module_spec.GetFileSpec()) 201 m_file = module_spec.GetFileSpec(); 202 else if (matching_module_spec.GetFileSpec()) 203 m_file = matching_module_spec.GetFileSpec(); 204 205 // Copy the platform file spec over 206 if (module_spec.GetPlatformFileSpec()) 207 m_platform_file = module_spec.GetPlatformFileSpec(); 208 else if (matching_module_spec.GetPlatformFileSpec()) 209 m_platform_file = matching_module_spec.GetPlatformFileSpec(); 210 211 // Copy the symbol file spec over 212 if (module_spec.GetSymbolFileSpec()) 213 m_symfile_spec = module_spec.GetSymbolFileSpec(); 214 else if (matching_module_spec.GetSymbolFileSpec()) 215 m_symfile_spec = matching_module_spec.GetSymbolFileSpec(); 216 217 // Copy the object name over 218 if (matching_module_spec.GetObjectName()) 219 m_object_name = matching_module_spec.GetObjectName(); 220 else 221 m_object_name = module_spec.GetObjectName(); 222 223 // Always trust the object offset (file offset) and object modification 224 // time (for mod time in a BSD static archive) of from the matching 225 // module specification 226 m_object_offset = matching_module_spec.GetObjectOffset(); 227 m_object_mod_time = matching_module_spec.GetObjectModificationTime(); 228 } 229 230 Module::Module(const FileSpec &file_spec, const ArchSpec &arch, 231 const ConstString *object_name, lldb::offset_t object_offset, 232 const llvm::sys::TimePoint<> &object_mod_time) 233 : m_mod_time(FileSystem::GetModificationTime(file_spec)), m_arch(arch), 234 m_file(file_spec), m_object_offset(object_offset), 235 m_object_mod_time(object_mod_time), m_file_has_changed(false), 236 m_first_file_changed_log(false) { 237 // Scope for locker below... 238 { 239 std::lock_guard<std::recursive_mutex> guard( 240 GetAllocationModuleCollectionMutex()); 241 GetModuleCollection().push_back(this); 242 } 243 244 if (object_name) 245 m_object_name = *object_name; 246 247 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT | 248 LIBLLDB_LOG_MODULES)); 249 if (log != nullptr) 250 log->Printf("%p Module::Module((%s) '%s%s%s%s')", static_cast<void *>(this), 251 m_arch.GetArchitectureName(), m_file.GetPath().c_str(), 252 m_object_name.IsEmpty() ? "" : "(", 253 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""), 254 m_object_name.IsEmpty() ? "" : ")"); 255 } 256 257 Module::Module() 258 : m_object_offset(0), m_file_has_changed(false), 259 m_first_file_changed_log(false) { 260 std::lock_guard<std::recursive_mutex> guard( 261 GetAllocationModuleCollectionMutex()); 262 GetModuleCollection().push_back(this); 263 } 264 265 Module::~Module() { 266 // Lock our module down while we tear everything down to make sure 267 // we don't get any access to the module while it is being destroyed 268 std::lock_guard<std::recursive_mutex> guard(m_mutex); 269 // Scope for locker below... 270 { 271 std::lock_guard<std::recursive_mutex> guard( 272 GetAllocationModuleCollectionMutex()); 273 ModuleCollection &modules = GetModuleCollection(); 274 ModuleCollection::iterator end = modules.end(); 275 ModuleCollection::iterator pos = std::find(modules.begin(), end, this); 276 assert(pos != end); 277 modules.erase(pos); 278 } 279 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_OBJECT | 280 LIBLLDB_LOG_MODULES)); 281 if (log != nullptr) 282 log->Printf("%p Module::~Module((%s) '%s%s%s%s')", 283 static_cast<void *>(this), m_arch.GetArchitectureName(), 284 m_file.GetPath().c_str(), m_object_name.IsEmpty() ? "" : "(", 285 m_object_name.IsEmpty() ? "" : m_object_name.AsCString(""), 286 m_object_name.IsEmpty() ? "" : ")"); 287 // Release any auto pointers before we start tearing down our member 288 // variables since the object file and symbol files might need to make 289 // function calls back into this module object. The ordering is important 290 // here because symbol files can require the module object file. So we tear 291 // down the symbol file first, then the object file. 292 m_sections_ap.reset(); 293 m_symfile_ap.reset(); 294 m_objfile_sp.reset(); 295 } 296 297 ObjectFile *Module::GetMemoryObjectFile(const lldb::ProcessSP &process_sp, 298 lldb::addr_t header_addr, Error &error, 299 size_t size_to_read) { 300 if (m_objfile_sp) { 301 error.SetErrorString("object file already exists"); 302 } else { 303 std::lock_guard<std::recursive_mutex> guard(m_mutex); 304 if (process_sp) { 305 m_did_load_objfile = true; 306 std::unique_ptr<DataBufferHeap> data_ap( 307 new DataBufferHeap(size_to_read, 0)); 308 Error readmem_error; 309 const size_t bytes_read = 310 process_sp->ReadMemory(header_addr, data_ap->GetBytes(), 311 data_ap->GetByteSize(), readmem_error); 312 if (bytes_read == size_to_read) { 313 DataBufferSP data_sp(data_ap.release()); 314 m_objfile_sp = ObjectFile::FindPlugin(shared_from_this(), process_sp, 315 header_addr, data_sp); 316 if (m_objfile_sp) { 317 StreamString s; 318 s.Printf("0x%16.16" PRIx64, header_addr); 319 m_object_name.SetString(s.GetString()); 320 321 // Once we get the object file, update our module with the object 322 // file's 323 // architecture since it might differ in vendor/os if some parts were 324 // unknown. 325 m_objfile_sp->GetArchitecture(m_arch); 326 } else { 327 error.SetErrorString("unable to find suitable object file plug-in"); 328 } 329 } else { 330 error.SetErrorStringWithFormat("unable to read header from memory: %s", 331 readmem_error.AsCString()); 332 } 333 } else { 334 error.SetErrorString("invalid process"); 335 } 336 } 337 return m_objfile_sp.get(); 338 } 339 340 const lldb_private::UUID &Module::GetUUID() { 341 if (!m_did_parse_uuid.load()) { 342 std::lock_guard<std::recursive_mutex> guard(m_mutex); 343 if (!m_did_parse_uuid.load()) { 344 ObjectFile *obj_file = GetObjectFile(); 345 346 if (obj_file != nullptr) { 347 obj_file->GetUUID(&m_uuid); 348 m_did_parse_uuid = true; 349 } 350 } 351 } 352 return m_uuid; 353 } 354 355 TypeSystem *Module::GetTypeSystemForLanguage(LanguageType language) { 356 return m_type_system_map.GetTypeSystemForLanguage(language, this, true); 357 } 358 359 void Module::ParseAllDebugSymbols() { 360 std::lock_guard<std::recursive_mutex> guard(m_mutex); 361 size_t num_comp_units = GetNumCompileUnits(); 362 if (num_comp_units == 0) 363 return; 364 365 SymbolContext sc; 366 sc.module_sp = shared_from_this(); 367 SymbolVendor *symbols = GetSymbolVendor(); 368 369 for (size_t cu_idx = 0; cu_idx < num_comp_units; cu_idx++) { 370 sc.comp_unit = symbols->GetCompileUnitAtIndex(cu_idx).get(); 371 if (sc.comp_unit) { 372 sc.function = nullptr; 373 symbols->ParseVariablesForContext(sc); 374 375 symbols->ParseCompileUnitFunctions(sc); 376 377 for (size_t func_idx = 0; 378 (sc.function = sc.comp_unit->GetFunctionAtIndex(func_idx).get()) != 379 nullptr; 380 ++func_idx) { 381 symbols->ParseFunctionBlocks(sc); 382 383 // Parse the variables for this function and all its blocks 384 symbols->ParseVariablesForContext(sc); 385 } 386 387 // Parse all types for this compile unit 388 sc.function = nullptr; 389 symbols->ParseTypes(sc); 390 } 391 } 392 } 393 394 void Module::CalculateSymbolContext(SymbolContext *sc) { 395 sc->module_sp = shared_from_this(); 396 } 397 398 ModuleSP Module::CalculateSymbolContextModule() { return shared_from_this(); } 399 400 void Module::DumpSymbolContext(Stream *s) { 401 s->Printf(", Module{%p}", static_cast<void *>(this)); 402 } 403 404 size_t Module::GetNumCompileUnits() { 405 std::lock_guard<std::recursive_mutex> guard(m_mutex); 406 Timer scoped_timer(LLVM_PRETTY_FUNCTION, 407 "Module::GetNumCompileUnits (module = %p)", 408 static_cast<void *>(this)); 409 SymbolVendor *symbols = GetSymbolVendor(); 410 if (symbols) 411 return symbols->GetNumCompileUnits(); 412 return 0; 413 } 414 415 CompUnitSP Module::GetCompileUnitAtIndex(size_t index) { 416 std::lock_guard<std::recursive_mutex> guard(m_mutex); 417 size_t num_comp_units = GetNumCompileUnits(); 418 CompUnitSP cu_sp; 419 420 if (index < num_comp_units) { 421 SymbolVendor *symbols = GetSymbolVendor(); 422 if (symbols) 423 cu_sp = symbols->GetCompileUnitAtIndex(index); 424 } 425 return cu_sp; 426 } 427 428 bool Module::ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr) { 429 std::lock_guard<std::recursive_mutex> guard(m_mutex); 430 Timer scoped_timer(LLVM_PRETTY_FUNCTION, 431 "Module::ResolveFileAddress (vm_addr = 0x%" PRIx64 ")", 432 vm_addr); 433 SectionList *section_list = GetSectionList(); 434 if (section_list) 435 return so_addr.ResolveAddressUsingFileSections(vm_addr, section_list); 436 return false; 437 } 438 439 uint32_t Module::ResolveSymbolContextForAddress( 440 const Address &so_addr, uint32_t resolve_scope, SymbolContext &sc, 441 bool resolve_tail_call_address) { 442 std::lock_guard<std::recursive_mutex> guard(m_mutex); 443 uint32_t resolved_flags = 0; 444 445 // Clear the result symbol context in case we don't find anything, but don't 446 // clear the target 447 sc.Clear(false); 448 449 // Get the section from the section/offset address. 450 SectionSP section_sp(so_addr.GetSection()); 451 452 // Make sure the section matches this module before we try and match anything 453 if (section_sp && section_sp->GetModule().get() == this) { 454 // If the section offset based address resolved itself, then this 455 // is the right module. 456 sc.module_sp = shared_from_this(); 457 resolved_flags |= eSymbolContextModule; 458 459 SymbolVendor *sym_vendor = GetSymbolVendor(); 460 if (!sym_vendor) 461 return resolved_flags; 462 463 // Resolve the compile unit, function, block, line table or line 464 // entry if requested. 465 if (resolve_scope & eSymbolContextCompUnit || 466 resolve_scope & eSymbolContextFunction || 467 resolve_scope & eSymbolContextBlock || 468 resolve_scope & eSymbolContextLineEntry || 469 resolve_scope & eSymbolContextVariable) { 470 resolved_flags |= 471 sym_vendor->ResolveSymbolContext(so_addr, resolve_scope, sc); 472 } 473 474 // Resolve the symbol if requested, but don't re-look it up if we've already 475 // found it. 476 if (resolve_scope & eSymbolContextSymbol && 477 !(resolved_flags & eSymbolContextSymbol)) { 478 Symtab *symtab = sym_vendor->GetSymtab(); 479 if (symtab && so_addr.IsSectionOffset()) { 480 Symbol *matching_symbol = nullptr; 481 482 symtab->ForEachSymbolContainingFileAddress( 483 so_addr.GetFileAddress(), 484 [&matching_symbol](Symbol *symbol) -> bool { 485 if (symbol->GetType() != eSymbolTypeInvalid) { 486 matching_symbol = symbol; 487 return false; // Stop iterating 488 } 489 return true; // Keep iterating 490 }); 491 sc.symbol = matching_symbol; 492 if (!sc.symbol && resolve_scope & eSymbolContextFunction && 493 !(resolved_flags & eSymbolContextFunction)) { 494 bool verify_unique = false; // No need to check again since 495 // ResolveSymbolContext failed to find a 496 // symbol at this address. 497 if (ObjectFile *obj_file = sc.module_sp->GetObjectFile()) 498 sc.symbol = 499 obj_file->ResolveSymbolForAddress(so_addr, verify_unique); 500 } 501 502 if (sc.symbol) { 503 if (sc.symbol->IsSynthetic()) { 504 // We have a synthetic symbol so lets check if the object file 505 // from the symbol file in the symbol vendor is different than 506 // the object file for the module, and if so search its symbol 507 // table to see if we can come up with a better symbol. For example 508 // dSYM files on MacOSX have an unstripped symbol table inside of 509 // them. 510 ObjectFile *symtab_objfile = symtab->GetObjectFile(); 511 if (symtab_objfile && symtab_objfile->IsStripped()) { 512 SymbolFile *symfile = sym_vendor->GetSymbolFile(); 513 if (symfile) { 514 ObjectFile *symfile_objfile = symfile->GetObjectFile(); 515 if (symfile_objfile != symtab_objfile) { 516 Symtab *symfile_symtab = symfile_objfile->GetSymtab(); 517 if (symfile_symtab) { 518 Symbol *symbol = 519 symfile_symtab->FindSymbolContainingFileAddress( 520 so_addr.GetFileAddress()); 521 if (symbol && !symbol->IsSynthetic()) { 522 sc.symbol = symbol; 523 } 524 } 525 } 526 } 527 } 528 } 529 resolved_flags |= eSymbolContextSymbol; 530 } 531 } 532 } 533 534 // For function symbols, so_addr may be off by one. This is a convention 535 // consistent 536 // with FDE row indices in eh_frame sections, but requires extra logic here 537 // to permit 538 // symbol lookup for disassembly and unwind. 539 if (resolve_scope & eSymbolContextSymbol && 540 !(resolved_flags & eSymbolContextSymbol) && resolve_tail_call_address && 541 so_addr.IsSectionOffset()) { 542 Address previous_addr = so_addr; 543 previous_addr.Slide(-1); 544 545 bool do_resolve_tail_call_address = false; // prevent recursion 546 const uint32_t flags = ResolveSymbolContextForAddress( 547 previous_addr, resolve_scope, sc, do_resolve_tail_call_address); 548 if (flags & eSymbolContextSymbol) { 549 AddressRange addr_range; 550 if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0, 551 false, addr_range)) { 552 if (addr_range.GetBaseAddress().GetSection() == 553 so_addr.GetSection()) { 554 // If the requested address is one past the address range of a 555 // function (i.e. a tail call), 556 // or the decremented address is the start of a function (i.e. some 557 // forms of trampoline), 558 // indicate that the symbol has been resolved. 559 if (so_addr.GetOffset() == 560 addr_range.GetBaseAddress().GetOffset() || 561 so_addr.GetOffset() == 562 addr_range.GetBaseAddress().GetOffset() + 563 addr_range.GetByteSize()) { 564 resolved_flags |= flags; 565 } 566 } else { 567 sc.symbol = 568 nullptr; // Don't trust the symbol if the sections didn't match. 569 } 570 } 571 } 572 } 573 } 574 return resolved_flags; 575 } 576 577 uint32_t Module::ResolveSymbolContextForFilePath(const char *file_path, 578 uint32_t line, 579 bool check_inlines, 580 uint32_t resolve_scope, 581 SymbolContextList &sc_list) { 582 FileSpec file_spec(file_path, false); 583 return ResolveSymbolContextsForFileSpec(file_spec, line, check_inlines, 584 resolve_scope, sc_list); 585 } 586 587 uint32_t Module::ResolveSymbolContextsForFileSpec(const FileSpec &file_spec, 588 uint32_t line, 589 bool check_inlines, 590 uint32_t resolve_scope, 591 SymbolContextList &sc_list) { 592 std::lock_guard<std::recursive_mutex> guard(m_mutex); 593 Timer scoped_timer(LLVM_PRETTY_FUNCTION, 594 "Module::ResolveSymbolContextForFilePath (%s:%u, " 595 "check_inlines = %s, resolve_scope = 0x%8.8x)", 596 file_spec.GetPath().c_str(), line, 597 check_inlines ? "yes" : "no", resolve_scope); 598 599 const uint32_t initial_count = sc_list.GetSize(); 600 601 SymbolVendor *symbols = GetSymbolVendor(); 602 if (symbols) 603 symbols->ResolveSymbolContext(file_spec, line, check_inlines, resolve_scope, 604 sc_list); 605 606 return sc_list.GetSize() - initial_count; 607 } 608 609 size_t Module::FindGlobalVariables(const ConstString &name, 610 const CompilerDeclContext *parent_decl_ctx, 611 bool append, size_t max_matches, 612 VariableList &variables) { 613 SymbolVendor *symbols = GetSymbolVendor(); 614 if (symbols) 615 return symbols->FindGlobalVariables(name, parent_decl_ctx, append, 616 max_matches, variables); 617 return 0; 618 } 619 620 size_t Module::FindGlobalVariables(const RegularExpression ®ex, bool append, 621 size_t max_matches, 622 VariableList &variables) { 623 SymbolVendor *symbols = GetSymbolVendor(); 624 if (symbols) 625 return symbols->FindGlobalVariables(regex, append, max_matches, variables); 626 return 0; 627 } 628 629 size_t Module::FindCompileUnits(const FileSpec &path, bool append, 630 SymbolContextList &sc_list) { 631 if (!append) 632 sc_list.Clear(); 633 634 const size_t start_size = sc_list.GetSize(); 635 const size_t num_compile_units = GetNumCompileUnits(); 636 SymbolContext sc; 637 sc.module_sp = shared_from_this(); 638 const bool compare_directory = (bool)path.GetDirectory(); 639 for (size_t i = 0; i < num_compile_units; ++i) { 640 sc.comp_unit = GetCompileUnitAtIndex(i).get(); 641 if (sc.comp_unit) { 642 if (FileSpec::Equal(*sc.comp_unit, path, compare_directory)) 643 sc_list.Append(sc); 644 } 645 } 646 return sc_list.GetSize() - start_size; 647 } 648 649 Module::LookupInfo::LookupInfo(const ConstString &name, uint32_t name_type_mask, 650 lldb::LanguageType language) 651 : m_name(name), m_lookup_name(), m_language(language), m_name_type_mask(0), 652 m_match_name_after_lookup(false) { 653 const char *name_cstr = name.GetCString(); 654 llvm::StringRef basename; 655 llvm::StringRef context; 656 657 if (name_type_mask & eFunctionNameTypeAuto) { 658 if (CPlusPlusLanguage::IsCPPMangledName(name_cstr)) 659 m_name_type_mask = eFunctionNameTypeFull; 660 else if ((language == eLanguageTypeUnknown || 661 Language::LanguageIsObjC(language)) && 662 ObjCLanguage::IsPossibleObjCMethodName(name_cstr)) 663 m_name_type_mask = eFunctionNameTypeFull; 664 else if (Language::LanguageIsC(language)) { 665 m_name_type_mask = eFunctionNameTypeFull; 666 } else { 667 if ((language == eLanguageTypeUnknown || 668 Language::LanguageIsObjC(language)) && 669 ObjCLanguage::IsPossibleObjCSelector(name_cstr)) 670 m_name_type_mask |= eFunctionNameTypeSelector; 671 672 CPlusPlusLanguage::MethodName cpp_method(name); 673 basename = cpp_method.GetBasename(); 674 if (basename.empty()) { 675 if (CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context, 676 basename)) 677 m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase); 678 else 679 m_name_type_mask |= eFunctionNameTypeFull; 680 } else { 681 m_name_type_mask |= (eFunctionNameTypeMethod | eFunctionNameTypeBase); 682 } 683 } 684 } else { 685 m_name_type_mask = name_type_mask; 686 if (name_type_mask & eFunctionNameTypeMethod || 687 name_type_mask & eFunctionNameTypeBase) { 688 // If they've asked for a CPP method or function name and it can't be 689 // that, we don't 690 // even need to search for CPP methods or names. 691 CPlusPlusLanguage::MethodName cpp_method(name); 692 if (cpp_method.IsValid()) { 693 basename = cpp_method.GetBasename(); 694 695 if (!cpp_method.GetQualifiers().empty()) { 696 // There is a "const" or other qualifier following the end of the 697 // function parens, 698 // this can't be a eFunctionNameTypeBase 699 m_name_type_mask &= ~(eFunctionNameTypeBase); 700 if (m_name_type_mask == eFunctionNameTypeNone) 701 return; 702 } 703 } else { 704 // If the CPP method parser didn't manage to chop this up, try to fill 705 // in the base name if we can. 706 // If a::b::c is passed in, we need to just look up "c", and then we'll 707 // filter the result later. 708 CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context, 709 basename); 710 } 711 } 712 713 if (name_type_mask & eFunctionNameTypeSelector) { 714 if (!ObjCLanguage::IsPossibleObjCSelector(name_cstr)) { 715 m_name_type_mask &= ~(eFunctionNameTypeSelector); 716 if (m_name_type_mask == eFunctionNameTypeNone) 717 return; 718 } 719 } 720 721 // Still try and get a basename in case someone specifies a name type mask 722 // of 723 // eFunctionNameTypeFull and a name like "A::func" 724 if (basename.empty()) { 725 if (name_type_mask & eFunctionNameTypeFull) { 726 CPlusPlusLanguage::MethodName cpp_method(name); 727 basename = cpp_method.GetBasename(); 728 if (basename.empty()) 729 CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context, 730 basename); 731 } 732 } 733 } 734 735 if (!basename.empty()) { 736 // The name supplied was a partial C++ path like "a::count". In this case we 737 // want to do a 738 // lookup on the basename "count" and then make sure any matching results 739 // contain "a::count" 740 // so that it would match "b::a::count" and "a::count". This is why we set 741 // "match_name_after_lookup" 742 // to true 743 m_lookup_name.SetString(basename); 744 m_match_name_after_lookup = true; 745 } else { 746 // The name is already correct, just use the exact name as supplied, and we 747 // won't need 748 // to check if any matches contain "name" 749 m_lookup_name = name; 750 m_match_name_after_lookup = false; 751 } 752 } 753 754 void Module::LookupInfo::Prune(SymbolContextList &sc_list, 755 size_t start_idx) const { 756 if (m_match_name_after_lookup && m_name) { 757 SymbolContext sc; 758 size_t i = start_idx; 759 while (i < sc_list.GetSize()) { 760 if (!sc_list.GetContextAtIndex(i, sc)) 761 break; 762 ConstString full_name(sc.GetFunctionName()); 763 if (full_name && 764 ::strstr(full_name.GetCString(), m_name.GetCString()) == nullptr) { 765 sc_list.RemoveContextAtIndex(i); 766 } else { 767 ++i; 768 } 769 } 770 } 771 772 // If we have only full name matches we might have tried to set breakpoint on 773 // "func" 774 // and specified eFunctionNameTypeFull, but we might have found "a::func()", 775 // "a::b::func()", "c::func()", "func()" and "func". Only "func()" and "func" 776 // should 777 // end up matching. 778 if (m_name_type_mask == eFunctionNameTypeFull) { 779 SymbolContext sc; 780 size_t i = start_idx; 781 while (i < sc_list.GetSize()) { 782 if (!sc_list.GetContextAtIndex(i, sc)) 783 break; 784 ConstString full_name(sc.GetFunctionName()); 785 CPlusPlusLanguage::MethodName cpp_method(full_name); 786 if (cpp_method.IsValid()) { 787 if (cpp_method.GetContext().empty()) { 788 if (cpp_method.GetBasename().compare(m_name.GetStringRef()) != 0) { 789 sc_list.RemoveContextAtIndex(i); 790 continue; 791 } 792 } else { 793 std::string qualified_name = cpp_method.GetScopeQualifiedName(); 794 if (qualified_name.compare(m_name.GetCString()) != 0) { 795 sc_list.RemoveContextAtIndex(i); 796 continue; 797 } 798 } 799 } 800 ++i; 801 } 802 } 803 } 804 805 size_t Module::FindFunctions(const ConstString &name, 806 const CompilerDeclContext *parent_decl_ctx, 807 uint32_t name_type_mask, bool include_symbols, 808 bool include_inlines, bool append, 809 SymbolContextList &sc_list) { 810 if (!append) 811 sc_list.Clear(); 812 813 const size_t old_size = sc_list.GetSize(); 814 815 // Find all the functions (not symbols, but debug information functions... 816 SymbolVendor *symbols = GetSymbolVendor(); 817 818 if (name_type_mask & eFunctionNameTypeAuto) { 819 LookupInfo lookup_info(name, name_type_mask, eLanguageTypeUnknown); 820 821 if (symbols) { 822 symbols->FindFunctions(lookup_info.GetLookupName(), parent_decl_ctx, 823 lookup_info.GetNameTypeMask(), include_inlines, 824 append, sc_list); 825 826 // Now check our symbol table for symbols that are code symbols if 827 // requested 828 if (include_symbols) { 829 Symtab *symtab = symbols->GetSymtab(); 830 if (symtab) 831 symtab->FindFunctionSymbols(lookup_info.GetLookupName(), 832 lookup_info.GetNameTypeMask(), sc_list); 833 } 834 } 835 836 const size_t new_size = sc_list.GetSize(); 837 838 if (old_size < new_size) 839 lookup_info.Prune(sc_list, old_size); 840 } else { 841 if (symbols) { 842 symbols->FindFunctions(name, parent_decl_ctx, name_type_mask, 843 include_inlines, append, sc_list); 844 845 // Now check our symbol table for symbols that are code symbols if 846 // requested 847 if (include_symbols) { 848 Symtab *symtab = symbols->GetSymtab(); 849 if (symtab) 850 symtab->FindFunctionSymbols(name, name_type_mask, sc_list); 851 } 852 } 853 } 854 855 return sc_list.GetSize() - old_size; 856 } 857 858 size_t Module::FindFunctions(const RegularExpression ®ex, 859 bool include_symbols, bool include_inlines, 860 bool append, SymbolContextList &sc_list) { 861 if (!append) 862 sc_list.Clear(); 863 864 const size_t start_size = sc_list.GetSize(); 865 866 SymbolVendor *symbols = GetSymbolVendor(); 867 if (symbols) { 868 symbols->FindFunctions(regex, include_inlines, append, sc_list); 869 870 // Now check our symbol table for symbols that are code symbols if requested 871 if (include_symbols) { 872 Symtab *symtab = symbols->GetSymtab(); 873 if (symtab) { 874 std::vector<uint32_t> symbol_indexes; 875 symtab->AppendSymbolIndexesMatchingRegExAndType( 876 regex, eSymbolTypeAny, Symtab::eDebugAny, Symtab::eVisibilityAny, 877 symbol_indexes); 878 const size_t num_matches = symbol_indexes.size(); 879 if (num_matches) { 880 SymbolContext sc(this); 881 const size_t end_functions_added_index = sc_list.GetSize(); 882 size_t num_functions_added_to_sc_list = 883 end_functions_added_index - start_size; 884 if (num_functions_added_to_sc_list == 0) { 885 // No functions were added, just symbols, so we can just append them 886 for (size_t i = 0; i < num_matches; ++i) { 887 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]); 888 SymbolType sym_type = sc.symbol->GetType(); 889 if (sc.symbol && (sym_type == eSymbolTypeCode || 890 sym_type == eSymbolTypeResolver)) 891 sc_list.Append(sc); 892 } 893 } else { 894 typedef std::map<lldb::addr_t, uint32_t> FileAddrToIndexMap; 895 FileAddrToIndexMap file_addr_to_index; 896 for (size_t i = start_size; i < end_functions_added_index; ++i) { 897 const SymbolContext &sc = sc_list[i]; 898 if (sc.block) 899 continue; 900 file_addr_to_index[sc.function->GetAddressRange() 901 .GetBaseAddress() 902 .GetFileAddress()] = i; 903 } 904 905 FileAddrToIndexMap::const_iterator end = file_addr_to_index.end(); 906 // Functions were added so we need to merge symbols into any 907 // existing function symbol contexts 908 for (size_t i = start_size; i < num_matches; ++i) { 909 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]); 910 SymbolType sym_type = sc.symbol->GetType(); 911 if (sc.symbol && sc.symbol->ValueIsAddress() && 912 (sym_type == eSymbolTypeCode || 913 sym_type == eSymbolTypeResolver)) { 914 FileAddrToIndexMap::const_iterator pos = 915 file_addr_to_index.find( 916 sc.symbol->GetAddressRef().GetFileAddress()); 917 if (pos == end) 918 sc_list.Append(sc); 919 else 920 sc_list[pos->second].symbol = sc.symbol; 921 } 922 } 923 } 924 } 925 } 926 } 927 } 928 return sc_list.GetSize() - start_size; 929 } 930 931 void Module::FindAddressesForLine(const lldb::TargetSP target_sp, 932 const FileSpec &file, uint32_t line, 933 Function *function, 934 std::vector<Address> &output_local, 935 std::vector<Address> &output_extern) { 936 SearchFilterByModule filter(target_sp, m_file); 937 AddressResolverFileLine resolver(file, line, true); 938 resolver.ResolveAddress(filter); 939 940 for (size_t n = 0; n < resolver.GetNumberOfAddresses(); n++) { 941 Address addr = resolver.GetAddressRangeAtIndex(n).GetBaseAddress(); 942 Function *f = addr.CalculateSymbolContextFunction(); 943 if (f && f == function) 944 output_local.push_back(addr); 945 else 946 output_extern.push_back(addr); 947 } 948 } 949 950 size_t Module::FindTypes_Impl( 951 const SymbolContext &sc, const ConstString &name, 952 const CompilerDeclContext *parent_decl_ctx, bool append, size_t max_matches, 953 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, 954 TypeMap &types) { 955 Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); 956 if (!sc.module_sp || sc.module_sp.get() == this) { 957 SymbolVendor *symbols = GetSymbolVendor(); 958 if (symbols) 959 return symbols->FindTypes(sc, name, parent_decl_ctx, append, max_matches, 960 searched_symbol_files, types); 961 } 962 return 0; 963 } 964 965 size_t Module::FindTypesInNamespace(const SymbolContext &sc, 966 const ConstString &type_name, 967 const CompilerDeclContext *parent_decl_ctx, 968 size_t max_matches, TypeList &type_list) { 969 const bool append = true; 970 TypeMap types_map; 971 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files; 972 size_t num_types = 973 FindTypes_Impl(sc, type_name, parent_decl_ctx, append, max_matches, 974 searched_symbol_files, types_map); 975 if (num_types > 0) 976 sc.SortTypeList(types_map, type_list); 977 return num_types; 978 } 979 980 lldb::TypeSP Module::FindFirstType(const SymbolContext &sc, 981 const ConstString &name, bool exact_match) { 982 TypeList type_list; 983 llvm::DenseSet<lldb_private::SymbolFile *> searched_symbol_files; 984 const size_t num_matches = 985 FindTypes(sc, name, exact_match, 1, searched_symbol_files, type_list); 986 if (num_matches) 987 return type_list.GetTypeAtIndex(0); 988 return TypeSP(); 989 } 990 991 size_t Module::FindTypes( 992 const SymbolContext &sc, const ConstString &name, bool exact_match, 993 size_t max_matches, 994 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, 995 TypeList &types) { 996 size_t num_matches = 0; 997 const char *type_name_cstr = name.GetCString(); 998 llvm::StringRef type_scope; 999 llvm::StringRef type_basename; 1000 const bool append = true; 1001 TypeClass type_class = eTypeClassAny; 1002 TypeMap typesmap; 1003 if (Type::GetTypeScopeAndBasename(type_name_cstr, type_scope, type_basename, 1004 type_class)) { 1005 // Check if "name" starts with "::" which means the qualified type starts 1006 // from the root namespace and implies and exact match. The typenames we 1007 // get back from clang do not start with "::" so we need to strip this off 1008 // in order to get the qualified names to match 1009 exact_match = type_scope.consume_front("::"); 1010 1011 ConstString type_basename_const_str(type_basename); 1012 if (FindTypes_Impl(sc, type_basename_const_str, nullptr, append, 1013 max_matches, searched_symbol_files, typesmap)) { 1014 typesmap.RemoveMismatchedTypes(type_scope, type_basename, type_class, 1015 exact_match); 1016 num_matches = typesmap.GetSize(); 1017 } 1018 } else { 1019 // The type is not in a namespace/class scope, just search for it by 1020 // basename 1021 if (type_class != eTypeClassAny) { 1022 // The "type_name_cstr" will have been modified if we have a valid type 1023 // class 1024 // prefix (like "struct", "class", "union", "typedef" etc). 1025 FindTypes_Impl(sc, ConstString(type_name_cstr), nullptr, append, 1026 max_matches, searched_symbol_files, typesmap); 1027 typesmap.RemoveMismatchedTypes(type_class); 1028 num_matches = typesmap.GetSize(); 1029 } else { 1030 num_matches = FindTypes_Impl(sc, name, nullptr, append, max_matches, 1031 searched_symbol_files, typesmap); 1032 } 1033 } 1034 if (num_matches > 0) 1035 sc.SortTypeList(typesmap, types); 1036 return num_matches; 1037 } 1038 1039 SymbolVendor *Module::GetSymbolVendor(bool can_create, 1040 lldb_private::Stream *feedback_strm) { 1041 if (!m_did_load_symbol_vendor.load()) { 1042 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1043 if (!m_did_load_symbol_vendor.load() && can_create) { 1044 ObjectFile *obj_file = GetObjectFile(); 1045 if (obj_file != nullptr) { 1046 Timer scoped_timer(LLVM_PRETTY_FUNCTION, LLVM_PRETTY_FUNCTION); 1047 m_symfile_ap.reset( 1048 SymbolVendor::FindPlugin(shared_from_this(), feedback_strm)); 1049 m_did_load_symbol_vendor = true; 1050 } 1051 } 1052 } 1053 return m_symfile_ap.get(); 1054 } 1055 1056 void Module::SetFileSpecAndObjectName(const FileSpec &file, 1057 const ConstString &object_name) { 1058 // Container objects whose paths do not specify a file directly can call 1059 // this function to correct the file and object names. 1060 m_file = file; 1061 m_mod_time = FileSystem::GetModificationTime(file); 1062 m_object_name = object_name; 1063 } 1064 1065 const ArchSpec &Module::GetArchitecture() const { return m_arch; } 1066 1067 std::string Module::GetSpecificationDescription() const { 1068 std::string spec(GetFileSpec().GetPath()); 1069 if (m_object_name) { 1070 spec += '('; 1071 spec += m_object_name.GetCString(); 1072 spec += ')'; 1073 } 1074 return spec; 1075 } 1076 1077 void Module::GetDescription(Stream *s, lldb::DescriptionLevel level) { 1078 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1079 1080 if (level >= eDescriptionLevelFull) { 1081 if (m_arch.IsValid()) 1082 s->Printf("(%s) ", m_arch.GetArchitectureName()); 1083 } 1084 1085 if (level == eDescriptionLevelBrief) { 1086 const char *filename = m_file.GetFilename().GetCString(); 1087 if (filename) 1088 s->PutCString(filename); 1089 } else { 1090 char path[PATH_MAX]; 1091 if (m_file.GetPath(path, sizeof(path))) 1092 s->PutCString(path); 1093 } 1094 1095 const char *object_name = m_object_name.GetCString(); 1096 if (object_name) 1097 s->Printf("(%s)", object_name); 1098 } 1099 1100 void Module::ReportError(const char *format, ...) { 1101 if (format && format[0]) { 1102 StreamString strm; 1103 strm.PutCString("error: "); 1104 GetDescription(&strm, lldb::eDescriptionLevelBrief); 1105 strm.PutChar(' '); 1106 va_list args; 1107 va_start(args, format); 1108 strm.PrintfVarArg(format, args); 1109 va_end(args); 1110 1111 const int format_len = strlen(format); 1112 if (format_len > 0) { 1113 const char last_char = format[format_len - 1]; 1114 if (last_char != '\n' || last_char != '\r') 1115 strm.EOL(); 1116 } 1117 Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData()); 1118 } 1119 } 1120 1121 bool Module::FileHasChanged() const { 1122 if (!m_file_has_changed) 1123 m_file_has_changed = 1124 (FileSystem::GetModificationTime(m_file) != m_mod_time); 1125 return m_file_has_changed; 1126 } 1127 1128 void Module::ReportErrorIfModifyDetected(const char *format, ...) { 1129 if (!m_first_file_changed_log) { 1130 if (FileHasChanged()) { 1131 m_first_file_changed_log = true; 1132 if (format) { 1133 StreamString strm; 1134 strm.PutCString("error: the object file "); 1135 GetDescription(&strm, lldb::eDescriptionLevelFull); 1136 strm.PutCString(" has been modified\n"); 1137 1138 va_list args; 1139 va_start(args, format); 1140 strm.PrintfVarArg(format, args); 1141 va_end(args); 1142 1143 const int format_len = strlen(format); 1144 if (format_len > 0) { 1145 const char last_char = format[format_len - 1]; 1146 if (last_char != '\n' || last_char != '\r') 1147 strm.EOL(); 1148 } 1149 strm.PutCString("The debug session should be aborted as the original " 1150 "debug information has been overwritten.\n"); 1151 Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData()); 1152 } 1153 } 1154 } 1155 } 1156 1157 void Module::ReportWarning(const char *format, ...) { 1158 if (format && format[0]) { 1159 StreamString strm; 1160 strm.PutCString("warning: "); 1161 GetDescription(&strm, lldb::eDescriptionLevelFull); 1162 strm.PutChar(' '); 1163 1164 va_list args; 1165 va_start(args, format); 1166 strm.PrintfVarArg(format, args); 1167 va_end(args); 1168 1169 const int format_len = strlen(format); 1170 if (format_len > 0) { 1171 const char last_char = format[format_len - 1]; 1172 if (last_char != '\n' || last_char != '\r') 1173 strm.EOL(); 1174 } 1175 Host::SystemLog(Host::eSystemLogWarning, "%s", strm.GetData()); 1176 } 1177 } 1178 1179 void Module::LogMessage(Log *log, const char *format, ...) { 1180 if (log != nullptr) { 1181 StreamString log_message; 1182 GetDescription(&log_message, lldb::eDescriptionLevelFull); 1183 log_message.PutCString(": "); 1184 va_list args; 1185 va_start(args, format); 1186 log_message.PrintfVarArg(format, args); 1187 va_end(args); 1188 log->PutCString(log_message.GetData()); 1189 } 1190 } 1191 1192 void Module::LogMessageVerboseBacktrace(Log *log, const char *format, ...) { 1193 if (log != nullptr) { 1194 StreamString log_message; 1195 GetDescription(&log_message, lldb::eDescriptionLevelFull); 1196 log_message.PutCString(": "); 1197 va_list args; 1198 va_start(args, format); 1199 log_message.PrintfVarArg(format, args); 1200 va_end(args); 1201 if (log->GetVerbose()) { 1202 std::string back_trace; 1203 llvm::raw_string_ostream stream(back_trace); 1204 llvm::sys::PrintStackTrace(stream); 1205 log_message.PutCString(back_trace); 1206 } 1207 log->PutCString(log_message.GetData()); 1208 } 1209 } 1210 1211 void Module::Dump(Stream *s) { 1212 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1213 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this); 1214 s->Indent(); 1215 s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(), 1216 m_object_name ? "(" : "", 1217 m_object_name ? m_object_name.GetCString() : "", 1218 m_object_name ? ")" : ""); 1219 1220 s->IndentMore(); 1221 1222 ObjectFile *objfile = GetObjectFile(); 1223 if (objfile) 1224 objfile->Dump(s); 1225 1226 SymbolVendor *symbols = GetSymbolVendor(); 1227 if (symbols) 1228 symbols->Dump(s); 1229 1230 s->IndentLess(); 1231 } 1232 1233 TypeList *Module::GetTypeList() { 1234 SymbolVendor *symbols = GetSymbolVendor(); 1235 if (symbols) 1236 return &symbols->GetTypeList(); 1237 return nullptr; 1238 } 1239 1240 const ConstString &Module::GetObjectName() const { return m_object_name; } 1241 1242 ObjectFile *Module::GetObjectFile() { 1243 if (!m_did_load_objfile.load()) { 1244 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1245 if (!m_did_load_objfile.load()) { 1246 Timer scoped_timer(LLVM_PRETTY_FUNCTION, 1247 "Module::GetObjectFile () module = %s", 1248 GetFileSpec().GetFilename().AsCString("")); 1249 DataBufferSP data_sp; 1250 lldb::offset_t data_offset = 0; 1251 const lldb::offset_t file_size = m_file.GetByteSize(); 1252 if (file_size > m_object_offset) { 1253 m_did_load_objfile = true; 1254 m_objfile_sp = ObjectFile::FindPlugin( 1255 shared_from_this(), &m_file, m_object_offset, 1256 file_size - m_object_offset, data_sp, data_offset); 1257 if (m_objfile_sp) { 1258 // Once we get the object file, update our module with the object 1259 // file's 1260 // architecture since it might differ in vendor/os if some parts were 1261 // unknown. But since the matching arch might already be more 1262 // specific 1263 // than the generic COFF architecture, only merge in those values that 1264 // overwrite unspecified unknown values. 1265 ArchSpec new_arch; 1266 m_objfile_sp->GetArchitecture(new_arch); 1267 m_arch.MergeFrom(new_arch); 1268 } else { 1269 ReportError("failed to load objfile for %s", 1270 GetFileSpec().GetPath().c_str()); 1271 } 1272 } 1273 } 1274 } 1275 return m_objfile_sp.get(); 1276 } 1277 1278 SectionList *Module::GetSectionList() { 1279 // Populate m_unified_sections_ap with sections from objfile. 1280 if (!m_sections_ap) { 1281 ObjectFile *obj_file = GetObjectFile(); 1282 if (obj_file != nullptr) 1283 obj_file->CreateSections(*GetUnifiedSectionList()); 1284 } 1285 return m_sections_ap.get(); 1286 } 1287 1288 void Module::SectionFileAddressesChanged() { 1289 ObjectFile *obj_file = GetObjectFile(); 1290 if (obj_file) 1291 obj_file->SectionFileAddressesChanged(); 1292 SymbolVendor *sym_vendor = GetSymbolVendor(); 1293 if (sym_vendor != nullptr) 1294 sym_vendor->SectionFileAddressesChanged(); 1295 } 1296 1297 SectionList *Module::GetUnifiedSectionList() { 1298 // Populate m_unified_sections_ap with sections from objfile. 1299 if (!m_sections_ap) 1300 m_sections_ap.reset(new SectionList()); 1301 return m_sections_ap.get(); 1302 } 1303 1304 const Symbol *Module::FindFirstSymbolWithNameAndType(const ConstString &name, 1305 SymbolType symbol_type) { 1306 Timer scoped_timer( 1307 LLVM_PRETTY_FUNCTION, 1308 "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)", 1309 name.AsCString(), symbol_type); 1310 SymbolVendor *sym_vendor = GetSymbolVendor(); 1311 if (sym_vendor) { 1312 Symtab *symtab = sym_vendor->GetSymtab(); 1313 if (symtab) 1314 return symtab->FindFirstSymbolWithNameAndType( 1315 name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny); 1316 } 1317 return nullptr; 1318 } 1319 void Module::SymbolIndicesToSymbolContextList( 1320 Symtab *symtab, std::vector<uint32_t> &symbol_indexes, 1321 SymbolContextList &sc_list) { 1322 // No need to protect this call using m_mutex all other method calls are 1323 // already thread safe. 1324 1325 size_t num_indices = symbol_indexes.size(); 1326 if (num_indices > 0) { 1327 SymbolContext sc; 1328 CalculateSymbolContext(&sc); 1329 for (size_t i = 0; i < num_indices; i++) { 1330 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]); 1331 if (sc.symbol) 1332 sc_list.Append(sc); 1333 } 1334 } 1335 } 1336 1337 size_t Module::FindFunctionSymbols(const ConstString &name, 1338 uint32_t name_type_mask, 1339 SymbolContextList &sc_list) { 1340 Timer scoped_timer(LLVM_PRETTY_FUNCTION, 1341 "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)", 1342 name.AsCString(), name_type_mask); 1343 SymbolVendor *sym_vendor = GetSymbolVendor(); 1344 if (sym_vendor) { 1345 Symtab *symtab = sym_vendor->GetSymtab(); 1346 if (symtab) 1347 return symtab->FindFunctionSymbols(name, name_type_mask, sc_list); 1348 } 1349 return 0; 1350 } 1351 1352 size_t Module::FindSymbolsWithNameAndType(const ConstString &name, 1353 SymbolType symbol_type, 1354 SymbolContextList &sc_list) { 1355 // No need to protect this call using m_mutex all other method calls are 1356 // already thread safe. 1357 1358 Timer scoped_timer( 1359 LLVM_PRETTY_FUNCTION, 1360 "Module::FindSymbolsWithNameAndType (name = %s, type = %i)", 1361 name.AsCString(), symbol_type); 1362 const size_t initial_size = sc_list.GetSize(); 1363 SymbolVendor *sym_vendor = GetSymbolVendor(); 1364 if (sym_vendor) { 1365 Symtab *symtab = sym_vendor->GetSymtab(); 1366 if (symtab) { 1367 std::vector<uint32_t> symbol_indexes; 1368 symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes); 1369 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list); 1370 } 1371 } 1372 return sc_list.GetSize() - initial_size; 1373 } 1374 1375 size_t Module::FindSymbolsMatchingRegExAndType(const RegularExpression ®ex, 1376 SymbolType symbol_type, 1377 SymbolContextList &sc_list) { 1378 // No need to protect this call using m_mutex all other method calls are 1379 // already thread safe. 1380 1381 Timer scoped_timer( 1382 LLVM_PRETTY_FUNCTION, 1383 "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)", 1384 regex.GetText().str().c_str(), symbol_type); 1385 const size_t initial_size = sc_list.GetSize(); 1386 SymbolVendor *sym_vendor = GetSymbolVendor(); 1387 if (sym_vendor) { 1388 Symtab *symtab = sym_vendor->GetSymtab(); 1389 if (symtab) { 1390 std::vector<uint32_t> symbol_indexes; 1391 symtab->FindAllSymbolsMatchingRexExAndType( 1392 regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, 1393 symbol_indexes); 1394 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list); 1395 } 1396 } 1397 return sc_list.GetSize() - initial_size; 1398 } 1399 1400 void Module::SetSymbolFileFileSpec(const FileSpec &file) { 1401 if (!file.Exists()) 1402 return; 1403 if (m_symfile_ap) { 1404 // Remove any sections in the unified section list that come from the 1405 // current symbol vendor. 1406 SectionList *section_list = GetSectionList(); 1407 SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile(); 1408 if (section_list && symbol_file) { 1409 ObjectFile *obj_file = symbol_file->GetObjectFile(); 1410 // Make sure we have an object file and that the symbol vendor's objfile 1411 // isn't 1412 // the same as the module's objfile before we remove any sections for 1413 // it... 1414 if (obj_file) { 1415 // Check to make sure we aren't trying to specify the file we already 1416 // have 1417 if (obj_file->GetFileSpec() == file) { 1418 // We are being told to add the exact same file that we already have 1419 // we don't have to do anything. 1420 return; 1421 } 1422 1423 // Cleare the current symtab as we are going to replace it with a new 1424 // one 1425 obj_file->ClearSymtab(); 1426 1427 // The symbol file might be a directory bundle ("/tmp/a.out.dSYM") 1428 // instead 1429 // of a full path to the symbol file within the bundle 1430 // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to 1431 // check this 1432 1433 if (file.IsDirectory()) { 1434 std::string new_path(file.GetPath()); 1435 std::string old_path(obj_file->GetFileSpec().GetPath()); 1436 if (old_path.find(new_path) == 0) { 1437 // We specified the same bundle as the symbol file that we already 1438 // have 1439 return; 1440 } 1441 } 1442 1443 if (obj_file != m_objfile_sp.get()) { 1444 size_t num_sections = section_list->GetNumSections(0); 1445 for (size_t idx = num_sections; idx > 0; --idx) { 1446 lldb::SectionSP section_sp( 1447 section_list->GetSectionAtIndex(idx - 1)); 1448 if (section_sp->GetObjectFile() == obj_file) { 1449 section_list->DeleteSection(idx - 1); 1450 } 1451 } 1452 } 1453 } 1454 } 1455 // Keep all old symbol files around in case there are any lingering type 1456 // references in 1457 // any SBValue objects that might have been handed out. 1458 m_old_symfiles.push_back(std::move(m_symfile_ap)); 1459 } 1460 m_symfile_spec = file; 1461 m_symfile_ap.reset(); 1462 m_did_load_symbol_vendor = false; 1463 } 1464 1465 bool Module::IsExecutable() { 1466 if (GetObjectFile() == nullptr) 1467 return false; 1468 else 1469 return GetObjectFile()->IsExecutable(); 1470 } 1471 1472 bool Module::IsLoadedInTarget(Target *target) { 1473 ObjectFile *obj_file = GetObjectFile(); 1474 if (obj_file) { 1475 SectionList *sections = GetSectionList(); 1476 if (sections != nullptr) { 1477 size_t num_sections = sections->GetSize(); 1478 for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++) { 1479 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx); 1480 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) { 1481 return true; 1482 } 1483 } 1484 } 1485 } 1486 return false; 1487 } 1488 1489 bool Module::LoadScriptingResourceInTarget(Target *target, Error &error, 1490 Stream *feedback_stream) { 1491 if (!target) { 1492 error.SetErrorString("invalid destination Target"); 1493 return false; 1494 } 1495 1496 LoadScriptFromSymFile should_load = 1497 target->TargetProperties::GetLoadScriptFromSymbolFile(); 1498 1499 if (should_load == eLoadScriptFromSymFileFalse) 1500 return false; 1501 1502 Debugger &debugger = target->GetDebugger(); 1503 const ScriptLanguage script_language = debugger.GetScriptLanguage(); 1504 if (script_language != eScriptLanguageNone) { 1505 1506 PlatformSP platform_sp(target->GetPlatform()); 1507 1508 if (!platform_sp) { 1509 error.SetErrorString("invalid Platform"); 1510 return false; 1511 } 1512 1513 FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources( 1514 target, *this, feedback_stream); 1515 1516 const uint32_t num_specs = file_specs.GetSize(); 1517 if (num_specs) { 1518 ScriptInterpreter *script_interpreter = 1519 debugger.GetCommandInterpreter().GetScriptInterpreter(); 1520 if (script_interpreter) { 1521 for (uint32_t i = 0; i < num_specs; ++i) { 1522 FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i)); 1523 if (scripting_fspec && scripting_fspec.Exists()) { 1524 if (should_load == eLoadScriptFromSymFileWarn) { 1525 if (feedback_stream) 1526 feedback_stream->Printf( 1527 "warning: '%s' contains a debug script. To run this script " 1528 "in " 1529 "this debug session:\n\n command script import " 1530 "\"%s\"\n\n" 1531 "To run all discovered debug scripts in this session:\n\n" 1532 " settings set target.load-script-from-symbol-file " 1533 "true\n", 1534 GetFileSpec().GetFileNameStrippingExtension().GetCString(), 1535 scripting_fspec.GetPath().c_str()); 1536 return false; 1537 } 1538 StreamString scripting_stream; 1539 scripting_fspec.Dump(&scripting_stream); 1540 const bool can_reload = true; 1541 const bool init_lldb_globals = false; 1542 bool did_load = script_interpreter->LoadScriptingModule( 1543 scripting_stream.GetData(), can_reload, init_lldb_globals, 1544 error); 1545 if (!did_load) 1546 return false; 1547 } 1548 } 1549 } else { 1550 error.SetErrorString("invalid ScriptInterpreter"); 1551 return false; 1552 } 1553 } 1554 } 1555 return true; 1556 } 1557 1558 bool Module::SetArchitecture(const ArchSpec &new_arch) { 1559 if (!m_arch.IsValid()) { 1560 m_arch = new_arch; 1561 return true; 1562 } 1563 return m_arch.IsCompatibleMatch(new_arch); 1564 } 1565 1566 bool Module::SetLoadAddress(Target &target, lldb::addr_t value, 1567 bool value_is_offset, bool &changed) { 1568 ObjectFile *object_file = GetObjectFile(); 1569 if (object_file != nullptr) { 1570 changed = object_file->SetLoadAddress(target, value, value_is_offset); 1571 return true; 1572 } else { 1573 changed = false; 1574 } 1575 return false; 1576 } 1577 1578 bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) { 1579 const UUID &uuid = module_ref.GetUUID(); 1580 1581 if (uuid.IsValid()) { 1582 // If the UUID matches, then nothing more needs to match... 1583 return (uuid == GetUUID()); 1584 } 1585 1586 const FileSpec &file_spec = module_ref.GetFileSpec(); 1587 if (file_spec) { 1588 if (!FileSpec::Equal(file_spec, m_file, (bool)file_spec.GetDirectory()) && 1589 !FileSpec::Equal(file_spec, m_platform_file, 1590 (bool)file_spec.GetDirectory())) 1591 return false; 1592 } 1593 1594 const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec(); 1595 if (platform_file_spec) { 1596 if (!FileSpec::Equal(platform_file_spec, GetPlatformFileSpec(), 1597 (bool)platform_file_spec.GetDirectory())) 1598 return false; 1599 } 1600 1601 const ArchSpec &arch = module_ref.GetArchitecture(); 1602 if (arch.IsValid()) { 1603 if (!m_arch.IsCompatibleMatch(arch)) 1604 return false; 1605 } 1606 1607 const ConstString &object_name = module_ref.GetObjectName(); 1608 if (object_name) { 1609 if (object_name != GetObjectName()) 1610 return false; 1611 } 1612 return true; 1613 } 1614 1615 bool Module::FindSourceFile(const FileSpec &orig_spec, 1616 FileSpec &new_spec) const { 1617 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1618 return m_source_mappings.FindFile(orig_spec, new_spec); 1619 } 1620 1621 bool Module::RemapSourceFile(llvm::StringRef path, 1622 std::string &new_path) const { 1623 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1624 return m_source_mappings.RemapPath(path, new_path); 1625 } 1626 1627 uint32_t Module::GetVersion(uint32_t *versions, uint32_t num_versions) { 1628 ObjectFile *obj_file = GetObjectFile(); 1629 if (obj_file) 1630 return obj_file->GetVersion(versions, num_versions); 1631 1632 if (versions != nullptr && num_versions != 0) { 1633 for (uint32_t i = 0; i < num_versions; ++i) 1634 versions[i] = LLDB_INVALID_MODULE_VERSION; 1635 } 1636 return 0; 1637 } 1638 1639 ModuleSP 1640 Module::CreateJITModule(const lldb::ObjectFileJITDelegateSP &delegate_sp) { 1641 if (delegate_sp) { 1642 // Must create a module and place it into a shared pointer before 1643 // we can create an object file since it has a std::weak_ptr back 1644 // to the module, so we need to control the creation carefully in 1645 // this static function 1646 ModuleSP module_sp(new Module()); 1647 module_sp->m_objfile_sp.reset(new ObjectFileJIT(module_sp, delegate_sp)); 1648 if (module_sp->m_objfile_sp) { 1649 // Once we get the object file, update our module with the object file's 1650 // architecture since it might differ in vendor/os if some parts were 1651 // unknown. 1652 module_sp->m_objfile_sp->GetArchitecture(module_sp->m_arch); 1653 } 1654 return module_sp; 1655 } 1656 return ModuleSP(); 1657 } 1658 1659 bool Module::GetIsDynamicLinkEditor() { 1660 ObjectFile *obj_file = GetObjectFile(); 1661 1662 if (obj_file) 1663 return obj_file->GetIsDynamicLinkEditor(); 1664 1665 return false; 1666 } 1667 1668 Error Module::LoadInMemory(Target &target) { 1669 return m_objfile_sp->LoadInMemory(target); 1670 } 1671