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