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