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