Function.cpp revision 360784
1//===-- Function.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/Symbol/Function.h" 10#include "lldb/Core/Disassembler.h" 11#include "lldb/Core/Module.h" 12#include "lldb/Core/ModuleList.h" 13#include "lldb/Core/Section.h" 14#include "lldb/Host/Host.h" 15#include "lldb/Symbol/CompileUnit.h" 16#include "lldb/Symbol/CompilerType.h" 17#include "lldb/Symbol/LineTable.h" 18#include "lldb/Symbol/SymbolFile.h" 19#include "lldb/Target/Language.h" 20#include "lldb/Target/Target.h" 21#include "lldb/Utility/Log.h" 22#include "llvm/Support/Casting.h" 23 24using namespace lldb; 25using namespace lldb_private; 26 27// Basic function information is contained in the FunctionInfo class. It is 28// designed to contain the name, linkage name, and declaration location. 29FunctionInfo::FunctionInfo(const char *name, const Declaration *decl_ptr) 30 : m_name(name), m_declaration(decl_ptr) {} 31 32FunctionInfo::FunctionInfo(ConstString name, const Declaration *decl_ptr) 33 : m_name(name), m_declaration(decl_ptr) {} 34 35FunctionInfo::~FunctionInfo() {} 36 37void FunctionInfo::Dump(Stream *s, bool show_fullpaths) const { 38 if (m_name) 39 *s << ", name = \"" << m_name << "\""; 40 m_declaration.Dump(s, show_fullpaths); 41} 42 43int FunctionInfo::Compare(const FunctionInfo &a, const FunctionInfo &b) { 44 int result = ConstString::Compare(a.GetName(), b.GetName()); 45 if (result) 46 return result; 47 48 return Declaration::Compare(a.m_declaration, b.m_declaration); 49} 50 51Declaration &FunctionInfo::GetDeclaration() { return m_declaration; } 52 53const Declaration &FunctionInfo::GetDeclaration() const { 54 return m_declaration; 55} 56 57ConstString FunctionInfo::GetName() const { return m_name; } 58 59size_t FunctionInfo::MemorySize() const { 60 return m_name.MemorySize() + m_declaration.MemorySize(); 61} 62 63InlineFunctionInfo::InlineFunctionInfo(const char *name, 64 llvm::StringRef mangled, 65 const Declaration *decl_ptr, 66 const Declaration *call_decl_ptr) 67 : FunctionInfo(name, decl_ptr), m_mangled(mangled), 68 m_call_decl(call_decl_ptr) {} 69 70InlineFunctionInfo::InlineFunctionInfo(ConstString name, 71 const Mangled &mangled, 72 const Declaration *decl_ptr, 73 const Declaration *call_decl_ptr) 74 : FunctionInfo(name, decl_ptr), m_mangled(mangled), 75 m_call_decl(call_decl_ptr) {} 76 77InlineFunctionInfo::~InlineFunctionInfo() {} 78 79void InlineFunctionInfo::Dump(Stream *s, bool show_fullpaths) const { 80 FunctionInfo::Dump(s, show_fullpaths); 81 if (m_mangled) 82 m_mangled.Dump(s); 83} 84 85void InlineFunctionInfo::DumpStopContext(Stream *s, 86 LanguageType language) const { 87 // s->Indent("[inlined] "); 88 s->Indent(); 89 if (m_mangled) 90 s->PutCString(m_mangled.GetName(language).AsCString()); 91 else 92 s->PutCString(m_name.AsCString()); 93} 94 95ConstString InlineFunctionInfo::GetName(LanguageType language) const { 96 if (m_mangled) 97 return m_mangled.GetName(language); 98 return m_name; 99} 100 101ConstString InlineFunctionInfo::GetDisplayName(LanguageType language) const { 102 if (m_mangled) 103 return m_mangled.GetDisplayDemangledName(language); 104 return m_name; 105} 106 107Declaration &InlineFunctionInfo::GetCallSite() { return m_call_decl; } 108 109const Declaration &InlineFunctionInfo::GetCallSite() const { 110 return m_call_decl; 111} 112 113Mangled &InlineFunctionInfo::GetMangled() { return m_mangled; } 114 115const Mangled &InlineFunctionInfo::GetMangled() const { return m_mangled; } 116 117size_t InlineFunctionInfo::MemorySize() const { 118 return FunctionInfo::MemorySize() + m_mangled.MemorySize(); 119} 120 121/// @name Call site related structures 122/// @{ 123 124lldb::addr_t CallEdge::GetReturnPCAddress(Function &caller, 125 Target &target) const { 126 const Address &base = caller.GetAddressRange().GetBaseAddress(); 127 return base.GetLoadAddress(&target) + return_pc; 128} 129 130void DirectCallEdge::ParseSymbolFileAndResolve(ModuleList &images) { 131 if (resolved) 132 return; 133 134 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 135 LLDB_LOG(log, "DirectCallEdge: Lazily parsing the call graph for {0}", 136 lazy_callee.symbol_name); 137 138 auto resolve_lazy_callee = [&]() -> Function * { 139 ConstString callee_name{lazy_callee.symbol_name}; 140 SymbolContextList sc_list; 141 images.FindFunctionSymbols(callee_name, eFunctionNameTypeAuto, sc_list); 142 size_t num_matches = sc_list.GetSize(); 143 if (num_matches == 0 || !sc_list[0].symbol) { 144 LLDB_LOG(log, 145 "DirectCallEdge: Found no symbols for {0}, cannot resolve it", 146 callee_name); 147 return nullptr; 148 } 149 Address callee_addr = sc_list[0].symbol->GetAddress(); 150 if (!callee_addr.IsValid()) { 151 LLDB_LOG(log, "DirectCallEdge: Invalid symbol address"); 152 return nullptr; 153 } 154 Function *f = callee_addr.CalculateSymbolContextFunction(); 155 if (!f) { 156 LLDB_LOG(log, "DirectCallEdge: Could not find complete function"); 157 return nullptr; 158 } 159 return f; 160 }; 161 lazy_callee.def = resolve_lazy_callee(); 162 resolved = true; 163} 164 165Function *DirectCallEdge::GetCallee(ModuleList &images, ExecutionContext &) { 166 ParseSymbolFileAndResolve(images); 167 assert(resolved && "Did not resolve lazy callee"); 168 return lazy_callee.def; 169} 170 171Function *IndirectCallEdge::GetCallee(ModuleList &images, 172 ExecutionContext &exe_ctx) { 173 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 174 Status error; 175 Value callee_addr_val; 176 if (!call_target.Evaluate(&exe_ctx, exe_ctx.GetRegisterContext(), 177 /*loclist_base_addr=*/LLDB_INVALID_ADDRESS, 178 /*initial_value_ptr=*/nullptr, 179 /*object_address_ptr=*/nullptr, callee_addr_val, 180 &error)) { 181 LLDB_LOGF(log, "IndirectCallEdge: Could not evaluate expression: %s", 182 error.AsCString()); 183 return nullptr; 184 } 185 186 addr_t raw_addr = callee_addr_val.GetScalar().ULongLong(LLDB_INVALID_ADDRESS); 187 if (raw_addr == LLDB_INVALID_ADDRESS) { 188 LLDB_LOG(log, "IndirectCallEdge: Could not extract address from scalar"); 189 return nullptr; 190 } 191 192 Address callee_addr; 193 if (!exe_ctx.GetTargetPtr()->ResolveLoadAddress(raw_addr, callee_addr)) { 194 LLDB_LOG(log, "IndirectCallEdge: Could not resolve callee's load address"); 195 return nullptr; 196 } 197 198 Function *f = callee_addr.CalculateSymbolContextFunction(); 199 if (!f) { 200 LLDB_LOG(log, "IndirectCallEdge: Could not find complete function"); 201 return nullptr; 202 } 203 204 return f; 205} 206 207/// @} 208 209// 210Function::Function(CompileUnit *comp_unit, lldb::user_id_t func_uid, 211 lldb::user_id_t type_uid, const Mangled &mangled, Type *type, 212 const AddressRange &range) 213 : UserID(func_uid), m_comp_unit(comp_unit), m_type_uid(type_uid), 214 m_type(type), m_mangled(mangled), m_block(func_uid), m_range(range), 215 m_frame_base(), m_flags(), m_prologue_byte_size(0) { 216 m_block.SetParentScope(this); 217 assert(comp_unit != nullptr); 218} 219 220Function::~Function() {} 221 222void Function::GetStartLineSourceInfo(FileSpec &source_file, 223 uint32_t &line_no) { 224 line_no = 0; 225 source_file.Clear(); 226 227 if (m_comp_unit == nullptr) 228 return; 229 230 // Initialize m_type if it hasn't been initialized already 231 GetType(); 232 233 if (m_type != nullptr && m_type->GetDeclaration().GetLine() != 0) { 234 source_file = m_type->GetDeclaration().GetFile(); 235 line_no = m_type->GetDeclaration().GetLine(); 236 } else { 237 LineTable *line_table = m_comp_unit->GetLineTable(); 238 if (line_table == nullptr) 239 return; 240 241 LineEntry line_entry; 242 if (line_table->FindLineEntryByAddress(GetAddressRange().GetBaseAddress(), 243 line_entry, nullptr)) { 244 line_no = line_entry.line; 245 source_file = line_entry.file; 246 } 247 } 248} 249 250void Function::GetEndLineSourceInfo(FileSpec &source_file, uint32_t &line_no) { 251 line_no = 0; 252 source_file.Clear(); 253 254 // The -1 is kind of cheesy, but I want to get the last line entry for the 255 // given function, not the first entry of the next. 256 Address scratch_addr(GetAddressRange().GetBaseAddress()); 257 scratch_addr.SetOffset(scratch_addr.GetOffset() + 258 GetAddressRange().GetByteSize() - 1); 259 260 LineTable *line_table = m_comp_unit->GetLineTable(); 261 if (line_table == nullptr) 262 return; 263 264 LineEntry line_entry; 265 if (line_table->FindLineEntryByAddress(scratch_addr, line_entry, nullptr)) { 266 line_no = line_entry.line; 267 source_file = line_entry.file; 268 } 269} 270 271llvm::ArrayRef<std::unique_ptr<CallEdge>> Function::GetCallEdges() { 272 if (m_call_edges_resolved) 273 return m_call_edges; 274 275 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 276 LLDB_LOG(log, "GetCallEdges: Attempting to parse call site info for {0}", 277 GetDisplayName()); 278 279 m_call_edges_resolved = true; 280 281 // Find the SymbolFile which provided this function's definition. 282 Block &block = GetBlock(/*can_create*/true); 283 SymbolFile *sym_file = block.GetSymbolFile(); 284 if (!sym_file) 285 return llvm::None; 286 287 // Lazily read call site information from the SymbolFile. 288 m_call_edges = sym_file->ParseCallEdgesInFunction(GetID()); 289 290 // Sort the call edges to speed up return_pc lookups. 291 llvm::sort(m_call_edges.begin(), m_call_edges.end(), 292 [](const std::unique_ptr<CallEdge> &LHS, 293 const std::unique_ptr<CallEdge> &RHS) { 294 return LHS->GetUnresolvedReturnPCAddress() < 295 RHS->GetUnresolvedReturnPCAddress(); 296 }); 297 298 return m_call_edges; 299} 300 301llvm::ArrayRef<std::unique_ptr<CallEdge>> Function::GetTailCallingEdges() { 302 // Call edges are sorted by return PC, and tail calling edges have invalid 303 // return PCs. Find them at the end of the list. 304 return GetCallEdges().drop_until([](const std::unique_ptr<CallEdge> &edge) { 305 return edge->GetUnresolvedReturnPCAddress() == LLDB_INVALID_ADDRESS; 306 }); 307} 308 309CallEdge *Function::GetCallEdgeForReturnAddress(addr_t return_pc, 310 Target &target) { 311 auto edges = GetCallEdges(); 312 auto edge_it = 313 std::lower_bound(edges.begin(), edges.end(), return_pc, 314 [&](const std::unique_ptr<CallEdge> &edge, addr_t pc) { 315 return edge->GetReturnPCAddress(*this, target) < pc; 316 }); 317 if (edge_it == edges.end() || 318 edge_it->get()->GetReturnPCAddress(*this, target) != return_pc) 319 return nullptr; 320 return &const_cast<CallEdge &>(*edge_it->get()); 321} 322 323Block &Function::GetBlock(bool can_create) { 324 if (!m_block.BlockInfoHasBeenParsed() && can_create) { 325 ModuleSP module_sp = CalculateSymbolContextModule(); 326 if (module_sp) { 327 module_sp->GetSymbolFile()->ParseBlocksRecursive(*this); 328 } else { 329 Host::SystemLog(Host::eSystemLogError, 330 "error: unable to find module " 331 "shared pointer for function '%s' " 332 "in %s\n", 333 GetName().GetCString(), 334 m_comp_unit->GetPrimaryFile().GetPath().c_str()); 335 } 336 m_block.SetBlockInfoHasBeenParsed(true, true); 337 } 338 return m_block; 339} 340 341CompileUnit *Function::GetCompileUnit() { return m_comp_unit; } 342 343const CompileUnit *Function::GetCompileUnit() const { return m_comp_unit; } 344 345void Function::GetDescription(Stream *s, lldb::DescriptionLevel level, 346 Target *target) { 347 ConstString name = GetName(); 348 ConstString mangled = m_mangled.GetMangledName(); 349 350 *s << "id = " << (const UserID &)*this; 351 if (name) 352 *s << ", name = \"" << name.GetCString() << '"'; 353 if (mangled) 354 *s << ", mangled = \"" << mangled.GetCString() << '"'; 355 *s << ", range = "; 356 Address::DumpStyle fallback_style; 357 if (level == eDescriptionLevelVerbose) 358 fallback_style = Address::DumpStyleModuleWithFileAddress; 359 else 360 fallback_style = Address::DumpStyleFileAddress; 361 GetAddressRange().Dump(s, target, Address::DumpStyleLoadAddress, 362 fallback_style); 363} 364 365void Function::Dump(Stream *s, bool show_context) const { 366 s->Printf("%p: ", static_cast<const void *>(this)); 367 s->Indent(); 368 *s << "Function" << static_cast<const UserID &>(*this); 369 370 m_mangled.Dump(s); 371 372 if (m_type) 373 s->Printf(", type = %p", static_cast<void *>(m_type)); 374 else if (m_type_uid != LLDB_INVALID_UID) 375 s->Printf(", type_uid = 0x%8.8" PRIx64, m_type_uid); 376 377 s->EOL(); 378 // Dump the root object 379 if (m_block.BlockInfoHasBeenParsed()) 380 m_block.Dump(s, m_range.GetBaseAddress().GetFileAddress(), INT_MAX, 381 show_context); 382} 383 384void Function::CalculateSymbolContext(SymbolContext *sc) { 385 sc->function = this; 386 m_comp_unit->CalculateSymbolContext(sc); 387} 388 389ModuleSP Function::CalculateSymbolContextModule() { 390 SectionSP section_sp(m_range.GetBaseAddress().GetSection()); 391 if (section_sp) 392 return section_sp->GetModule(); 393 394 return this->GetCompileUnit()->GetModule(); 395} 396 397CompileUnit *Function::CalculateSymbolContextCompileUnit() { 398 return this->GetCompileUnit(); 399} 400 401Function *Function::CalculateSymbolContextFunction() { return this; } 402 403lldb::DisassemblerSP Function::GetInstructions(const ExecutionContext &exe_ctx, 404 const char *flavor, 405 bool prefer_file_cache) { 406 ModuleSP module_sp(GetAddressRange().GetBaseAddress().GetModule()); 407 if (module_sp) { 408 const bool prefer_file_cache = false; 409 return Disassembler::DisassembleRange(module_sp->GetArchitecture(), nullptr, 410 flavor, exe_ctx, GetAddressRange(), 411 prefer_file_cache); 412 } 413 return lldb::DisassemblerSP(); 414} 415 416bool Function::GetDisassembly(const ExecutionContext &exe_ctx, 417 const char *flavor, bool prefer_file_cache, 418 Stream &strm) { 419 lldb::DisassemblerSP disassembler_sp = 420 GetInstructions(exe_ctx, flavor, prefer_file_cache); 421 if (disassembler_sp) { 422 const bool show_address = true; 423 const bool show_bytes = false; 424 disassembler_sp->GetInstructionList().Dump(&strm, show_address, show_bytes, 425 &exe_ctx); 426 return true; 427 } 428 return false; 429} 430 431// Symbol * 432// Function::CalculateSymbolContextSymbol () 433//{ 434// return // TODO: find the symbol for the function??? 435//} 436 437void Function::DumpSymbolContext(Stream *s) { 438 m_comp_unit->DumpSymbolContext(s); 439 s->Printf(", Function{0x%8.8" PRIx64 "}", GetID()); 440} 441 442size_t Function::MemorySize() const { 443 size_t mem_size = sizeof(Function) + m_block.MemorySize(); 444 return mem_size; 445} 446 447bool Function::GetIsOptimized() { 448 bool result = false; 449 450 // Currently optimization is only indicted by the vendor extension 451 // DW_AT_APPLE_optimized which is set on a compile unit level. 452 if (m_comp_unit) { 453 result = m_comp_unit->GetIsOptimized(); 454 } 455 return result; 456} 457 458bool Function::IsTopLevelFunction() { 459 bool result = false; 460 461 if (Language *language = Language::FindPlugin(GetLanguage())) 462 result = language->IsTopLevelFunction(*this); 463 464 return result; 465} 466 467ConstString Function::GetDisplayName() const { 468 return m_mangled.GetDisplayDemangledName(GetLanguage()); 469} 470 471CompilerDeclContext Function::GetDeclContext() { 472 ModuleSP module_sp = CalculateSymbolContextModule(); 473 474 if (module_sp) { 475 if (SymbolFile *sym_file = module_sp->GetSymbolFile()) 476 return sym_file->GetDeclContextForUID(GetID()); 477 } 478 return CompilerDeclContext(); 479} 480 481Type *Function::GetType() { 482 if (m_type == nullptr) { 483 SymbolContext sc; 484 485 CalculateSymbolContext(&sc); 486 487 if (!sc.module_sp) 488 return nullptr; 489 490 SymbolFile *sym_file = sc.module_sp->GetSymbolFile(); 491 492 if (sym_file == nullptr) 493 return nullptr; 494 495 m_type = sym_file->ResolveTypeUID(m_type_uid); 496 } 497 return m_type; 498} 499 500const Type *Function::GetType() const { return m_type; } 501 502CompilerType Function::GetCompilerType() { 503 Type *function_type = GetType(); 504 if (function_type) 505 return function_type->GetFullCompilerType(); 506 return CompilerType(); 507} 508 509uint32_t Function::GetPrologueByteSize() { 510 if (m_prologue_byte_size == 0 && 511 m_flags.IsClear(flagsCalculatedPrologueSize)) { 512 m_flags.Set(flagsCalculatedPrologueSize); 513 LineTable *line_table = m_comp_unit->GetLineTable(); 514 uint32_t prologue_end_line_idx = 0; 515 516 if (line_table) { 517 LineEntry first_line_entry; 518 uint32_t first_line_entry_idx = UINT32_MAX; 519 if (line_table->FindLineEntryByAddress(GetAddressRange().GetBaseAddress(), 520 first_line_entry, 521 &first_line_entry_idx)) { 522 // Make sure the first line entry isn't already the end of the prologue 523 addr_t prologue_end_file_addr = LLDB_INVALID_ADDRESS; 524 addr_t line_zero_end_file_addr = LLDB_INVALID_ADDRESS; 525 526 if (first_line_entry.is_prologue_end) { 527 prologue_end_file_addr = 528 first_line_entry.range.GetBaseAddress().GetFileAddress(); 529 prologue_end_line_idx = first_line_entry_idx; 530 } else { 531 // Check the first few instructions and look for one that has 532 // is_prologue_end set to true. 533 const uint32_t last_line_entry_idx = first_line_entry_idx + 6; 534 for (uint32_t idx = first_line_entry_idx + 1; 535 idx < last_line_entry_idx; ++idx) { 536 LineEntry line_entry; 537 if (line_table->GetLineEntryAtIndex(idx, line_entry)) { 538 if (line_entry.is_prologue_end) { 539 prologue_end_file_addr = 540 line_entry.range.GetBaseAddress().GetFileAddress(); 541 prologue_end_line_idx = idx; 542 break; 543 } 544 } 545 } 546 } 547 548 // If we didn't find the end of the prologue in the line tables, then 549 // just use the end address of the first line table entry 550 if (prologue_end_file_addr == LLDB_INVALID_ADDRESS) { 551 // Check the first few instructions and look for one that has a line 552 // number that's different than the first entry. 553 uint32_t last_line_entry_idx = first_line_entry_idx + 6; 554 for (uint32_t idx = first_line_entry_idx + 1; 555 idx < last_line_entry_idx; ++idx) { 556 LineEntry line_entry; 557 if (line_table->GetLineEntryAtIndex(idx, line_entry)) { 558 if (line_entry.line != first_line_entry.line) { 559 prologue_end_file_addr = 560 line_entry.range.GetBaseAddress().GetFileAddress(); 561 prologue_end_line_idx = idx; 562 break; 563 } 564 } 565 } 566 567 if (prologue_end_file_addr == LLDB_INVALID_ADDRESS) { 568 prologue_end_file_addr = 569 first_line_entry.range.GetBaseAddress().GetFileAddress() + 570 first_line_entry.range.GetByteSize(); 571 prologue_end_line_idx = first_line_entry_idx; 572 } 573 } 574 575 const addr_t func_start_file_addr = 576 m_range.GetBaseAddress().GetFileAddress(); 577 const addr_t func_end_file_addr = 578 func_start_file_addr + m_range.GetByteSize(); 579 580 // Now calculate the offset to pass the subsequent line 0 entries. 581 uint32_t first_non_zero_line = prologue_end_line_idx; 582 while (true) { 583 LineEntry line_entry; 584 if (line_table->GetLineEntryAtIndex(first_non_zero_line, 585 line_entry)) { 586 if (line_entry.line != 0) 587 break; 588 } 589 if (line_entry.range.GetBaseAddress().GetFileAddress() >= 590 func_end_file_addr) 591 break; 592 593 first_non_zero_line++; 594 } 595 596 if (first_non_zero_line > prologue_end_line_idx) { 597 LineEntry first_non_zero_entry; 598 if (line_table->GetLineEntryAtIndex(first_non_zero_line, 599 first_non_zero_entry)) { 600 line_zero_end_file_addr = 601 first_non_zero_entry.range.GetBaseAddress().GetFileAddress(); 602 } 603 } 604 605 // Verify that this prologue end file address in the function's address 606 // range just to be sure 607 if (func_start_file_addr < prologue_end_file_addr && 608 prologue_end_file_addr < func_end_file_addr) { 609 m_prologue_byte_size = prologue_end_file_addr - func_start_file_addr; 610 } 611 612 if (prologue_end_file_addr < line_zero_end_file_addr && 613 line_zero_end_file_addr < func_end_file_addr) { 614 m_prologue_byte_size += 615 line_zero_end_file_addr - prologue_end_file_addr; 616 } 617 } 618 } 619 } 620 621 return m_prologue_byte_size; 622} 623 624lldb::LanguageType Function::GetLanguage() const { 625 lldb::LanguageType lang = m_mangled.GuessLanguage(); 626 if (lang != lldb::eLanguageTypeUnknown) 627 return lang; 628 629 if (m_comp_unit) 630 return m_comp_unit->GetLanguage(); 631 632 return lldb::eLanguageTypeUnknown; 633} 634 635ConstString Function::GetName() const { 636 LanguageType language = lldb::eLanguageTypeUnknown; 637 if (m_comp_unit) 638 language = m_comp_unit->GetLanguage(); 639 return m_mangled.GetName(language); 640} 641 642ConstString Function::GetNameNoArguments() const { 643 LanguageType language = lldb::eLanguageTypeUnknown; 644 if (m_comp_unit) 645 language = m_comp_unit->GetLanguage(); 646 return m_mangled.GetName(language, Mangled::ePreferDemangledWithoutArguments); 647} 648