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) { 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_class); 1013 num_matches = typesmap.GetSize(); 1014 } else { 1015 num_matches = FindTypes_Impl(sc, name, nullptr, append, max_matches, 1016 searched_symbol_files, typesmap); 1017 } 1018 } 1019 if (num_matches > 0) 1020 sc.SortTypeList(typesmap, types); 1021 return num_matches; 1022 } 1023 1024 SymbolVendor *Module::GetSymbolVendor(bool can_create, 1025 lldb_private::Stream *feedback_strm) { 1026 if (!m_did_load_symbol_vendor.load()) { 1027 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1028 if (!m_did_load_symbol_vendor.load() && can_create) { 1029 ObjectFile *obj_file = GetObjectFile(); 1030 if (obj_file != nullptr) { 1031 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 1032 Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION); 1033 m_symfile_ap.reset( 1034 SymbolVendor::FindPlugin(shared_from_this(), feedback_strm)); 1035 m_did_load_symbol_vendor = true; 1036 } 1037 } 1038 } 1039 return m_symfile_ap.get(); 1040 } 1041 1042 void Module::SetFileSpecAndObjectName(const FileSpec &file, 1043 const ConstString &object_name) { 1044 // Container objects whose paths do not specify a file directly can call this 1045 // function to correct the file and object names. 1046 m_file = file; 1047 m_mod_time = FileSystem::GetModificationTime(file); 1048 m_object_name = object_name; 1049 } 1050 1051 const ArchSpec &Module::GetArchitecture() const { return m_arch; } 1052 1053 std::string Module::GetSpecificationDescription() const { 1054 std::string spec(GetFileSpec().GetPath()); 1055 if (m_object_name) { 1056 spec += '('; 1057 spec += m_object_name.GetCString(); 1058 spec += ')'; 1059 } 1060 return spec; 1061 } 1062 1063 void Module::GetDescription(Stream *s, lldb::DescriptionLevel level) { 1064 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1065 1066 if (level >= eDescriptionLevelFull) { 1067 if (m_arch.IsValid()) 1068 s->Printf("(%s) ", m_arch.GetArchitectureName()); 1069 } 1070 1071 if (level == eDescriptionLevelBrief) { 1072 const char *filename = m_file.GetFilename().GetCString(); 1073 if (filename) 1074 s->PutCString(filename); 1075 } else { 1076 char path[PATH_MAX]; 1077 if (m_file.GetPath(path, sizeof(path))) 1078 s->PutCString(path); 1079 } 1080 1081 const char *object_name = m_object_name.GetCString(); 1082 if (object_name) 1083 s->Printf("(%s)", object_name); 1084 } 1085 1086 void Module::ReportError(const char *format, ...) { 1087 if (format && format[0]) { 1088 StreamString strm; 1089 strm.PutCString("error: "); 1090 GetDescription(&strm, lldb::eDescriptionLevelBrief); 1091 strm.PutChar(' '); 1092 va_list args; 1093 va_start(args, format); 1094 strm.PrintfVarArg(format, args); 1095 va_end(args); 1096 1097 const int format_len = strlen(format); 1098 if (format_len > 0) { 1099 const char last_char = format[format_len - 1]; 1100 if (last_char != '\n' || last_char != '\r') 1101 strm.EOL(); 1102 } 1103 Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData()); 1104 } 1105 } 1106 1107 bool Module::FileHasChanged() const { 1108 if (!m_file_has_changed) 1109 m_file_has_changed = 1110 (FileSystem::GetModificationTime(m_file) != m_mod_time); 1111 return m_file_has_changed; 1112 } 1113 1114 void Module::ReportErrorIfModifyDetected(const char *format, ...) { 1115 if (!m_first_file_changed_log) { 1116 if (FileHasChanged()) { 1117 m_first_file_changed_log = true; 1118 if (format) { 1119 StreamString strm; 1120 strm.PutCString("error: the object file "); 1121 GetDescription(&strm, lldb::eDescriptionLevelFull); 1122 strm.PutCString(" has been modified\n"); 1123 1124 va_list args; 1125 va_start(args, format); 1126 strm.PrintfVarArg(format, args); 1127 va_end(args); 1128 1129 const int format_len = strlen(format); 1130 if (format_len > 0) { 1131 const char last_char = format[format_len - 1]; 1132 if (last_char != '\n' || last_char != '\r') 1133 strm.EOL(); 1134 } 1135 strm.PutCString("The debug session should be aborted as the original " 1136 "debug information has been overwritten.\n"); 1137 Host::SystemLog(Host::eSystemLogError, "%s", strm.GetData()); 1138 } 1139 } 1140 } 1141 } 1142 1143 void Module::ReportWarning(const char *format, ...) { 1144 if (format && format[0]) { 1145 StreamString strm; 1146 strm.PutCString("warning: "); 1147 GetDescription(&strm, lldb::eDescriptionLevelFull); 1148 strm.PutChar(' '); 1149 1150 va_list args; 1151 va_start(args, format); 1152 strm.PrintfVarArg(format, args); 1153 va_end(args); 1154 1155 const int format_len = strlen(format); 1156 if (format_len > 0) { 1157 const char last_char = format[format_len - 1]; 1158 if (last_char != '\n' || last_char != '\r') 1159 strm.EOL(); 1160 } 1161 Host::SystemLog(Host::eSystemLogWarning, "%s", strm.GetData()); 1162 } 1163 } 1164 1165 void Module::LogMessage(Log *log, const char *format, ...) { 1166 if (log != nullptr) { 1167 StreamString log_message; 1168 GetDescription(&log_message, lldb::eDescriptionLevelFull); 1169 log_message.PutCString(": "); 1170 va_list args; 1171 va_start(args, format); 1172 log_message.PrintfVarArg(format, args); 1173 va_end(args); 1174 log->PutCString(log_message.GetData()); 1175 } 1176 } 1177 1178 void Module::LogMessageVerboseBacktrace(Log *log, const char *format, ...) { 1179 if (log != nullptr) { 1180 StreamString log_message; 1181 GetDescription(&log_message, lldb::eDescriptionLevelFull); 1182 log_message.PutCString(": "); 1183 va_list args; 1184 va_start(args, format); 1185 log_message.PrintfVarArg(format, args); 1186 va_end(args); 1187 if (log->GetVerbose()) { 1188 std::string back_trace; 1189 llvm::raw_string_ostream stream(back_trace); 1190 llvm::sys::PrintStackTrace(stream); 1191 log_message.PutCString(back_trace); 1192 } 1193 log->PutCString(log_message.GetData()); 1194 } 1195 } 1196 1197 void Module::Dump(Stream *s) { 1198 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1199 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this); 1200 s->Indent(); 1201 s->Printf("Module %s%s%s%s\n", m_file.GetPath().c_str(), 1202 m_object_name ? "(" : "", 1203 m_object_name ? m_object_name.GetCString() : "", 1204 m_object_name ? ")" : ""); 1205 1206 s->IndentMore(); 1207 1208 ObjectFile *objfile = GetObjectFile(); 1209 if (objfile) 1210 objfile->Dump(s); 1211 1212 SymbolVendor *symbols = GetSymbolVendor(); 1213 if (symbols) 1214 symbols->Dump(s); 1215 1216 s->IndentLess(); 1217 } 1218 1219 TypeList *Module::GetTypeList() { 1220 SymbolVendor *symbols = GetSymbolVendor(); 1221 if (symbols) 1222 return &symbols->GetTypeList(); 1223 return nullptr; 1224 } 1225 1226 const ConstString &Module::GetObjectName() const { return m_object_name; } 1227 1228 ObjectFile *Module::GetObjectFile() { 1229 if (!m_did_load_objfile.load()) { 1230 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1231 if (!m_did_load_objfile.load()) { 1232 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 1233 Timer scoped_timer(func_cat, "Module::GetObjectFile () module = %s", 1234 GetFileSpec().GetFilename().AsCString("")); 1235 DataBufferSP data_sp; 1236 lldb::offset_t data_offset = 0; 1237 const lldb::offset_t file_size = m_file.GetByteSize(); 1238 if (file_size > m_object_offset) { 1239 m_did_load_objfile = true; 1240 m_objfile_sp = ObjectFile::FindPlugin( 1241 shared_from_this(), &m_file, m_object_offset, 1242 file_size - m_object_offset, data_sp, data_offset); 1243 if (m_objfile_sp) { 1244 // Once we get the object file, update our module with the object 1245 // file's architecture since it might differ in vendor/os if some 1246 // parts were unknown. But since the matching arch might already be 1247 // more specific than the generic COFF architecture, only merge in 1248 // those values that overwrite unspecified unknown values. 1249 ArchSpec new_arch; 1250 m_objfile_sp->GetArchitecture(new_arch); 1251 m_arch.MergeFrom(new_arch); 1252 } else { 1253 ReportError("failed to load objfile for %s", 1254 GetFileSpec().GetPath().c_str()); 1255 } 1256 } 1257 } 1258 } 1259 return m_objfile_sp.get(); 1260 } 1261 1262 SectionList *Module::GetSectionList() { 1263 // Populate m_sections_ap with sections from objfile. 1264 if (!m_sections_ap) { 1265 ObjectFile *obj_file = GetObjectFile(); 1266 if (obj_file != nullptr) 1267 obj_file->CreateSections(*GetUnifiedSectionList()); 1268 } 1269 return m_sections_ap.get(); 1270 } 1271 1272 void Module::SectionFileAddressesChanged() { 1273 ObjectFile *obj_file = GetObjectFile(); 1274 if (obj_file) 1275 obj_file->SectionFileAddressesChanged(); 1276 SymbolVendor *sym_vendor = GetSymbolVendor(); 1277 if (sym_vendor != nullptr) 1278 sym_vendor->SectionFileAddressesChanged(); 1279 } 1280 1281 SectionList *Module::GetUnifiedSectionList() { 1282 if (!m_sections_ap) 1283 m_sections_ap = llvm::make_unique<SectionList>(); 1284 return m_sections_ap.get(); 1285 } 1286 1287 const Symbol *Module::FindFirstSymbolWithNameAndType(const ConstString &name, 1288 SymbolType symbol_type) { 1289 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 1290 Timer scoped_timer( 1291 func_cat, "Module::FindFirstSymbolWithNameAndType (name = %s, type = %i)", 1292 name.AsCString(), symbol_type); 1293 SymbolVendor *sym_vendor = GetSymbolVendor(); 1294 if (sym_vendor) { 1295 Symtab *symtab = sym_vendor->GetSymtab(); 1296 if (symtab) 1297 return symtab->FindFirstSymbolWithNameAndType( 1298 name, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny); 1299 } 1300 return nullptr; 1301 } 1302 void Module::SymbolIndicesToSymbolContextList( 1303 Symtab *symtab, std::vector<uint32_t> &symbol_indexes, 1304 SymbolContextList &sc_list) { 1305 // No need to protect this call using m_mutex all other method calls are 1306 // already thread safe. 1307 1308 size_t num_indices = symbol_indexes.size(); 1309 if (num_indices > 0) { 1310 SymbolContext sc; 1311 CalculateSymbolContext(&sc); 1312 for (size_t i = 0; i < num_indices; i++) { 1313 sc.symbol = symtab->SymbolAtIndex(symbol_indexes[i]); 1314 if (sc.symbol) 1315 sc_list.Append(sc); 1316 } 1317 } 1318 } 1319 1320 size_t Module::FindFunctionSymbols(const ConstString &name, 1321 uint32_t name_type_mask, 1322 SymbolContextList &sc_list) { 1323 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 1324 Timer scoped_timer(func_cat, 1325 "Module::FindSymbolsFunctions (name = %s, mask = 0x%8.8x)", 1326 name.AsCString(), name_type_mask); 1327 SymbolVendor *sym_vendor = GetSymbolVendor(); 1328 if (sym_vendor) { 1329 Symtab *symtab = sym_vendor->GetSymtab(); 1330 if (symtab) 1331 return symtab->FindFunctionSymbols(name, name_type_mask, sc_list); 1332 } 1333 return 0; 1334 } 1335 1336 size_t Module::FindSymbolsWithNameAndType(const ConstString &name, 1337 SymbolType symbol_type, 1338 SymbolContextList &sc_list) { 1339 // No need to protect this call using m_mutex all other method calls are 1340 // already thread safe. 1341 1342 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 1343 Timer scoped_timer( 1344 func_cat, "Module::FindSymbolsWithNameAndType (name = %s, type = %i)", 1345 name.AsCString(), symbol_type); 1346 const size_t initial_size = sc_list.GetSize(); 1347 SymbolVendor *sym_vendor = GetSymbolVendor(); 1348 if (sym_vendor) { 1349 Symtab *symtab = sym_vendor->GetSymtab(); 1350 if (symtab) { 1351 std::vector<uint32_t> symbol_indexes; 1352 symtab->FindAllSymbolsWithNameAndType(name, symbol_type, symbol_indexes); 1353 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list); 1354 } 1355 } 1356 return sc_list.GetSize() - initial_size; 1357 } 1358 1359 size_t Module::FindSymbolsMatchingRegExAndType(const RegularExpression ®ex, 1360 SymbolType symbol_type, 1361 SymbolContextList &sc_list) { 1362 // No need to protect this call using m_mutex all other method calls are 1363 // already thread safe. 1364 1365 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 1366 Timer scoped_timer( 1367 func_cat, 1368 "Module::FindSymbolsMatchingRegExAndType (regex = %s, type = %i)", 1369 regex.GetText().str().c_str(), symbol_type); 1370 const size_t initial_size = sc_list.GetSize(); 1371 SymbolVendor *sym_vendor = GetSymbolVendor(); 1372 if (sym_vendor) { 1373 Symtab *symtab = sym_vendor->GetSymtab(); 1374 if (symtab) { 1375 std::vector<uint32_t> symbol_indexes; 1376 symtab->FindAllSymbolsMatchingRexExAndType( 1377 regex, symbol_type, Symtab::eDebugAny, Symtab::eVisibilityAny, 1378 symbol_indexes); 1379 SymbolIndicesToSymbolContextList(symtab, symbol_indexes, sc_list); 1380 } 1381 } 1382 return sc_list.GetSize() - initial_size; 1383 } 1384 1385 void Module::PreloadSymbols() { 1386 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1387 SymbolVendor * sym_vendor = GetSymbolVendor(); 1388 if (!sym_vendor) { 1389 return; 1390 } 1391 // Prime the symbol file first, since it adds symbols to the symbol table. 1392 if (SymbolFile *symbol_file = sym_vendor->GetSymbolFile()) { 1393 symbol_file->PreloadSymbols(); 1394 } 1395 // Now we can prime the symbol table. 1396 if (Symtab * symtab = sym_vendor->GetSymtab()) { 1397 symtab->PreloadSymbols(); 1398 } 1399 } 1400 1401 void Module::SetSymbolFileFileSpec(const FileSpec &file) { 1402 if (!file.Exists()) 1403 return; 1404 if (m_symfile_ap) { 1405 // Remove any sections in the unified section list that come from the 1406 // current symbol vendor. 1407 SectionList *section_list = GetSectionList(); 1408 SymbolFile *symbol_file = m_symfile_ap->GetSymbolFile(); 1409 if (section_list && symbol_file) { 1410 ObjectFile *obj_file = symbol_file->GetObjectFile(); 1411 // Make sure we have an object file and that the symbol vendor's objfile 1412 // isn't the same as the module's objfile before we remove any sections 1413 // for 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 of a full path to the symbol file within the bundle 1429 // ("/tmp/a.out.dSYM/Contents/Resources/DWARF/a.out"). So we need to 1430 // check this 1431 1432 if (llvm::sys::fs::is_directory(file.GetPath())) { 1433 std::string new_path(file.GetPath()); 1434 std::string old_path(obj_file->GetFileSpec().GetPath()); 1435 if (old_path.find(new_path) == 0) { 1436 // We specified the same bundle as the symbol file that we already 1437 // have 1438 return; 1439 } 1440 } 1441 1442 if (obj_file != m_objfile_sp.get()) { 1443 size_t num_sections = section_list->GetNumSections(0); 1444 for (size_t idx = num_sections; idx > 0; --idx) { 1445 lldb::SectionSP section_sp( 1446 section_list->GetSectionAtIndex(idx - 1)); 1447 if (section_sp->GetObjectFile() == obj_file) { 1448 section_list->DeleteSection(idx - 1); 1449 } 1450 } 1451 } 1452 } 1453 } 1454 // Keep all old symbol files around in case there are any lingering type 1455 // references in any SBValue objects that might have been handed out. 1456 m_old_symfiles.push_back(std::move(m_symfile_ap)); 1457 } 1458 m_symfile_spec = file; 1459 m_symfile_ap.reset(); 1460 m_did_load_symbol_vendor = false; 1461 } 1462 1463 bool Module::IsExecutable() { 1464 if (GetObjectFile() == nullptr) 1465 return false; 1466 else 1467 return GetObjectFile()->IsExecutable(); 1468 } 1469 1470 bool Module::IsLoadedInTarget(Target *target) { 1471 ObjectFile *obj_file = GetObjectFile(); 1472 if (obj_file) { 1473 SectionList *sections = GetSectionList(); 1474 if (sections != nullptr) { 1475 size_t num_sections = sections->GetSize(); 1476 for (size_t sect_idx = 0; sect_idx < num_sections; sect_idx++) { 1477 SectionSP section_sp = sections->GetSectionAtIndex(sect_idx); 1478 if (section_sp->GetLoadBaseAddress(target) != LLDB_INVALID_ADDRESS) { 1479 return true; 1480 } 1481 } 1482 } 1483 } 1484 return false; 1485 } 1486 1487 bool Module::LoadScriptingResourceInTarget(Target *target, Status &error, 1488 Stream *feedback_stream) { 1489 if (!target) { 1490 error.SetErrorString("invalid destination Target"); 1491 return false; 1492 } 1493 1494 LoadScriptFromSymFile should_load = 1495 target->TargetProperties::GetLoadScriptFromSymbolFile(); 1496 1497 if (should_load == eLoadScriptFromSymFileFalse) 1498 return false; 1499 1500 Debugger &debugger = target->GetDebugger(); 1501 const ScriptLanguage script_language = debugger.GetScriptLanguage(); 1502 if (script_language != eScriptLanguageNone) { 1503 1504 PlatformSP platform_sp(target->GetPlatform()); 1505 1506 if (!platform_sp) { 1507 error.SetErrorString("invalid Platform"); 1508 return false; 1509 } 1510 1511 FileSpecList file_specs = platform_sp->LocateExecutableScriptingResources( 1512 target, *this, feedback_stream); 1513 1514 const uint32_t num_specs = file_specs.GetSize(); 1515 if (num_specs) { 1516 ScriptInterpreter *script_interpreter = 1517 debugger.GetCommandInterpreter().GetScriptInterpreter(); 1518 if (script_interpreter) { 1519 for (uint32_t i = 0; i < num_specs; ++i) { 1520 FileSpec scripting_fspec(file_specs.GetFileSpecAtIndex(i)); 1521 if (scripting_fspec && scripting_fspec.Exists()) { 1522 if (should_load == eLoadScriptFromSymFileWarn) { 1523 if (feedback_stream) 1524 feedback_stream->Printf( 1525 "warning: '%s' contains a debug script. To run this script " 1526 "in " 1527 "this debug session:\n\n command script import " 1528 "\"%s\"\n\n" 1529 "To run all discovered debug scripts in this session:\n\n" 1530 " settings set target.load-script-from-symbol-file " 1531 "true\n", 1532 GetFileSpec().GetFileNameStrippingExtension().GetCString(), 1533 scripting_fspec.GetPath().c_str()); 1534 return false; 1535 } 1536 StreamString scripting_stream; 1537 scripting_fspec.Dump(&scripting_stream); 1538 const bool can_reload = true; 1539 const bool init_lldb_globals = false; 1540 bool did_load = script_interpreter->LoadScriptingModule( 1541 scripting_stream.GetData(), can_reload, init_lldb_globals, 1542 error); 1543 if (!did_load) 1544 return false; 1545 } 1546 } 1547 } else { 1548 error.SetErrorString("invalid ScriptInterpreter"); 1549 return false; 1550 } 1551 } 1552 } 1553 return true; 1554 } 1555 1556 bool Module::SetArchitecture(const ArchSpec &new_arch) { 1557 if (!m_arch.IsValid()) { 1558 m_arch = new_arch; 1559 return true; 1560 } 1561 return m_arch.IsCompatibleMatch(new_arch); 1562 } 1563 1564 bool Module::SetLoadAddress(Target &target, lldb::addr_t value, 1565 bool value_is_offset, bool &changed) { 1566 ObjectFile *object_file = GetObjectFile(); 1567 if (object_file != nullptr) { 1568 changed = object_file->SetLoadAddress(target, value, value_is_offset); 1569 return true; 1570 } else { 1571 changed = false; 1572 } 1573 return false; 1574 } 1575 1576 bool Module::MatchesModuleSpec(const ModuleSpec &module_ref) { 1577 const UUID &uuid = module_ref.GetUUID(); 1578 1579 if (uuid.IsValid()) { 1580 // If the UUID matches, then nothing more needs to match... 1581 return (uuid == GetUUID()); 1582 } 1583 1584 const FileSpec &file_spec = module_ref.GetFileSpec(); 1585 if (file_spec) { 1586 if (!FileSpec::Equal(file_spec, m_file, (bool)file_spec.GetDirectory()) && 1587 !FileSpec::Equal(file_spec, m_platform_file, 1588 (bool)file_spec.GetDirectory())) 1589 return false; 1590 } 1591 1592 const FileSpec &platform_file_spec = module_ref.GetPlatformFileSpec(); 1593 if (platform_file_spec) { 1594 if (!FileSpec::Equal(platform_file_spec, GetPlatformFileSpec(), 1595 (bool)platform_file_spec.GetDirectory())) 1596 return false; 1597 } 1598 1599 const ArchSpec &arch = module_ref.GetArchitecture(); 1600 if (arch.IsValid()) { 1601 if (!m_arch.IsCompatibleMatch(arch)) 1602 return false; 1603 } 1604 1605 const ConstString &object_name = module_ref.GetObjectName(); 1606 if (object_name) { 1607 if (object_name != GetObjectName()) 1608 return false; 1609 } 1610 return true; 1611 } 1612 1613 bool Module::FindSourceFile(const FileSpec &orig_spec, 1614 FileSpec &new_spec) const { 1615 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1616 return m_source_mappings.FindFile(orig_spec, new_spec); 1617 } 1618 1619 bool Module::RemapSourceFile(llvm::StringRef path, 1620 std::string &new_path) const { 1621 std::lock_guard<std::recursive_mutex> guard(m_mutex); 1622 return m_source_mappings.RemapPath(path, new_path); 1623 } 1624 1625 uint32_t Module::GetVersion(uint32_t *versions, uint32_t num_versions) { 1626 ObjectFile *obj_file = GetObjectFile(); 1627 if (obj_file) 1628 return obj_file->GetVersion(versions, num_versions); 1629 1630 if (versions != nullptr && num_versions != 0) { 1631 for (uint32_t i = 0; i < num_versions; ++i) 1632 versions[i] = LLDB_INVALID_MODULE_VERSION; 1633 } 1634 return 0; 1635 } 1636 1637 ModuleSP 1638 Module::CreateJITModule(const lldb::ObjectFileJITDelegateSP &delegate_sp) { 1639 if (delegate_sp) { 1640 // Must create a module and place it into a shared pointer before we can 1641 // create an object file since it has a std::weak_ptr back to the module, 1642 // so we need to control the creation carefully in this static function 1643 ModuleSP module_sp(new Module()); 1644 module_sp->m_objfile_sp = 1645 std::make_shared<ObjectFileJIT>(module_sp, delegate_sp); 1646 if (module_sp->m_objfile_sp) { 1647 // Once we get the object file, update our module with the object file's 1648 // architecture since it might differ in vendor/os if some parts were 1649 // unknown. 1650 module_sp->m_objfile_sp->GetArchitecture(module_sp->m_arch); 1651 } 1652 return module_sp; 1653 } 1654 return ModuleSP(); 1655 } 1656 1657 bool Module::GetIsDynamicLinkEditor() { 1658 ObjectFile *obj_file = GetObjectFile(); 1659 1660 if (obj_file) 1661 return obj_file->GetIsDynamicLinkEditor(); 1662 1663 return false; 1664 } 1665