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