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