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