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