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