LLDB mainline
BreakpointResolverFileLine.cpp
Go to the documentation of this file.
1//===-- BreakpointResolverFileLine.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
12#include "lldb/Core/Module.h"
16#include "lldb/Target/Target.h"
18#include "lldb/Utility/Log.h"
21#include <optional>
22
23using namespace lldb;
24using namespace lldb_private;
25
26// BreakpointResolverFileLine:
28 const BreakpointSP &bkpt, lldb::addr_t offset, bool skip_prologue,
29 const SourceLocationSpec &location_spec,
30 std::optional<llvm::StringRef> removed_prefix_opt)
32 m_location_spec(location_spec), m_skip_prologue(skip_prologue),
33 m_removed_prefix_opt(removed_prefix_opt) {}
34
36 const StructuredData::Dictionary &options_dict, Status &error) {
37 llvm::StringRef filename;
38 uint32_t line;
39 uint16_t column;
40 bool check_inlines;
41 bool skip_prologue;
42 bool exact_match;
43 bool success;
44
45 lldb::addr_t offset = 0;
46
48 filename);
49 if (!success) {
50 error =
51 Status::FromErrorString("BRFL::CFSD: Couldn't find filename entry.");
52 return nullptr;
53 }
54
55 success = options_dict.GetValueForKeyAsInteger(
57 if (!success) {
58 error =
59 Status::FromErrorString("BRFL::CFSD: Couldn't find line number entry.");
60 return nullptr;
61 }
62
63 success =
65 if (!success) {
66 // Backwards compatibility.
67 column = 0;
68 }
69
71 check_inlines);
72 if (!success) {
74 "BRFL::CFSD: Couldn't find check inlines entry.");
75 return nullptr;
76 }
77
78 success = options_dict.GetValueForKeyAsBoolean(
79 GetKey(OptionNames::SkipPrologue), skip_prologue);
80 if (!success) {
82 "BRFL::CFSD: Couldn't find skip prologue entry.");
83 return nullptr;
84 }
85
86 success = options_dict.GetValueForKeyAsBoolean(
87 GetKey(OptionNames::ExactMatch), exact_match);
88 if (!success) {
89 error =
90 Status::FromErrorString("BRFL::CFSD: Couldn't find exact match entry.");
91 return nullptr;
92 }
93
94 SourceLocationSpec location_spec(FileSpec(filename), line, column,
95 check_inlines, exact_match);
96 if (!location_spec)
97 return nullptr;
98
99 return std::make_shared<BreakpointResolverFileLine>(
100 nullptr, offset, skip_prologue, location_spec);
101}
102
105 StructuredData::DictionarySP options_dict_sp(
107
108 options_dict_sp->AddBooleanItem(GetKey(OptionNames::SkipPrologue),
110 options_dict_sp->AddStringItem(GetKey(OptionNames::FileName),
111 m_location_spec.GetFileSpec().GetPath());
112 options_dict_sp->AddIntegerItem(GetKey(OptionNames::LineNumber),
113 m_location_spec.GetLine().value_or(0));
114 options_dict_sp->AddIntegerItem(
116 m_location_spec.GetColumn().value_or(LLDB_INVALID_COLUMN_NUMBER));
117 options_dict_sp->AddBooleanItem(GetKey(OptionNames::Inlines),
118 m_location_spec.GetCheckInlines());
119 options_dict_sp->AddBooleanItem(GetKey(OptionNames::ExactMatch),
120 m_location_spec.GetExactMatch());
121
122 return WrapOptionsDict(options_dict_sp);
123}
124
125// Filter the symbol context list to remove contexts where the line number was
126// moved into a new function. We do this conservatively, so if e.g. we cannot
127// resolve the function in the context (which can happen in case of line-table-
128// only debug info), we leave the context as is. The trickiest part here is
129// handling inlined functions -- in this case we need to make sure we look at
130// the declaration line of the inlined function, NOT the function it was
131// inlined into.
133 if (m_location_spec.GetExactMatch())
134 return; // Nothing to do. Contexts are precise.
135
137 for(uint32_t i = 0; i < sc_list.GetSize(); ++i) {
138 SymbolContext sc;
139 sc_list.GetContextAtIndex(i, sc);
140 if (!sc.block)
141 continue;
142
143 SupportFileNSP file_sp = std::make_shared<SupportFile>();
144 uint32_t line;
145 const Block *inline_block = sc.block->GetContainingInlinedBlock();
146 if (inline_block) {
147 const Declaration &inline_declaration = inline_block->GetInlinedFunctionInfo()->GetDeclaration();
148 if (!inline_declaration.IsValid())
149 continue;
150 file_sp = std::make_shared<SupportFile>(inline_declaration.GetFile());
151 line = inline_declaration.GetLine();
152 } else if (sc.function)
153 sc.function->GetStartLineSourceInfo(file_sp, line);
154 else
155 continue;
156
157 if (!file_sp ||
158 !file_sp->Equal(*sc.line_entry.file_sp,
160 LLDB_LOG(log, "unexpected symbol context file {0}",
161 sc.line_entry.GetFile());
162 continue;
163 }
164
165 // Compare the requested line number with the line of the function
166 // declaration. In case of a function declared as:
167 //
168 // int
169 // foo()
170 // {
171 // ...
172 //
173 // the compiler will set the declaration line to the "foo" line, which is
174 // the reason why we have -1 here. This can fail in case of two inline
175 // functions defined back-to-back:
176 //
177 // inline int foo1() { ... }
178 // inline int foo2() { ... }
179 //
180 // but that's the best we can do for now.
181 // One complication, if the line number returned from GetStartLineSourceInfo
182 // is 0, then we can't do this calculation. That can happen if
183 // GetStartLineSourceInfo gets an error, or if the first line number in
184 // the function really is 0 - which happens for some languages.
185
186 // But only do this calculation if the line number we found in the SC
187 // was different from the one requested in the source file. If we actually
188 // found an exact match it must be valid.
189
190 if (m_location_spec.GetLine() == sc.line_entry.line)
191 continue;
192
193 const int decl_line_is_too_late_fudge = 1;
194 if (line &&
195 m_location_spec.GetLine() < line - decl_line_is_too_late_fudge) {
196 LLDB_LOG(log, "removing symbol context at {0}:{1}",
197 file_sp->GetSpecOnly(), line);
198 sc_list.RemoveContextAtIndex(i);
199 --i;
200 }
201 }
202}
203
205 const SymbolContextList &sc_list) {
206 Target &target = GetBreakpoint()->GetTarget();
207 if (!target.GetAutoSourceMapRelative())
208 return;
209
211 // Check if "b" is a suffix of "a".
212 // And return std::nullopt if not or the new path
213 // of "a" after consuming "b" from the back.
214 auto check_suffix =
215 [](llvm::StringRef a, llvm::StringRef b,
216 bool case_sensitive) -> std::optional<llvm::StringRef> {
217 if (case_sensitive ? a.consume_back(b) : a.consume_back_insensitive(b)) {
218 // Note sc_file_dir and request_file_dir below are normalized
219 // and always contain the path separator '/'.
220 if (a.empty() || a.ends_with("/")) {
221 return a;
222 }
223 }
224 return std::nullopt;
225 };
226
227 FileSpec request_file = m_location_spec.GetFileSpec();
228
229 // Only auto deduce source map if breakpoint is full path.
230 // Note: an existing source map reverse mapping (m_removed_prefix_opt has
231 // value) may make request_file relative.
232 if (!m_removed_prefix_opt.has_value() && request_file.IsRelative())
233 return;
234
235 const bool case_sensitive = request_file.IsCaseSensitive();
236 for (const SymbolContext &sc : sc_list) {
237 FileSpec sc_file = sc.line_entry.GetFile();
238
239 if (FileSpec::Equal(sc_file, request_file, /*full*/ true))
240 continue;
241
242 llvm::StringRef sc_file_dir = sc_file.GetDirectory();
243 llvm::StringRef request_file_dir = request_file.GetDirectory();
244
245 llvm::StringRef new_mapping_from;
246 llvm::SmallString<256> new_mapping_to;
247
248 // Adding back any potentially reverse mapping stripped prefix.
249 // for new_mapping_to.
250 if (m_removed_prefix_opt.has_value())
251 llvm::sys::path::append(new_mapping_to, *m_removed_prefix_opt);
252
253 std::optional<llvm::StringRef> new_mapping_from_opt =
254 check_suffix(sc_file_dir, request_file_dir, case_sensitive);
255 if (new_mapping_from_opt) {
256 new_mapping_from = *new_mapping_from_opt;
257 if (new_mapping_to.empty())
258 new_mapping_to = ".";
259 } else {
260 std::optional<llvm::StringRef> new_mapping_to_opt =
261 check_suffix(request_file_dir, sc_file_dir, case_sensitive);
262 if (new_mapping_to_opt) {
263 new_mapping_from = ".";
264 llvm::sys::path::append(new_mapping_to, *new_mapping_to_opt);
265 }
266 }
267
268 if (!new_mapping_from.empty() && !new_mapping_to.empty()) {
269 LLDB_LOG(log, "generating auto source map from {0} to {1}",
270 new_mapping_from, new_mapping_to);
271 if (target.GetSourcePathMap().AppendUnique(new_mapping_from,
272 new_mapping_to,
273 /*notify*/ true))
275 }
276 }
277}
278
280 SearchFilter &filter, SymbolContext &context, Address *addr) {
281 SymbolContextList sc_list;
282
283 // There is a tricky bit here. You can have two compilation units that
284 // #include the same file, and in one of them the function at m_line_number
285 // is used (and so code and a line entry for it is generated) but in the
286 // other it isn't. If we considered the CU's independently, then in the
287 // second inclusion, we'd move the breakpoint to the next function that
288 // actually generated code in the header file. That would end up being
289 // confusing. So instead, we do the CU iterations by hand here, then scan
290 // through the complete list of matches, and figure out the closest line
291 // number match, and only set breakpoints on that match.
292
293 // Note also that if file_spec only had a file name and not a directory,
294 // there may be many different file spec's in the resultant list. The
295 // closest line match for one will not be right for some totally different
296 // file. So we go through the match list and pull out the sets that have the
297 // same file spec in their line_entry and treat each set separately.
298
299 const uint32_t line = m_location_spec.GetLine().value_or(0);
300 const std::optional<uint16_t> column = m_location_spec.GetColumn();
301
302 Target &target = GetBreakpoint()->GetTarget();
303 RealpathPrefixes realpath_prefixes = target.GetSourceRealpathPrefixes();
304
305 if (const auto sym_file = context.module_sp->GetSymbolFileLocked()) {
306 const size_t num_comp_units = sym_file->GetNumCompileUnits();
307 for (size_t i = 0; i < num_comp_units; i++) {
308
309 if (const auto cu_sp = sym_file->GetCompileUnitAtIndex(i);
310 cu_sp && filter.CompUnitPasses(*cu_sp)) {
311 cu_sp->ResolveSymbolContext(m_location_spec, eSymbolContextEverything,
312 sc_list, &realpath_prefixes);
313 }
314 }
315 }
316
317 // Gather stats into the Target
319 realpath_prefixes.GetSourceRealpathAttemptCount());
321 realpath_prefixes.GetSourceRealpathCompatibleCount());
322
323 FilterContexts(sc_list);
324
325 DeduceSourceMapping(sc_list);
326
327 StreamString s;
328 s.Format("for {0}:{1} ",
329 m_location_spec.GetFileSpec().GetFilename().nonEmptyOr("<Unknown>"),
330 line);
331
332 SetSCMatchesByLine(filter, sc_list, m_skip_prologue, s.GetString(), line,
333 column);
334
336}
337
341
343 s->Printf("file = '%s', line = %u, ",
344 m_location_spec.GetFileSpec().GetPath().c_str(),
345 m_location_spec.GetLine().value_or(0));
346 auto column = m_location_spec.GetColumn();
347 if (column)
348 s->Printf("column = %u, ", *column);
349 s->Printf("exact_match = %d", m_location_spec.GetExactMatch());
350}
351
353
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:376
A section + offset based address class.
Definition Address.h:62
A class that describes a single lexical block.
Definition Block.h:41
Block * GetContainingInlinedBlock()
Get the inlined block that contains this block.
Definition Block.cpp:206
const InlineFunctionInfo * GetInlinedFunctionInfo() const
Get const accessor for any inlined function information.
Definition Block.h:268
Searcher::CallbackReturn SearchCallback(SearchFilter &filter, SymbolContext &context, Address *addr) override
static lldb::BreakpointResolverSP CreateFromStructuredData(const StructuredData::Dictionary &data_dict, Status &error)
void GetDescription(Stream *s) override
Prints a canonical description for the breakpoint to the stream s.
void DeduceSourceMapping(const SymbolContextList &sc_list)
StructuredData::ObjectSP SerializeToStructuredData() override
std::optional< llvm::StringRef > m_removed_prefix_opt
void Dump(Stream *s) const override
Standard "Dump" method. At present it does nothing.
lldb::BreakpointResolverSP CopyForBreakpoint(lldb::BreakpointSP &breakpoint) override
BreakpointResolverFileLine(const lldb::BreakpointSP &bkpt, lldb::addr_t offset, bool skip_prologue, const SourceLocationSpec &location_spec, std::optional< llvm::StringRef > removed_prefix_opt=std::nullopt)
static const char * GetKey(OptionNames enum_value)
StructuredData::DictionarySP WrapOptionsDict(StructuredData::DictionarySP options_dict_sp)
void SetSCMatchesByLine(SearchFilter &filter, SymbolContextList &sc_list, bool skip_prologue, llvm::StringRef log_ident, uint32_t line=0, std::optional< uint16_t > column=std::nullopt)
Takes a symbol context list of matches which supposedly represent the same file and line number in a ...
lldb::BreakpointSP GetBreakpoint() const
This gets the breakpoint for this resolver.
BreakpointResolver(const lldb::BreakpointSP &bkpt, unsigned char resolverType, lldb::addr_t offset=0, bool offset_is_insn_count=false)
The breakpoint resolver need to have a breakpoint for "ResolveBreakpoint to make sense.
A class that describes the declaration location of a lldb object.
Definition Declaration.h:24
uint32_t GetLine() const
Get accessor for the declaration line number.
FileSpec & GetFile()
Get accessor for file specification.
A file utility class.
Definition FileSpec.h:57
static bool Equal(const FileSpec &a, const FileSpec &b, bool full)
Definition FileSpec.cpp:306
bool IsRelative() const
Returns true if the filespec represents a relative path.
Definition FileSpec.cpp:512
bool IsCaseSensitive() const
Case sensitivity of path.
Definition FileSpec.h:206
llvm::StringRef GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:234
Declaration & GetDeclaration()
Get accessor for the declaration information.
Definition Function.cpp:54
void GetStartLineSourceInfo(SupportFileNSP &source_file_sp, uint32_t &line_no)
Find the file and line number of the source location of the start of the function.
Definition Function.cpp:272
bool AppendUnique(llvm::StringRef path, llvm::StringRef replacement, bool notify)
Append <path, replacement> pair without duplication.
uint32_t GetSourceRealpathAttemptCount() const
uint32_t GetSourceRealpathCompatibleCount() const
General Outline: Provides the callback and search depth for the SearchFilter search.
virtual bool CompUnitPasses(FileSpec &fileSpec)
Call this method with a FileSpec to see if file spec passes the filter as the name of a compilation u...
"lldb/Core/SourceLocationSpec.h" A source location specifier class.
An error handling class.
Definition Status.h:118
static Status FromErrorString(const char *str)
Definition Status.h:141
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
bool GetValueForKeyAsInteger(llvm::StringRef key, IntType &result) const
bool GetValueForKeyAsString(llvm::StringRef key, llvm::StringRef &result) const
bool GetValueForKeyAsBoolean(llvm::StringRef key, bool &result) const
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
Defines a list of symbol context objects.
bool GetContextAtIndex(size_t idx, SymbolContext &sc) const
Get accessor for a symbol context at index idx.
uint32_t GetSize() const
Get accessor for a symbol context list size.
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
Block * block
The Block for a given query.
lldb::ModuleSP module_sp
The Module for a given query.
LineEntry line_entry
The LineEntry for a given query.
RealpathPrefixes GetSourceRealpathPrefixes() const
Definition Target.cpp:5334
PathMappingList & GetSourcePathMap() const
Definition Target.cpp:5445
bool GetAutoSourceMapRelative() const
Definition Target.cpp:5461
void IncreaseSourceRealpathAttemptCount(uint32_t count)
void IncreaseSourceRealpathCompatibleCount(uint32_t count)
TargetStats & GetStatistics()
Definition Target.h:2181
#define LLDB_INVALID_COLUMN_NUMBER
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:339
NonNullSharedPtr< lldb_private::SupportFile > SupportFileNSP
Definition SupportFile.h:80
std::shared_ptr< lldb_private::BreakpointResolver > BreakpointResolverSP
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
uint64_t addr_t
Definition lldb-types.h:80
uint32_t line
The source line number, or LLDB_INVALID_LINE_NUMBER if there is no line number information.
Definition LineEntry.h:151
const FileSpec & GetFile() const
Helper to access the file.
Definition LineEntry.h:134
SupportFileNSP file_sp
The source file, possibly mapped by the target.source-map setting.
Definition LineEntry.h:144