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