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