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