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