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