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