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