1 //===-- BreakpointResolverFileLine.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/Breakpoint/BreakpointResolverFileLine.h"
10 
11 #include "lldb/Breakpoint/BreakpointLocation.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Symbol/CompileUnit.h"
14 #include "lldb/Symbol/Function.h"
15 #include "lldb/Utility/Log.h"
16 #include "lldb/Utility/StreamString.h"
17 
18 using namespace lldb;
19 using namespace lldb_private;
20 
21 // BreakpointResolverFileLine:
BreakpointResolverFileLine(Breakpoint * bkpt,const FileSpec & file_spec,uint32_t line_no,uint32_t column,lldb::addr_t offset,bool check_inlines,bool skip_prologue,bool exact_match)22 BreakpointResolverFileLine::BreakpointResolverFileLine(
23     Breakpoint *bkpt, const FileSpec &file_spec, uint32_t line_no,
24     uint32_t column, lldb::addr_t offset, bool check_inlines,
25     bool skip_prologue, bool exact_match)
26     : BreakpointResolver(bkpt, BreakpointResolver::FileLineResolver, offset),
27       m_file_spec(file_spec), m_line_number(line_no), m_column(column),
28       m_inlines(check_inlines), m_skip_prologue(skip_prologue),
29       m_exact_match(exact_match) {}
30 
~BreakpointResolverFileLine()31 BreakpointResolverFileLine::~BreakpointResolverFileLine() {}
32 
CreateFromStructuredData(Breakpoint * bkpt,const StructuredData::Dictionary & options_dict,Status & error)33 BreakpointResolver *BreakpointResolverFileLine::CreateFromStructuredData(
34     Breakpoint *bkpt, const StructuredData::Dictionary &options_dict,
35     Status &error) {
36   llvm::StringRef filename;
37   uint32_t line_no;
38   uint32_t column;
39   bool check_inlines;
40   bool skip_prologue;
41   bool exact_match;
42   bool success;
43 
44   lldb::addr_t offset = 0;
45 
46   success = options_dict.GetValueForKeyAsString(GetKey(OptionNames::FileName),
47                                                 filename);
48   if (!success) {
49     error.SetErrorString("BRFL::CFSD: Couldn't find filename entry.");
50     return nullptr;
51   }
52 
53   success = options_dict.GetValueForKeyAsInteger(
54       GetKey(OptionNames::LineNumber), line_no);
55   if (!success) {
56     error.SetErrorString("BRFL::CFSD: Couldn't find line number entry.");
57     return nullptr;
58   }
59 
60   success =
61       options_dict.GetValueForKeyAsInteger(GetKey(OptionNames::Column), column);
62   if (!success) {
63     // Backwards compatibility.
64     column = 0;
65   }
66 
67   success = options_dict.GetValueForKeyAsBoolean(GetKey(OptionNames::Inlines),
68                                                  check_inlines);
69   if (!success) {
70     error.SetErrorString("BRFL::CFSD: Couldn't find check inlines entry.");
71     return nullptr;
72   }
73 
74   success = options_dict.GetValueForKeyAsBoolean(
75       GetKey(OptionNames::SkipPrologue), skip_prologue);
76   if (!success) {
77     error.SetErrorString("BRFL::CFSD: Couldn't find skip prologue entry.");
78     return nullptr;
79   }
80 
81   success = options_dict.GetValueForKeyAsBoolean(
82       GetKey(OptionNames::ExactMatch), exact_match);
83   if (!success) {
84     error.SetErrorString("BRFL::CFSD: Couldn't find exact match entry.");
85     return nullptr;
86   }
87 
88   FileSpec file_spec(filename);
89 
90   return new BreakpointResolverFileLine(bkpt, file_spec, line_no, column,
91                                         offset, check_inlines, skip_prologue,
92                                         exact_match);
93 }
94 
95 StructuredData::ObjectSP
SerializeToStructuredData()96 BreakpointResolverFileLine::SerializeToStructuredData() {
97   StructuredData::DictionarySP options_dict_sp(
98       new StructuredData::Dictionary());
99 
100   options_dict_sp->AddStringItem(GetKey(OptionNames::FileName),
101                                  m_file_spec.GetPath());
102   options_dict_sp->AddIntegerItem(GetKey(OptionNames::LineNumber),
103                                   m_line_number);
104   options_dict_sp->AddIntegerItem(GetKey(OptionNames::Column),
105                                   m_column);
106   options_dict_sp->AddBooleanItem(GetKey(OptionNames::Inlines), m_inlines);
107   options_dict_sp->AddBooleanItem(GetKey(OptionNames::SkipPrologue),
108                                   m_skip_prologue);
109   options_dict_sp->AddBooleanItem(GetKey(OptionNames::ExactMatch),
110                                   m_exact_match);
111 
112   return WrapOptionsDict(options_dict_sp);
113 }
114 
115 // Filter the symbol context list to remove contexts where the line number was
116 // moved into a new function. We do this conservatively, so if e.g. we cannot
117 // resolve the function in the context (which can happen in case of line-table-
118 // only debug info), we leave the context as is. The trickiest part here is
119 // handling inlined functions -- in this case we need to make sure we look at
120 // the declaration line of the inlined function, NOT the function it was
121 // inlined into.
FilterContexts(SymbolContextList & sc_list,bool is_relative)122 void BreakpointResolverFileLine::FilterContexts(SymbolContextList &sc_list,
123                                                 bool is_relative) {
124   if (m_exact_match)
125     return; // Nothing to do. Contexts are precise.
126 
127   llvm::StringRef relative_path;
128   if (is_relative)
129     relative_path = m_file_spec.GetDirectory().GetStringRef();
130 
131   Log * log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS);
132   for(uint32_t i = 0; i < sc_list.GetSize(); ++i) {
133     SymbolContext sc;
134     sc_list.GetContextAtIndex(i, sc);
135     if (is_relative) {
136       // If the path was relative, make sure any matches match as long as the
137       // relative parts of the path match the path from support files
138       auto sc_dir = sc.line_entry.file.GetDirectory().GetStringRef();
139       if (!sc_dir.endswith(relative_path)) {
140         // We had a relative path specified and the relative directory doesn't
141         // match so remove this one
142         LLDB_LOG(log, "removing not matching relative path {0} since it "
143                 "doesn't end with {1}", sc_dir, relative_path);
144         sc_list.RemoveContextAtIndex(i);
145         --i;
146         continue;
147       }
148     }
149 
150     if (!sc.block)
151       continue;
152 
153     FileSpec file;
154     uint32_t line;
155     const Block *inline_block = sc.block->GetContainingInlinedBlock();
156     if (inline_block) {
157       const Declaration &inline_declaration = inline_block->GetInlinedFunctionInfo()->GetDeclaration();
158       if (!inline_declaration.IsValid())
159         continue;
160       file = inline_declaration.GetFile();
161       line = inline_declaration.GetLine();
162     } else if (sc.function)
163       sc.function->GetStartLineSourceInfo(file, line);
164     else
165       continue;
166 
167     if (file != sc.line_entry.file) {
168       LLDB_LOG(log, "unexpected symbol context file {0}", sc.line_entry.file);
169       continue;
170     }
171 
172     // Compare the requested line number with the line of the function
173     // declaration. In case of a function declared as:
174     //
175     // int
176     // foo()
177     // {
178     //   ...
179     //
180     // the compiler will set the declaration line to the "foo" line, which is
181     // the reason why we have -1 here. This can fail in case of two inline
182     // functions defined back-to-back:
183     //
184     // inline int foo1() { ... }
185     // inline int foo2() { ... }
186     //
187     // but that's the best we can do for now.
188     // One complication, if the line number returned from GetStartLineSourceInfo
189     // is 0, then we can't do this calculation.  That can happen if
190     // GetStartLineSourceInfo gets an error, or if the first line number in
191     // the function really is 0 - which happens for some languages.
192     const int decl_line_is_too_late_fudge = 1;
193     if (line && m_line_number < line - decl_line_is_too_late_fudge) {
194       LLDB_LOG(log, "removing symbol context at {0}:{1}", file, line);
195       sc_list.RemoveContextAtIndex(i);
196       --i;
197     }
198   }
199 }
200 
SearchCallback(SearchFilter & filter,SymbolContext & context,Address * addr)201 Searcher::CallbackReturn BreakpointResolverFileLine::SearchCallback(
202     SearchFilter &filter, SymbolContext &context, Address *addr) {
203   SymbolContextList sc_list;
204 
205   assert(m_breakpoint != nullptr);
206 
207   // There is a tricky bit here.  You can have two compilation units that
208   // #include the same file, and in one of them the function at m_line_number
209   // is used (and so code and a line entry for it is generated) but in the
210   // other it isn't.  If we considered the CU's independently, then in the
211   // second inclusion, we'd move the breakpoint to the next function that
212   // actually generated code in the header file.  That would end up being
213   // confusing.  So instead, we do the CU iterations by hand here, then scan
214   // through the complete list of matches, and figure out the closest line
215   // number match, and only set breakpoints on that match.
216 
217   // Note also that if file_spec only had a file name and not a directory,
218   // there may be many different file spec's in the resultant list.  The
219   // closest line match for one will not be right for some totally different
220   // file.  So we go through the match list and pull out the sets that have the
221   // same file spec in their line_entry and treat each set separately.
222 
223   FileSpec search_file_spec = m_file_spec;
224   const bool is_relative = m_file_spec.IsRelative();
225   if (is_relative)
226     search_file_spec.GetDirectory().Clear();
227 
228   const size_t num_comp_units = context.module_sp->GetNumCompileUnits();
229   for (size_t i = 0; i < num_comp_units; i++) {
230     CompUnitSP cu_sp(context.module_sp->GetCompileUnitAtIndex(i));
231     if (cu_sp) {
232       if (filter.CompUnitPasses(*cu_sp))
233         cu_sp->ResolveSymbolContext(search_file_spec, m_line_number, m_inlines,
234                                     m_exact_match, eSymbolContextEverything,
235                                     sc_list);
236     }
237   }
238 
239   FilterContexts(sc_list, is_relative);
240 
241   StreamString s;
242   s.Printf("for %s:%d ", m_file_spec.GetFilename().AsCString("<Unknown>"),
243            m_line_number);
244 
245   SetSCMatchesByLine(filter, sc_list, m_skip_prologue, s.GetString(),
246                      m_line_number, m_column);
247 
248   return Searcher::eCallbackReturnContinue;
249 }
250 
GetDepth()251 lldb::SearchDepth BreakpointResolverFileLine::GetDepth() {
252   return lldb::eSearchDepthModule;
253 }
254 
GetDescription(Stream * s)255 void BreakpointResolverFileLine::GetDescription(Stream *s) {
256   s->Printf("file = '%s', line = %u, ", m_file_spec.GetPath().c_str(),
257             m_line_number);
258   if (m_column)
259     s->Printf("column = %u, ", m_column);
260   s->Printf("exact_match = %d", m_exact_match);
261 }
262 
Dump(Stream * s) const263 void BreakpointResolverFileLine::Dump(Stream *s) const {}
264 
265 lldb::BreakpointResolverSP
CopyForBreakpoint(Breakpoint & breakpoint)266 BreakpointResolverFileLine::CopyForBreakpoint(Breakpoint &breakpoint) {
267   lldb::BreakpointResolverSP ret_sp(new BreakpointResolverFileLine(
268       &breakpoint, m_file_spec, m_line_number, m_column, m_offset, m_inlines,
269       m_skip_prologue, m_exact_match));
270 
271   return ret_sp;
272 }
273