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, 63 llvm::StringRef mangled, 64 const Declaration *decl_ptr, 65 const Declaration *call_decl_ptr) 66 : FunctionInfo(name, decl_ptr), m_mangled(mangled), 67 m_call_decl(call_decl_ptr) {} 68 69 InlineFunctionInfo::InlineFunctionInfo(ConstString name, 70 const Mangled &mangled, 71 const Declaration *decl_ptr, 72 const Declaration *call_decl_ptr) 73 : FunctionInfo(name, decl_ptr), m_mangled(mangled), 74 m_call_decl(call_decl_ptr) {} 75 76 InlineFunctionInfo::~InlineFunctionInfo() {} 77 78 int InlineFunctionInfo::Compare(const InlineFunctionInfo &a, 79 const InlineFunctionInfo &b) { 80 81 int result = FunctionInfo::Compare(a, b); 82 if (result) 83 return result; 84 // only compare the mangled names if both have them 85 return Mangled::Compare(a.m_mangled, a.m_mangled); 86 } 87 88 void InlineFunctionInfo::Dump(Stream *s, bool show_fullpaths) const { 89 FunctionInfo::Dump(s, show_fullpaths); 90 if (m_mangled) 91 m_mangled.Dump(s); 92 } 93 94 void InlineFunctionInfo::DumpStopContext(Stream *s, 95 LanguageType language) const { 96 // s->Indent("[inlined] "); 97 s->Indent(); 98 if (m_mangled) 99 s->PutCString(m_mangled.GetName(language).AsCString()); 100 else 101 s->PutCString(m_name.AsCString()); 102 } 103 104 ConstString InlineFunctionInfo::GetName(LanguageType language) const { 105 if (m_mangled) 106 return m_mangled.GetName(language); 107 return m_name; 108 } 109 110 ConstString InlineFunctionInfo::GetDisplayName(LanguageType language) const { 111 if (m_mangled) 112 return m_mangled.GetDisplayDemangledName(language); 113 return m_name; 114 } 115 116 Declaration &InlineFunctionInfo::GetCallSite() { return m_call_decl; } 117 118 const Declaration &InlineFunctionInfo::GetCallSite() const { 119 return m_call_decl; 120 } 121 122 Mangled &InlineFunctionInfo::GetMangled() { return m_mangled; } 123 124 const Mangled &InlineFunctionInfo::GetMangled() const { return m_mangled; } 125 126 size_t InlineFunctionInfo::MemorySize() const { 127 return FunctionInfo::MemorySize() + m_mangled.MemorySize(); 128 } 129 130 // 131 CallEdge::CallEdge(const char *symbol_name, lldb::addr_t return_pc, 132 CallSiteParameterArray parameters) 133 : return_pc(return_pc), parameters(std::move(parameters)), resolved(false) { 134 lazy_callee.symbol_name = symbol_name; 135 } 136 137 llvm::ArrayRef<CallSiteParameter> CallEdge::GetCallSiteParameters() const { 138 return parameters; 139 } 140 141 void CallEdge::ParseSymbolFileAndResolve(ModuleList &images) { 142 if (resolved) 143 return; 144 145 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 146 LLDB_LOG(log, "CallEdge: Lazily parsing the call graph for {0}", 147 lazy_callee.symbol_name); 148 149 auto resolve_lazy_callee = [&]() -> Function * { 150 ConstString callee_name{lazy_callee.symbol_name}; 151 SymbolContextList sc_list; 152 images.FindFunctionSymbols(callee_name, eFunctionNameTypeAuto, sc_list); 153 size_t num_matches = sc_list.GetSize(); 154 if (num_matches == 0 || !sc_list[0].symbol) { 155 LLDB_LOG(log, "CallEdge: Found no symbols for {0}, cannot resolve it", 156 callee_name); 157 return nullptr; 158 } 159 Address callee_addr = sc_list[0].symbol->GetAddress(); 160 if (!callee_addr.IsValid()) { 161 LLDB_LOG(log, "CallEdge: Invalid symbol address"); 162 return nullptr; 163 } 164 Function *f = callee_addr.CalculateSymbolContextFunction(); 165 if (!f) { 166 LLDB_LOG(log, "CallEdge: Could not find complete function"); 167 return nullptr; 168 } 169 return f; 170 }; 171 lazy_callee.def = resolve_lazy_callee(); 172 resolved = true; 173 } 174 175 Function *CallEdge::GetCallee(ModuleList &images) { 176 ParseSymbolFileAndResolve(images); 177 assert(resolved && "Did not resolve lazy callee"); 178 return lazy_callee.def; 179 } 180 181 lldb::addr_t CallEdge::GetReturnPCAddress(Function &caller, 182 Target &target) const { 183 const Address &base = caller.GetAddressRange().GetBaseAddress(); 184 return base.GetLoadAddress(&target) + return_pc; 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(), 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 CallEdge *Function::GetCallEdgeForReturnAddress(addr_t return_pc, 287 Target &target) { 288 auto edges = GetCallEdges(); 289 auto edge_it = 290 std::lower_bound(edges.begin(), edges.end(), return_pc, 291 [&](const CallEdge &edge, addr_t pc) { 292 return edge.GetReturnPCAddress(*this, target) < pc; 293 }); 294 if (edge_it == edges.end() || 295 edge_it->GetReturnPCAddress(*this, target) != return_pc) 296 return nullptr; 297 return &const_cast<CallEdge &>(*edge_it); 298 } 299 300 Block &Function::GetBlock(bool can_create) { 301 if (!m_block.BlockInfoHasBeenParsed() && can_create) { 302 ModuleSP module_sp = CalculateSymbolContextModule(); 303 if (module_sp) { 304 module_sp->GetSymbolFile()->ParseBlocksRecursive(*this); 305 } else { 306 Host::SystemLog(Host::eSystemLogError, 307 "error: unable to find module " 308 "shared pointer for function '%s' " 309 "in %s\n", 310 GetName().GetCString(), m_comp_unit->GetPath().c_str()); 311 } 312 m_block.SetBlockInfoHasBeenParsed(true, true); 313 } 314 return m_block; 315 } 316 317 CompileUnit *Function::GetCompileUnit() { return m_comp_unit; } 318 319 const CompileUnit *Function::GetCompileUnit() const { return m_comp_unit; } 320 321 void Function::GetDescription(Stream *s, lldb::DescriptionLevel level, 322 Target *target) { 323 ConstString name = GetName(); 324 ConstString mangled = m_mangled.GetMangledName(); 325 326 *s << "id = " << (const UserID &)*this; 327 if (name) 328 *s << ", name = \"" << name.GetCString() << '"'; 329 if (mangled) 330 *s << ", mangled = \"" << mangled.GetCString() << '"'; 331 *s << ", range = "; 332 Address::DumpStyle fallback_style; 333 if (level == eDescriptionLevelVerbose) 334 fallback_style = Address::DumpStyleModuleWithFileAddress; 335 else 336 fallback_style = Address::DumpStyleFileAddress; 337 GetAddressRange().Dump(s, target, Address::DumpStyleLoadAddress, 338 fallback_style); 339 } 340 341 void Function::Dump(Stream *s, bool show_context) const { 342 s->Printf("%p: ", static_cast<const void *>(this)); 343 s->Indent(); 344 *s << "Function" << static_cast<const UserID &>(*this); 345 346 m_mangled.Dump(s); 347 348 if (m_type) 349 s->Printf(", type = %p", static_cast<void *>(m_type)); 350 else if (m_type_uid != LLDB_INVALID_UID) 351 s->Printf(", type_uid = 0x%8.8" PRIx64, m_type_uid); 352 353 s->EOL(); 354 // Dump the root object 355 if (m_block.BlockInfoHasBeenParsed()) 356 m_block.Dump(s, m_range.GetBaseAddress().GetFileAddress(), INT_MAX, 357 show_context); 358 } 359 360 void Function::CalculateSymbolContext(SymbolContext *sc) { 361 sc->function = this; 362 m_comp_unit->CalculateSymbolContext(sc); 363 } 364 365 ModuleSP Function::CalculateSymbolContextModule() { 366 SectionSP section_sp(m_range.GetBaseAddress().GetSection()); 367 if (section_sp) 368 return section_sp->GetModule(); 369 370 return this->GetCompileUnit()->GetModule(); 371 } 372 373 CompileUnit *Function::CalculateSymbolContextCompileUnit() { 374 return this->GetCompileUnit(); 375 } 376 377 Function *Function::CalculateSymbolContextFunction() { return this; } 378 379 lldb::DisassemblerSP Function::GetInstructions(const ExecutionContext &exe_ctx, 380 const char *flavor, 381 bool prefer_file_cache) { 382 ModuleSP module_sp(GetAddressRange().GetBaseAddress().GetModule()); 383 if (module_sp) { 384 const bool prefer_file_cache = false; 385 return Disassembler::DisassembleRange(module_sp->GetArchitecture(), nullptr, 386 flavor, exe_ctx, GetAddressRange(), 387 prefer_file_cache); 388 } 389 return lldb::DisassemblerSP(); 390 } 391 392 bool Function::GetDisassembly(const ExecutionContext &exe_ctx, 393 const char *flavor, bool prefer_file_cache, 394 Stream &strm) { 395 lldb::DisassemblerSP disassembler_sp = 396 GetInstructions(exe_ctx, flavor, prefer_file_cache); 397 if (disassembler_sp) { 398 const bool show_address = true; 399 const bool show_bytes = false; 400 disassembler_sp->GetInstructionList().Dump(&strm, show_address, show_bytes, 401 &exe_ctx); 402 return true; 403 } 404 return false; 405 } 406 407 // Symbol * 408 // Function::CalculateSymbolContextSymbol () 409 //{ 410 // return // TODO: find the symbol for the function??? 411 //} 412 413 void Function::DumpSymbolContext(Stream *s) { 414 m_comp_unit->DumpSymbolContext(s); 415 s->Printf(", Function{0x%8.8" PRIx64 "}", GetID()); 416 } 417 418 size_t Function::MemorySize() const { 419 size_t mem_size = sizeof(Function) + m_block.MemorySize(); 420 return mem_size; 421 } 422 423 bool Function::GetIsOptimized() { 424 bool result = false; 425 426 // Currently optimization is only indicted by the vendor extension 427 // DW_AT_APPLE_optimized which is set on a compile unit level. 428 if (m_comp_unit) { 429 result = m_comp_unit->GetIsOptimized(); 430 } 431 return result; 432 } 433 434 bool Function::IsTopLevelFunction() { 435 bool result = false; 436 437 if (Language *language = Language::FindPlugin(GetLanguage())) 438 result = language->IsTopLevelFunction(*this); 439 440 return result; 441 } 442 443 ConstString Function::GetDisplayName() const { 444 return m_mangled.GetDisplayDemangledName(GetLanguage()); 445 } 446 447 CompilerDeclContext Function::GetDeclContext() { 448 ModuleSP module_sp = CalculateSymbolContextModule(); 449 450 if (module_sp) { 451 if (SymbolFile *sym_file = module_sp->GetSymbolFile()) 452 return sym_file->GetDeclContextForUID(GetID()); 453 } 454 return CompilerDeclContext(); 455 } 456 457 Type *Function::GetType() { 458 if (m_type == nullptr) { 459 SymbolContext sc; 460 461 CalculateSymbolContext(&sc); 462 463 if (!sc.module_sp) 464 return nullptr; 465 466 SymbolFile *sym_file = sc.module_sp->GetSymbolFile(); 467 468 if (sym_file == nullptr) 469 return nullptr; 470 471 m_type = sym_file->ResolveTypeUID(m_type_uid); 472 } 473 return m_type; 474 } 475 476 const Type *Function::GetType() const { return m_type; } 477 478 CompilerType Function::GetCompilerType() { 479 Type *function_type = GetType(); 480 if (function_type) 481 return function_type->GetFullCompilerType(); 482 return CompilerType(); 483 } 484 485 uint32_t Function::GetPrologueByteSize() { 486 if (m_prologue_byte_size == 0 && 487 m_flags.IsClear(flagsCalculatedPrologueSize)) { 488 m_flags.Set(flagsCalculatedPrologueSize); 489 LineTable *line_table = m_comp_unit->GetLineTable(); 490 uint32_t prologue_end_line_idx = 0; 491 492 if (line_table) { 493 LineEntry first_line_entry; 494 uint32_t first_line_entry_idx = UINT32_MAX; 495 if (line_table->FindLineEntryByAddress(GetAddressRange().GetBaseAddress(), 496 first_line_entry, 497 &first_line_entry_idx)) { 498 // Make sure the first line entry isn't already the end of the prologue 499 addr_t prologue_end_file_addr = LLDB_INVALID_ADDRESS; 500 addr_t line_zero_end_file_addr = LLDB_INVALID_ADDRESS; 501 502 if (first_line_entry.is_prologue_end) { 503 prologue_end_file_addr = 504 first_line_entry.range.GetBaseAddress().GetFileAddress(); 505 prologue_end_line_idx = first_line_entry_idx; 506 } else { 507 // Check the first few instructions and look for one that has 508 // is_prologue_end set to true. 509 const uint32_t last_line_entry_idx = first_line_entry_idx + 6; 510 for (uint32_t idx = first_line_entry_idx + 1; 511 idx < last_line_entry_idx; ++idx) { 512 LineEntry line_entry; 513 if (line_table->GetLineEntryAtIndex(idx, line_entry)) { 514 if (line_entry.is_prologue_end) { 515 prologue_end_file_addr = 516 line_entry.range.GetBaseAddress().GetFileAddress(); 517 prologue_end_line_idx = idx; 518 break; 519 } 520 } 521 } 522 } 523 524 // If we didn't find the end of the prologue in the line tables, then 525 // just use the end address of the first line table entry 526 if (prologue_end_file_addr == LLDB_INVALID_ADDRESS) { 527 // Check the first few instructions and look for one that has a line 528 // number that's different than the first entry. 529 uint32_t last_line_entry_idx = first_line_entry_idx + 6; 530 for (uint32_t idx = first_line_entry_idx + 1; 531 idx < last_line_entry_idx; ++idx) { 532 LineEntry line_entry; 533 if (line_table->GetLineEntryAtIndex(idx, line_entry)) { 534 if (line_entry.line != first_line_entry.line) { 535 prologue_end_file_addr = 536 line_entry.range.GetBaseAddress().GetFileAddress(); 537 prologue_end_line_idx = idx; 538 break; 539 } 540 } 541 } 542 543 if (prologue_end_file_addr == LLDB_INVALID_ADDRESS) { 544 prologue_end_file_addr = 545 first_line_entry.range.GetBaseAddress().GetFileAddress() + 546 first_line_entry.range.GetByteSize(); 547 prologue_end_line_idx = first_line_entry_idx; 548 } 549 } 550 551 const addr_t func_start_file_addr = 552 m_range.GetBaseAddress().GetFileAddress(); 553 const addr_t func_end_file_addr = 554 func_start_file_addr + m_range.GetByteSize(); 555 556 // Now calculate the offset to pass the subsequent line 0 entries. 557 uint32_t first_non_zero_line = prologue_end_line_idx; 558 while (true) { 559 LineEntry line_entry; 560 if (line_table->GetLineEntryAtIndex(first_non_zero_line, 561 line_entry)) { 562 if (line_entry.line != 0) 563 break; 564 } 565 if (line_entry.range.GetBaseAddress().GetFileAddress() >= 566 func_end_file_addr) 567 break; 568 569 first_non_zero_line++; 570 } 571 572 if (first_non_zero_line > prologue_end_line_idx) { 573 LineEntry first_non_zero_entry; 574 if (line_table->GetLineEntryAtIndex(first_non_zero_line, 575 first_non_zero_entry)) { 576 line_zero_end_file_addr = 577 first_non_zero_entry.range.GetBaseAddress().GetFileAddress(); 578 } 579 } 580 581 // Verify that this prologue end file address in the function's address 582 // range just to be sure 583 if (func_start_file_addr < prologue_end_file_addr && 584 prologue_end_file_addr < func_end_file_addr) { 585 m_prologue_byte_size = prologue_end_file_addr - func_start_file_addr; 586 } 587 588 if (prologue_end_file_addr < line_zero_end_file_addr && 589 line_zero_end_file_addr < func_end_file_addr) { 590 m_prologue_byte_size += 591 line_zero_end_file_addr - prologue_end_file_addr; 592 } 593 } 594 } 595 } 596 597 return m_prologue_byte_size; 598 } 599 600 lldb::LanguageType Function::GetLanguage() const { 601 lldb::LanguageType lang = m_mangled.GuessLanguage(); 602 if (lang != lldb::eLanguageTypeUnknown) 603 return lang; 604 605 if (m_comp_unit) 606 return m_comp_unit->GetLanguage(); 607 608 return lldb::eLanguageTypeUnknown; 609 } 610 611 ConstString Function::GetName() const { 612 LanguageType language = lldb::eLanguageTypeUnknown; 613 if (m_comp_unit) 614 language = m_comp_unit->GetLanguage(); 615 return m_mangled.GetName(language); 616 } 617 618 ConstString Function::GetNameNoArguments() const { 619 LanguageType language = lldb::eLanguageTypeUnknown; 620 if (m_comp_unit) 621 language = m_comp_unit->GetLanguage(); 622 return m_mangled.GetName(language, Mangled::ePreferDemangledWithoutArguments); 623 } 624