LLDB mainline
CompileUnit.cpp
Go to the documentation of this file.
1//===-- CompileUnit.cpp ---------------------------------------------------===//
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
10#include "lldb/Core/Module.h"
15#include "lldb/Utility/Timer.h"
16#include <optional>
17
18using namespace lldb;
19using namespace lldb_private;
20
21CompileUnit::CompileUnit(const lldb::ModuleSP &module_sp, void *user_data,
22 const char *pathname, const lldb::user_id_t cu_sym_id,
23 lldb::LanguageType language,
24 lldb_private::LazyBool is_optimized)
25 : CompileUnit(module_sp, user_data,
26 std::make_shared<SupportFile>(FileSpec(pathname)), cu_sym_id,
27 language, is_optimized) {}
28
29CompileUnit::CompileUnit(const lldb::ModuleSP &module_sp, void *user_data,
30 lldb::SupportFileSP support_file_sp,
31 const lldb::user_id_t cu_sym_id,
32 lldb::LanguageType language,
33 lldb_private::LazyBool is_optimized,
34 SupportFileList &&support_files)
35 : ModuleChild(module_sp), UserID(cu_sym_id), m_user_data(user_data),
36 m_language(language), m_flags(0),
37 m_primary_support_file_sp(support_file_sp),
38 m_support_files(std::move(support_files)), m_is_optimized(is_optimized) {
39 if (language != eLanguageTypeUnknown)
41 assert(module_sp);
42}
43
45 sc->comp_unit = this;
46 GetModule()->CalculateSymbolContext(sc);
47}
48
50
52
54 GetModule()->DumpSymbolContext(s);
55 s->Printf(", CompileUnit{0x%8.8" PRIx64 "}", GetID());
56}
57
59 lldb::DescriptionLevel level) const {
60 const char *language = GetCachedLanguage();
61 *s << "id = " << (const UserID &)*this << ", file = \""
62 << this->GetPrimaryFile() << "\", language = \"" << language << '"';
63}
64
66 llvm::function_ref<bool(const FunctionSP &)> lambda) const {
67 std::vector<lldb::FunctionSP> sorted_functions;
68 sorted_functions.reserve(m_functions_by_uid.size());
69 for (auto &p : m_functions_by_uid)
70 sorted_functions.push_back(p.second);
71 llvm::sort(sorted_functions,
72 [](const lldb::FunctionSP &a, const lldb::FunctionSP &b) {
73 return a->GetID() < b->GetID();
74 });
75
76 for (auto &f : sorted_functions)
77 if (lambda(f))
78 return;
79}
80
82 llvm::function_ref<bool(const FunctionSP &)> matching_lambda) {
84
86
87 if (!module)
88 return {};
89
90 SymbolFile *symbol_file = module->GetSymbolFile();
91
92 if (!symbol_file)
93 return {};
94
95 // m_functions_by_uid is filled in lazily but we need all the entries.
96 symbol_file->ParseFunctions(*this);
97
98 for (auto &p : m_functions_by_uid) {
99 if (matching_lambda(p.second))
100 return p.second;
101 }
102 return {};
103}
104
107 return "<not loaded>";
109}
110
111// Dump the current contents of this object. No functions that cause on demand
112// parsing of functions, globals, statics are called, so this is a good
113// function to call to get an idea of the current contents of the CompileUnit
114// object.
115void CompileUnit::Dump(Stream *s, bool show_context) const {
116 const char *language = GetCachedLanguage();
117
118 s->Printf("%p: ", static_cast<const void *>(this));
119 s->Indent();
120 *s << "CompileUnit" << static_cast<const UserID &>(*this) << ", language = \""
121 << language << "\", file = '" << GetPrimaryFile() << "'\n";
122
123 // m_types.Dump(s);
124
125 if (m_variables.get()) {
126 s->IndentMore();
127 m_variables->Dump(s, show_context);
128 s->IndentLess();
129 }
130
131 if (!m_functions_by_uid.empty()) {
132 s->IndentMore();
133 ForeachFunction([&s, show_context](const FunctionSP &f) {
134 f->Dump(s, show_context);
135 return false;
136 });
137
138 s->IndentLess();
139 s->EOL();
140 }
141}
142
143// Add a function to this compile unit
145 m_functions_by_uid[funcSP->GetID()] = funcSP;
146}
147
149 auto it = m_functions_by_uid.find(func_uid);
150 if (it == m_functions_by_uid.end())
151 return FunctionSP();
152 return it->second;
153}
154
159 if (SymbolFile *symfile = GetModule()->GetSymbolFile())
160 m_language = symfile->ParseLanguage(*this);
161 }
162 }
163 return m_language;
164}
165
167 if (m_line_table_up == nullptr) {
170 if (SymbolFile *symfile = GetModule()->GetSymbolFile())
171 symfile->ParseLineTable(*this);
172 }
173 }
174 return m_line_table_up.get();
175}
176
178 if (line_table == nullptr)
180 else
182 m_line_table_up.reset(line_table);
183}
184
186 if (m_debug_macros_sp.get() == nullptr) {
189 if (SymbolFile *symfile = GetModule()->GetSymbolFile())
190 symfile->ParseDebugMacros(*this);
191 }
192 }
193
194 return m_debug_macros_sp.get();
195}
196
197void CompileUnit::SetDebugMacros(const DebugMacrosSP &debug_macros_sp) {
198 if (debug_macros_sp.get() == nullptr)
200 else
202 m_debug_macros_sp = debug_macros_sp;
203}
204
206 if (m_variables.get() == nullptr && can_create) {
207 SymbolContext sc;
209 assert(sc.module_sp);
210 sc.module_sp->GetSymbolFile()->ParseVariablesForContext(sc);
211 }
212
213 return m_variables;
214}
215
216std::vector<uint32_t>
217FindFileIndexes(const SupportFileList &files, const FileSpec &file,
218 RealpathPrefixes *realpath_prefixes = nullptr) {
219 std::vector<uint32_t> result;
220 uint32_t idx = -1;
221 while ((idx = files.FindCompatibleIndex(idx + 1, file, realpath_prefixes)) !=
223 result.push_back(idx);
224 return result;
225}
226
227uint32_t CompileUnit::FindLineEntry(uint32_t start_idx, uint32_t line,
228 const FileSpec *file_spec_ptr, bool exact,
229 LineEntry *line_entry_ptr) {
230 if (!file_spec_ptr)
231 file_spec_ptr = &GetPrimaryFile();
232 std::vector<uint32_t> file_indexes = FindFileIndexes(GetSupportFiles(),
233 *file_spec_ptr);
234 if (file_indexes.empty())
235 return UINT32_MAX;
236
237 // TODO: Handle SourceLocationSpec column information
238 SourceLocationSpec location_spec(*file_spec_ptr, line,
239 /*column=*/std::nullopt,
240 /*check_inlines=*/false, exact);
241
242 LineTable *line_table = GetLineTable();
243 if (line_table)
244 return line_table->FindLineEntryIndexByFileIndex(
245 start_idx, file_indexes, location_spec, line_entry_ptr);
246 return UINT32_MAX;
247}
248
250 const SourceLocationSpec &src_location_spec,
251 SymbolContextItem resolve_scope, SymbolContextList &sc_list,
252 RealpathPrefixes *realpath_prefixes) {
253 const FileSpec file_spec = src_location_spec.GetFileSpec();
254 const uint32_t line = src_location_spec.GetLine().value_or(0);
255 const bool check_inlines = src_location_spec.GetCheckInlines();
256
257 // First find all of the file indexes that match our "file_spec". If
258 // "file_spec" has an empty directory, then only compare the basenames when
259 // finding file indexes
260 bool file_spec_matches_cu_file_spec =
261 FileSpec::Match(file_spec, this->GetPrimaryFile());
262
263 // If we are not looking for inlined functions and our file spec doesn't
264 // match then we are done...
265 if (!file_spec_matches_cu_file_spec && !check_inlines)
266 return;
267
269 sc.comp_unit = this;
270
271 if (line == 0) {
272 if (file_spec_matches_cu_file_spec && !check_inlines) {
273 // only append the context if we aren't looking for inline call sites by
274 // file and line and if the file spec matches that of the compile unit
275 sc_list.Append(sc);
276 }
277 return;
278 }
279
280 std::vector<uint32_t> file_indexes =
281 FindFileIndexes(GetSupportFiles(), file_spec, realpath_prefixes);
282 const size_t num_file_indexes = file_indexes.size();
283 if (num_file_indexes == 0)
284 return;
285
286 // Found a matching source file in this compile unit load its debug info.
287 GetModule()->GetSymbolFile()->SetLoadDebugInfoEnabled();
288
289 LineTable *line_table = sc.comp_unit->GetLineTable();
290
291 if (line_table == nullptr) {
292 if (file_spec_matches_cu_file_spec && !check_inlines) {
293 sc_list.Append(sc);
294 }
295 return;
296 }
297
298 uint32_t line_idx;
299 LineEntry line_entry;
300
301 if (num_file_indexes == 1) {
302 // We only have a single support file that matches, so use the line
303 // table function that searches for a line entries that match a single
304 // support file index
305 line_idx = line_table->FindLineEntryIndexByFileIndex(
306 0, file_indexes.front(), src_location_spec, &line_entry);
307 } else {
308 // We found multiple support files that match "file_spec" so use the
309 // line table function that searches for a line entries that match a
310 // multiple support file indexes.
311 line_idx = line_table->FindLineEntryIndexByFileIndex(
312 0, file_indexes, src_location_spec, &line_entry);
313 }
314
315 // If "exact == true", then "found_line" will be the same as "line". If
316 // "exact == false", the "found_line" will be the closest line entry
317 // with a line number greater than "line" and we will use this for our
318 // subsequent line exact matches below.
319 const bool inlines = false;
320 const bool exact = true;
321 const std::optional<uint16_t> column =
322 src_location_spec.GetColumn() ? std::optional<uint16_t>(line_entry.column)
323 : std::nullopt;
324
325 SourceLocationSpec found_entry(line_entry.GetFile(), line_entry.line, column,
326 inlines, exact);
327
328 while (line_idx != UINT32_MAX) {
329 // If they only asked for the line entry, then we're done, we can
330 // just copy that over. But if they wanted more than just the line
331 // number, fill it in.
332 SymbolContext resolved_sc;
333 sc.line_entry = line_entry;
334 if (resolve_scope == eSymbolContextLineEntry) {
335 sc_list.Append(sc);
336 } else {
337 line_entry.range.GetBaseAddress().CalculateSymbolContext(&resolved_sc,
338 resolve_scope);
339 // Sometimes debug info is bad and isn't able to resolve the line entry's
340 // address back to the same compile unit and/or line entry. If the compile
341 // unit changed, then revert back to just the compile unit and line entry.
342 // Prior to this fix, the above code might end up not being able to lookup
343 // the address, and then it would clear compile unit and the line entry in
344 // the symbol context and the breakpoint would fail to get set even though
345 // we have a valid line table entry in this compile unit. The address
346 // lookup can also end up finding another function in another compiler
347 // unit if the DWARF has overlappging address ranges. So if we end up with
348 // no compile unit or a different one after the above function call,
349 // revert back to the same results as if resolve_scope was set exactly to
350 // eSymbolContextLineEntry.
351 if (resolved_sc.comp_unit == this) {
352 sc_list.Append(resolved_sc);
353 } else {
354 if (resolved_sc.comp_unit == nullptr && resolved_sc.module_sp) {
355 // Only report an error if we don't map back to any compile unit. With
356 // link time optimizations, the debug info might have many compile
357 // units that have the same address range due to function outlining
358 // or other link time optimizations. If the compile unit is NULL, then
359 // address resolving is completely failing and more deserving of an
360 // error message the user can see.
361 resolved_sc.module_sp->ReportError(
362 "unable to resolve a line table file address {0:x16} back "
363 "to a compile unit, please file a bug and attach the address "
364 "and file.",
365 line_entry.range.GetBaseAddress().GetFileAddress());
366 }
367 sc_list.Append(sc);
368 }
369 }
370
371 if (num_file_indexes == 1)
372 line_idx = line_table->FindLineEntryIndexByFileIndex(
373 line_idx + 1, file_indexes.front(), found_entry, &line_entry);
374 else
375 line_idx = line_table->FindLineEntryIndexByFileIndex(
376 line_idx + 1, file_indexes, found_entry, &line_entry);
377 }
378}
379
383 if (SymbolFile *symfile = GetModule()->GetSymbolFile()) {
384 if (symfile->ParseIsOptimized(*this))
386 }
387 }
388 return m_is_optimized;
389}
390
392 m_variables = variables;
393}
394
395const std::vector<SourceModule> &CompileUnit::GetImportedModules() {
396 if (m_imported_modules.empty() &&
399 if (SymbolFile *symfile = GetModule()->GetSymbolFile()) {
400 SymbolContext sc;
402 symfile->ParseImportedModules(sc, m_imported_modules);
403 }
404 }
405 return m_imported_modules;
406}
407
409 llvm::DenseSet<SymbolFile *> &visited_symbol_files,
410 llvm::function_ref<bool(Module &)> lambda) {
411 if (SymbolFile *symfile = GetModule()->GetSymbolFile())
412 return symfile->ForEachExternalModule(*this, visited_symbol_files, lambda);
413 return false;
414}
415
417 if (m_support_files.GetSize() == 0) {
420 if (SymbolFile *symfile = GetModule()->GetSymbolFile())
421 symfile->ParseSupportFiles(*this, m_support_files);
422 }
423 }
424 return m_support_files;
425}
426
427void *CompileUnit::GetUserData() const { return m_user_data; }
std::vector< uint32_t > FindFileIndexes(const SupportFileList &files, const FileSpec &file, RealpathPrefixes *realpath_prefixes=nullptr)
#define LLDB_SCOPED_TIMER()
Definition: Timer.h:83
Address & GetBaseAddress()
Get accessor for the base address of the range.
Definition: AddressRange.h:211
uint32_t CalculateSymbolContext(SymbolContext *sc, lldb::SymbolContextItem resolve_scope=lldb::eSymbolContextEverything) const
Reconstruct a symbol context from an address.
Definition: Address.cpp:832
lldb::addr_t GetFileAddress() const
Get the file address.
Definition: Address.cpp:293
A class that describes a compilation unit.
Definition: CompileUnit.h:43
void SetVariableList(lldb::VariableListSP &variable_list_sp)
Set accessor for the variable list.
void Dump(Stream *s, bool show_context) const
Dump the compile unit contents to the stream s.
const SupportFileList & GetSupportFiles()
Get the compile unit's support file list.
lldb::LanguageType m_language
The programming language enumeration value.
Definition: CompileUnit.h:424
const std::vector< SourceModule > & GetImportedModules()
Get the compile unit's imported module list.
lldb::VariableListSP GetVariableList(bool can_create)
Get the variable list for a compile unit.
lldb_private::LazyBool m_is_optimized
eLazyBoolYes if this compile unit was compiled with optimization.
Definition: CompileUnit.h:444
void SetDebugMacros(const DebugMacrosSP &debug_macros)
const FileSpec & GetPrimaryFile() const
Return the primary source spec associated with this compile unit.
Definition: CompileUnit.h:232
void ForeachFunction(llvm::function_ref< bool(const lldb::FunctionSP &)> lambda) const
Apply a lambda to each function in this compile unit.
Definition: CompileUnit.cpp:65
@ flagsParsedLanguage
Have we parsed the language already?
Definition: CompileUnit.h:456
@ flagsParsedSupportFiles
Have we already parsed the support files for this compile unit?
Definition: CompileUnit.h:452
@ flagsParsedImportedModules
Have we parsed the imported modules already?
Definition: CompileUnit.h:457
@ flagsParsedDebugMacros
Have we parsed the debug macros already?
Definition: CompileUnit.h:459
@ flagsParsedLineTable
Have we parsed the line table already?
Definition: CompileUnit.h:454
Flags m_flags
Compile unit flags that help with partial parsing.
Definition: CompileUnit.h:426
lldb::FunctionSP FindFunction(llvm::function_ref< bool(const lldb::FunctionSP &)> matching_lambda)
Find a function in the compile unit based on the predicate matching_lambda.
Definition: CompileUnit.cpp:81
void * GetUserData() const
Get the SymbolFile plug-in user data.
bool GetIsOptimized()
Get whether compiler optimizations were enabled for this compile unit.
void CalculateSymbolContext(SymbolContext *sc) override
Reconstruct the object's symbol context into sc.
Definition: CompileUnit.cpp:44
lldb::ModuleSP CalculateSymbolContextModule() override
Definition: CompileUnit.cpp:49
void ResolveSymbolContext(const SourceLocationSpec &src_location_spec, lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list, RealpathPrefixes *realpath_prefixes=nullptr)
Resolve symbol contexts by file and line.
DebugMacros * GetDebugMacros()
void SetLineTable(LineTable *line_table)
Set the line table for the compile unit.
virtual bool ForEachExternalModule(llvm::DenseSet< lldb_private::SymbolFile * > &visited_symbol_files, llvm::function_ref< bool(Module &)> lambda)
Apply a lambda to each external lldb::Module referenced by this compilation unit.
void DumpSymbolContext(Stream *s) override
Dump the object's symbol context to the stream s.
Definition: CompileUnit.cpp:53
void AddFunction(lldb::FunctionSP &function_sp)
Add a function to this compile unit.
lldb::FunctionSP FindFunctionByUID(lldb::user_id_t uid)
Finds a function by user ID.
DebugMacrosSP m_debug_macros_sp
Debug macros that will get parsed on demand.
Definition: CompileUnit.h:439
std::unique_ptr< LineTable > m_line_table_up
Line table that will get parsed on demand.
Definition: CompileUnit.h:437
const char * GetCachedLanguage() const
CompileUnit * CalculateSymbolContextCompileUnit() override
Definition: CompileUnit.cpp:51
CompileUnit(const lldb::ModuleSP &module_sp, void *user_data, const char *pathname, lldb::user_id_t uid, lldb::LanguageType language, lldb_private::LazyBool is_optimized)
Construct with a module, path, UID and language.
Definition: CompileUnit.cpp:21
SupportFileList m_support_files
Files associated with this compile unit's line table and declarations.
Definition: CompileUnit.h:435
lldb::VariableListSP m_variables
Global and static variable list that will get parsed on demand.
Definition: CompileUnit.h:441
uint32_t FindLineEntry(uint32_t start_idx, uint32_t line, const FileSpec *file_spec_ptr, bool exact, LineEntry *line_entry)
Find the line entry by line and optional inlined file spec.
void GetDescription(Stream *s, lldb::DescriptionLevel level) const
Definition: CompileUnit.cpp:58
std::vector< SourceModule > m_imported_modules
All modules, including the current module, imported by this compile unit.
Definition: CompileUnit.h:431
lldb::LanguageType GetLanguage()
llvm::DenseMap< lldb::user_id_t, lldb::FunctionSP > m_functions_by_uid
Maps UIDs to functions.
Definition: CompileUnit.h:428
LineTable * GetLineTable()
Get the line table for the compile unit.
void * m_user_data
User data for the SymbolFile parser to store information into.
Definition: CompileUnit.h:422
A file utility class.
Definition: FileSpec.h:56
static bool Match(const FileSpec &pattern, const FileSpec &file)
Match FileSpec pattern against FileSpec file.
Definition: FileSpec.cpp:301
bool IsClear(ValueType bit) const
Test a single flag bit to see if it is clear (zero).
Definition: Flags.h:111
ValueType Clear(ValueType mask=~static_cast< ValueType >(0))
Clear one or more flags.
Definition: Flags.h:61
ValueType Set(ValueType mask)
Set one or more flags by logical OR'ing mask with the current flags.
Definition: Flags.h:73
static const char * GetNameForLanguageType(lldb::LanguageType language)
Definition: Language.cpp:266
A line table class.
Definition: LineTable.h:40
uint32_t FindLineEntryIndexByFileIndex(uint32_t start_idx, uint32_t file_idx, const SourceLocationSpec &src_location_spec, LineEntry *line_entry_ptr)
Find a line entry index that has a matching file index and source line number.
Definition: LineTable.cpp:305
A mix in class that contains a pointer back to the module that owns the object which inherits from it...
Definition: ModuleChild.h:19
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
Definition: ModuleChild.cpp:24
A class that describes an executable image and its associated object and symbol files.
Definition: Module.h:88
"lldb/Core/SourceLocationSpec.h" A source location specifier class.
std::optional< uint32_t > GetLine() const
std::optional< uint16_t > GetColumn() const
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition: Stream.cpp:157
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:134
size_t EOL()
Output and End of Line character to the stream.
Definition: Stream.cpp:155
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition: Stream.cpp:198
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition: Stream.cpp:195
A list of support files for a CompileUnit.
Definition: FileSpecList.h:23
size_t FindCompatibleIndex(size_t idx, const FileSpec &file, RealpathPrefixes *realpath_prefixes=nullptr) const
Find a compatible file index.
Wraps either a FileSpec that represents a local file or a source file whose contents is known (for ex...
Definition: SupportFile.h:21
Defines a list of symbol context objects.
void Append(const SymbolContext &sc)
Append a new symbol context to the list.
Defines a symbol context baton that can be handed other debug core functions.
Definition: SymbolContext.h:34
lldb::ModuleSP module_sp
The Module for a given query.
CompileUnit * comp_unit
The CompileUnit for a given query.
LineEntry line_entry
The LineEntry for a given query.
Provides public interface for all SymbolFiles.
Definition: SymbolFile.h:50
virtual size_t ParseFunctions(CompileUnit &comp_unit)=0
#define UINT32_MAX
Definition: lldb-defines.h:19
A class that represents a running process on the host machine.
std::shared_ptr< DebugMacros > DebugMacrosSP
Definition: DebugMacros.h:22
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::Function > FunctionSP
Definition: lldb-forward.h:353
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
std::shared_ptr< lldb_private::SupportFile > SupportFileSP
Definition: lldb-forward.h:475
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
std::shared_ptr< lldb_private::VariableList > VariableListSP
Definition: lldb-forward.h:483
uint64_t user_id_t
Definition: lldb-types.h:82
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:371
A line table entry class.
Definition: LineEntry.h:21
uint16_t column
The column number of the source line, or zero if there is no column information.
Definition: LineEntry.h:151
AddressRange range
The section offset address range for this line entry.
Definition: LineEntry.h:137
uint32_t line
The source line number, or LLDB_INVALID_LINE_NUMBER if there is no line number information.
Definition: LineEntry.h:147
const FileSpec & GetFile() const
Helper to access the file.
Definition: LineEntry.h:134
A mix in class that contains a generic user ID.
Definition: UserID.h:31
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:47