1 //===-- CompileUnit.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/CompileUnit.h"
10 #include "lldb/Core/Module.h"
11 #include "lldb/Symbol/LineTable.h"
12 #include "lldb/Symbol/SymbolVendor.h"
13 #include "lldb/Symbol/VariableList.h"
14 #include "lldb/Target/Language.h"
15 
16 using namespace lldb;
17 using namespace lldb_private;
18 
19 CompileUnit::CompileUnit(const lldb::ModuleSP &module_sp, void *user_data,
20                          const char *pathname, const lldb::user_id_t cu_sym_id,
21                          lldb::LanguageType language,
22                          lldb_private::LazyBool is_optimized)
23     : ModuleChild(module_sp), FileSpec(pathname), UserID(cu_sym_id),
24       m_user_data(user_data), m_language(language), m_flags(0),
25       m_support_files(), m_line_table_up(), m_variables(),
26       m_is_optimized(is_optimized) {
27   if (language != eLanguageTypeUnknown)
28     m_flags.Set(flagsParsedLanguage);
29   assert(module_sp);
30 }
31 
32 CompileUnit::CompileUnit(const lldb::ModuleSP &module_sp, void *user_data,
33                          const FileSpec &fspec, const lldb::user_id_t cu_sym_id,
34                          lldb::LanguageType language,
35                          lldb_private::LazyBool is_optimized)
36     : ModuleChild(module_sp), FileSpec(fspec), UserID(cu_sym_id),
37       m_user_data(user_data), m_language(language), m_flags(0),
38       m_support_files(), m_line_table_up(), m_variables(),
39       m_is_optimized(is_optimized) {
40   if (language != eLanguageTypeUnknown)
41     m_flags.Set(flagsParsedLanguage);
42   assert(module_sp);
43 }
44 
45 CompileUnit::~CompileUnit() {}
46 
47 void CompileUnit::CalculateSymbolContext(SymbolContext *sc) {
48   sc->comp_unit = this;
49   GetModule()->CalculateSymbolContext(sc);
50 }
51 
52 ModuleSP CompileUnit::CalculateSymbolContextModule() { return GetModule(); }
53 
54 CompileUnit *CompileUnit::CalculateSymbolContextCompileUnit() { return this; }
55 
56 void CompileUnit::DumpSymbolContext(Stream *s) {
57   GetModule()->DumpSymbolContext(s);
58   s->Printf(", CompileUnit{0x%8.8" PRIx64 "}", GetID());
59 }
60 
61 void CompileUnit::GetDescription(Stream *s,
62                                  lldb::DescriptionLevel level) const {
63   const char *language = Language::GetNameForLanguageType(m_language);
64   *s << "id = " << (const UserID &)*this << ", file = \""
65      << (const FileSpec &)*this << "\", language = \"" << language << '"';
66 }
67 
68 void CompileUnit::ForeachFunction(
69     llvm::function_ref<bool(const FunctionSP &)> lambda) const {
70   std::vector<lldb::FunctionSP> sorted_functions;
71   sorted_functions.reserve(m_functions_by_uid.size());
72   for (auto &p : m_functions_by_uid)
73     sorted_functions.push_back(p.second);
74   llvm::sort(sorted_functions.begin(), sorted_functions.end(),
75              [](const lldb::FunctionSP &a, const lldb::FunctionSP &b) {
76                return a->GetID() < b->GetID();
77              });
78 
79   for (auto &f : sorted_functions)
80     if (lambda(f))
81       return;
82 }
83 
84 //----------------------------------------------------------------------
85 // Dump the current contents of this object. No functions that cause on demand
86 // parsing of functions, globals, statics are called, so this is a good
87 // function to call to get an idea of the current contents of the CompileUnit
88 // object.
89 //----------------------------------------------------------------------
90 void CompileUnit::Dump(Stream *s, bool show_context) const {
91   const char *language = Language::GetNameForLanguageType(m_language);
92 
93   s->Printf("%p: ", static_cast<const void *>(this));
94   s->Indent();
95   *s << "CompileUnit" << static_cast<const UserID &>(*this) << ", language = \""
96      << language << "\", file = '" << static_cast<const FileSpec &>(*this)
97      << "'\n";
98 
99   //  m_types.Dump(s);
100 
101   if (m_variables.get()) {
102     s->IndentMore();
103     m_variables->Dump(s, show_context);
104     s->IndentLess();
105   }
106 
107   if (!m_functions_by_uid.empty()) {
108     s->IndentMore();
109     ForeachFunction([&s, show_context](const FunctionSP &f) {
110       f->Dump(s, show_context);
111       return false;
112     });
113 
114     s->IndentLess();
115     s->EOL();
116   }
117 }
118 
119 //----------------------------------------------------------------------
120 // Add a function to this compile unit
121 //----------------------------------------------------------------------
122 void CompileUnit::AddFunction(FunctionSP &funcSP) {
123   m_functions_by_uid[funcSP->GetID()] = funcSP;
124 }
125 
126 //----------------------------------------------------------------------
127 // Find functions using the Mangled::Tokens token list. This function currently
128 // implements an interactive approach designed to find all instances of certain
129 // functions. It isn't designed to the quickest way to lookup functions as it
130 // will need to iterate through all functions and see if they match, though it
131 // does provide a powerful and context sensitive way to search for all
132 // functions with a certain name, all functions in a namespace, or all
133 // functions of a template type. See Mangled::Tokens::Parse() comments for more
134 // information.
135 //
136 // The function prototype will need to change to return a list of results. It
137 // was originally used to help debug the Mangled class and the
138 // Mangled::Tokens::MatchesQuery() function and it currently will print out a
139 // list of matching results for the functions that are currently in this
140 // compile unit.
141 //
142 // A FindFunctions method should be called prior to this that takes
143 // a regular function name (const char * or ConstString as a parameter) before
144 // resorting to this slower but more complete function. The other FindFunctions
145 // method should be able to take advantage of any accelerator tables available
146 // in the debug information (which is parsed by the SymbolFile parser plug-ins
147 // and registered with each Module).
148 //----------------------------------------------------------------------
149 // void
150 // CompileUnit::FindFunctions(const Mangled::Tokens& tokens)
151 //{
152 //  if (!m_functions.empty())
153 //  {
154 //      Stream s(stdout);
155 //      std::vector<FunctionSP>::const_iterator pos;
156 //      std::vector<FunctionSP>::const_iterator end = m_functions.end();
157 //      for (pos = m_functions.begin(); pos != end; ++pos)
158 //      {
159 //          const ConstString& demangled = (*pos)->Mangled().Demangled();
160 //          if (demangled)
161 //          {
162 //              const Mangled::Tokens& func_tokens =
163 //              (*pos)->Mangled().GetTokens();
164 //              if (func_tokens.MatchesQuery (tokens))
165 //                  s << "demangled MATCH found: " << demangled << "\n";
166 //          }
167 //      }
168 //  }
169 //}
170 
171 FunctionSP CompileUnit::FindFunctionByUID(lldb::user_id_t func_uid) {
172   auto it = m_functions_by_uid.find(func_uid);
173   if (it == m_functions_by_uid.end())
174     return FunctionSP();
175   return it->second;
176 }
177 
178 lldb::LanguageType CompileUnit::GetLanguage() {
179   if (m_language == eLanguageTypeUnknown) {
180     if (m_flags.IsClear(flagsParsedLanguage)) {
181       m_flags.Set(flagsParsedLanguage);
182       SymbolVendor *symbol_vendor = GetModule()->GetSymbolVendor();
183       if (symbol_vendor) {
184         m_language = symbol_vendor->ParseLanguage(*this);
185       }
186     }
187   }
188   return m_language;
189 }
190 
191 LineTable *CompileUnit::GetLineTable() {
192   if (m_line_table_up == nullptr) {
193     if (m_flags.IsClear(flagsParsedLineTable)) {
194       m_flags.Set(flagsParsedLineTable);
195       SymbolVendor *symbol_vendor = GetModule()->GetSymbolVendor();
196       if (symbol_vendor)
197         symbol_vendor->ParseLineTable(*this);
198     }
199   }
200   return m_line_table_up.get();
201 }
202 
203 void CompileUnit::SetLineTable(LineTable *line_table) {
204   if (line_table == nullptr)
205     m_flags.Clear(flagsParsedLineTable);
206   else
207     m_flags.Set(flagsParsedLineTable);
208   m_line_table_up.reset(line_table);
209 }
210 
211 DebugMacros *CompileUnit::GetDebugMacros() {
212   if (m_debug_macros_sp.get() == nullptr) {
213     if (m_flags.IsClear(flagsParsedDebugMacros)) {
214       m_flags.Set(flagsParsedDebugMacros);
215       SymbolVendor *symbol_vendor = GetModule()->GetSymbolVendor();
216       if (symbol_vendor) {
217         symbol_vendor->ParseDebugMacros(*this);
218       }
219     }
220   }
221 
222   return m_debug_macros_sp.get();
223 }
224 
225 void CompileUnit::SetDebugMacros(const DebugMacrosSP &debug_macros_sp) {
226   if (debug_macros_sp.get() == nullptr)
227     m_flags.Clear(flagsParsedDebugMacros);
228   else
229     m_flags.Set(flagsParsedDebugMacros);
230   m_debug_macros_sp = debug_macros_sp;
231 }
232 
233 VariableListSP CompileUnit::GetVariableList(bool can_create) {
234   if (m_variables.get() == nullptr && can_create) {
235     SymbolContext sc;
236     CalculateSymbolContext(&sc);
237     assert(sc.module_sp);
238     sc.module_sp->GetSymbolVendor()->ParseVariablesForContext(sc);
239   }
240 
241   return m_variables;
242 }
243 
244 uint32_t CompileUnit::FindLineEntry(uint32_t start_idx, uint32_t line,
245                                     const FileSpec *file_spec_ptr, bool exact,
246                                     LineEntry *line_entry_ptr) {
247   uint32_t file_idx = 0;
248 
249   if (file_spec_ptr) {
250     file_idx = GetSupportFiles().FindFileIndex(1, *file_spec_ptr, true);
251     if (file_idx == UINT32_MAX)
252       return UINT32_MAX;
253   } else {
254     // All the line table entries actually point to the version of the Compile
255     // Unit that is in the support files (the one at 0 was artificially added.)
256     // So prefer the one further on in the support files if it exists...
257     FileSpecList &support_files = GetSupportFiles();
258     const bool full = true;
259     file_idx = support_files.FindFileIndex(
260         1, support_files.GetFileSpecAtIndex(0), full);
261     if (file_idx == UINT32_MAX)
262       file_idx = 0;
263   }
264   LineTable *line_table = GetLineTable();
265   if (line_table)
266     return line_table->FindLineEntryIndexByFileIndex(start_idx, file_idx, line,
267                                                      exact, line_entry_ptr);
268   return UINT32_MAX;
269 }
270 
271 uint32_t CompileUnit::ResolveSymbolContext(const FileSpec &file_spec,
272                                            uint32_t line, bool check_inlines,
273                                            bool exact,
274                                            SymbolContextItem resolve_scope,
275                                            SymbolContextList &sc_list) {
276   // First find all of the file indexes that match our "file_spec". If
277   // "file_spec" has an empty directory, then only compare the basenames when
278   // finding file indexes
279   std::vector<uint32_t> file_indexes;
280   const bool full_match = (bool)file_spec.GetDirectory();
281   bool file_spec_matches_cu_file_spec =
282       FileSpec::Equal(file_spec, *this, full_match);
283 
284   // If we are not looking for inlined functions and our file spec doesn't
285   // match then we are done...
286   if (!file_spec_matches_cu_file_spec && !check_inlines)
287     return 0;
288 
289   uint32_t file_idx =
290       GetSupportFiles().FindFileIndex(1, file_spec, true);
291   while (file_idx != UINT32_MAX) {
292     file_indexes.push_back(file_idx);
293     file_idx = GetSupportFiles().FindFileIndex(file_idx + 1, file_spec, true);
294   }
295 
296   const size_t num_file_indexes = file_indexes.size();
297   if (num_file_indexes == 0)
298     return 0;
299 
300   const uint32_t prev_size = sc_list.GetSize();
301 
302   SymbolContext sc(GetModule());
303   sc.comp_unit = this;
304 
305   if (line != 0) {
306     LineTable *line_table = sc.comp_unit->GetLineTable();
307 
308     if (line_table != nullptr) {
309       uint32_t found_line;
310       uint32_t line_idx;
311 
312       if (num_file_indexes == 1) {
313         // We only have a single support file that matches, so use the line
314         // table function that searches for a line entries that match a single
315         // support file index
316         LineEntry line_entry;
317         line_idx = line_table->FindLineEntryIndexByFileIndex(
318             0, file_indexes.front(), line, exact, &line_entry);
319 
320         // If "exact == true", then "found_line" will be the same as "line". If
321         // "exact == false", the "found_line" will be the closest line entry
322         // with a line number greater than "line" and we will use this for our
323         // subsequent line exact matches below.
324         found_line = line_entry.line;
325 
326         while (line_idx != UINT32_MAX) {
327           // If they only asked for the line entry, then we're done, we can
328           // just copy that over. But if they wanted more than just the line
329           // number, fill it in.
330           if (resolve_scope == eSymbolContextLineEntry) {
331             sc.line_entry = line_entry;
332           } else {
333             line_entry.range.GetBaseAddress().CalculateSymbolContext(
334                 &sc, resolve_scope);
335           }
336 
337           sc_list.Append(sc);
338           line_idx = line_table->FindLineEntryIndexByFileIndex(
339               line_idx + 1, file_indexes.front(), found_line, true,
340               &line_entry);
341         }
342       } else {
343         // We found multiple support files that match "file_spec" so use the
344         // line table function that searches for a line entries that match a
345         // multiple support file indexes.
346         LineEntry line_entry;
347         line_idx = line_table->FindLineEntryIndexByFileIndex(
348             0, file_indexes, line, exact, &line_entry);
349 
350         // If "exact == true", then "found_line" will be the same as "line". If
351         // "exact == false", the "found_line" will be the closest line entry
352         // with a line number greater than "line" and we will use this for our
353         // subsequent line exact matches below.
354         found_line = line_entry.line;
355 
356         while (line_idx != UINT32_MAX) {
357           if (resolve_scope == eSymbolContextLineEntry) {
358             sc.line_entry = line_entry;
359           } else {
360             line_entry.range.GetBaseAddress().CalculateSymbolContext(
361                 &sc, resolve_scope);
362           }
363 
364           sc_list.Append(sc);
365           line_idx = line_table->FindLineEntryIndexByFileIndex(
366               line_idx + 1, file_indexes, found_line, true, &line_entry);
367         }
368       }
369     }
370   } else if (file_spec_matches_cu_file_spec && !check_inlines) {
371     // only append the context if we aren't looking for inline call sites by
372     // file and line and if the file spec matches that of the compile unit
373     sc_list.Append(sc);
374   }
375   return sc_list.GetSize() - prev_size;
376 }
377 
378 bool CompileUnit::GetIsOptimized() {
379   if (m_is_optimized == eLazyBoolCalculate) {
380     m_is_optimized = eLazyBoolNo;
381     if (SymbolVendor *symbol_vendor = GetModule()->GetSymbolVendor()) {
382       if (symbol_vendor->ParseIsOptimized(*this))
383         m_is_optimized = eLazyBoolYes;
384     }
385   }
386   return m_is_optimized;
387 }
388 
389 void CompileUnit::SetVariableList(VariableListSP &variables) {
390   m_variables = variables;
391 }
392 
393 const std::vector<SourceModule> &CompileUnit::GetImportedModules() {
394   if (m_imported_modules.empty() &&
395       m_flags.IsClear(flagsParsedImportedModules)) {
396     m_flags.Set(flagsParsedImportedModules);
397     if (SymbolVendor *symbol_vendor = GetModule()->GetSymbolVendor()) {
398       SymbolContext sc;
399       CalculateSymbolContext(&sc);
400       symbol_vendor->ParseImportedModules(sc, m_imported_modules);
401     }
402   }
403   return m_imported_modules;
404 }
405 
406 FileSpecList &CompileUnit::GetSupportFiles() {
407   if (m_support_files.GetSize() == 0) {
408     if (m_flags.IsClear(flagsParsedSupportFiles)) {
409       m_flags.Set(flagsParsedSupportFiles);
410       SymbolVendor *symbol_vendor = GetModule()->GetSymbolVendor();
411       if (symbol_vendor) {
412         symbol_vendor->ParseSupportFiles(*this, m_support_files);
413       }
414     }
415   }
416   return m_support_files;
417 }
418 
419 void *CompileUnit::GetUserData() const { return m_user_data; }
420