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