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