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