1 //===-- BreakpointResolver.cpp ----------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Breakpoint/BreakpointResolver.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 #include "lldb/Breakpoint/Breakpoint.h"
17 #include "lldb/Breakpoint/BreakpointLocation.h"
18 // Have to include the other breakpoint resolver types here so the static
19 // create from StructuredData can call them.
20 #include "lldb/Breakpoint/BreakpointResolverAddress.h"
21 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
22 #include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
23 #include "lldb/Breakpoint/BreakpointResolverName.h"
24 #include "lldb/Core/Address.h"
25 #include "lldb/Core/ModuleList.h"
26 #include "lldb/Core/SearchFilter.h"
27 #include "lldb/Symbol/CompileUnit.h"
28 #include "lldb/Symbol/Function.h"
29 #include "lldb/Symbol/SymbolContext.h"
30 #include "lldb/Target/Target.h"
31 #include "lldb/Utility/Log.h"
32 #include "lldb/Utility/Stream.h"
33 #include "lldb/Utility/StreamString.h"
34 
35 using namespace lldb_private;
36 using namespace lldb;
37 
38 //----------------------------------------------------------------------
39 // BreakpointResolver:
40 //----------------------------------------------------------------------
41 const char *BreakpointResolver::g_ty_to_name[] = {"FileAndLine", "Address",
42                                                   "SymbolName",  "SourceRegex",
43                                                   "Exception",   "Unknown"};
44 
45 const char *BreakpointResolver::g_option_names[static_cast<uint32_t>(
46     BreakpointResolver::OptionNames::LastOptionName)] = {
47     "AddressOffset", "Exact",        "FileName",   "Inlines", "Language",
48     "LineNumber",    "ModuleName",   "NameMask",   "Offset",  "Regex",
49     "SectionName",   "SkipPrologue", "SymbolNames"};
50 
51 const char *BreakpointResolver::ResolverTyToName(enum ResolverTy type) {
52   if (type > LastKnownResolverType)
53     return g_ty_to_name[UnknownResolver];
54 
55   return g_ty_to_name[type];
56 }
57 
58 BreakpointResolver::ResolverTy
59 BreakpointResolver::NameToResolverTy(llvm::StringRef name) {
60   for (size_t i = 0; i < LastKnownResolverType; i++) {
61     if (name == g_ty_to_name[i])
62       return (ResolverTy)i;
63   }
64   return UnknownResolver;
65 }
66 
67 BreakpointResolver::BreakpointResolver(Breakpoint *bkpt,
68                                        const unsigned char resolverTy,
69                                        lldb::addr_t offset)
70     : m_breakpoint(bkpt), m_offset(offset), SubclassID(resolverTy) {}
71 
72 BreakpointResolver::~BreakpointResolver() {}
73 
74 BreakpointResolverSP BreakpointResolver::CreateFromStructuredData(
75     const StructuredData::Dictionary &resolver_dict, Status &error) {
76   BreakpointResolverSP result_sp;
77   if (!resolver_dict.IsValid()) {
78     error.SetErrorString("Can't deserialize from an invalid data object.");
79     return result_sp;
80   }
81 
82   llvm::StringRef subclass_name;
83 
84   bool success = resolver_dict.GetValueForKeyAsString(
85       GetSerializationSubclassKey(), subclass_name);
86 
87   if (!success) {
88     error.SetErrorStringWithFormat(
89         "Resolver data missing subclass resolver key");
90     return result_sp;
91   }
92 
93   ResolverTy resolver_type = NameToResolverTy(subclass_name);
94   if (resolver_type == UnknownResolver) {
95     error.SetErrorStringWithFormatv("Unknown resolver type: {0}.",
96                                     subclass_name);
97     return result_sp;
98   }
99 
100   StructuredData::Dictionary *subclass_options = nullptr;
101   success = resolver_dict.GetValueForKeyAsDictionary(
102       GetSerializationSubclassOptionsKey(), subclass_options);
103   if (!success || !subclass_options || !subclass_options->IsValid()) {
104     error.SetErrorString("Resolver data missing subclass options key.");
105     return result_sp;
106   }
107 
108   lldb::addr_t offset;
109   success = subclass_options->GetValueForKeyAsInteger(
110       GetKey(OptionNames::Offset), offset);
111   if (!success) {
112     error.SetErrorString("Resolver data missing offset options key.");
113     return result_sp;
114   }
115 
116   BreakpointResolver *resolver;
117 
118   switch (resolver_type) {
119   case FileLineResolver:
120     resolver = BreakpointResolverFileLine::CreateFromStructuredData(
121         nullptr, *subclass_options, error);
122     break;
123   case AddressResolver:
124     resolver = BreakpointResolverAddress::CreateFromStructuredData(
125         nullptr, *subclass_options, error);
126     break;
127   case NameResolver:
128     resolver = BreakpointResolverName::CreateFromStructuredData(
129         nullptr, *subclass_options, error);
130     break;
131   case FileRegexResolver:
132     resolver = BreakpointResolverFileRegex::CreateFromStructuredData(
133         nullptr, *subclass_options, error);
134     break;
135   case ExceptionResolver:
136     error.SetErrorString("Exception resolvers are hard.");
137     break;
138   default:
139     llvm_unreachable("Should never get an unresolvable resolver type.");
140   }
141 
142   if (!error.Success()) {
143     return result_sp;
144   } else {
145     // Add on the global offset option:
146     resolver->SetOffset(offset);
147     return BreakpointResolverSP(resolver);
148   }
149 }
150 
151 StructuredData::DictionarySP BreakpointResolver::WrapOptionsDict(
152     StructuredData::DictionarySP options_dict_sp) {
153   if (!options_dict_sp || !options_dict_sp->IsValid())
154     return StructuredData::DictionarySP();
155 
156   StructuredData::DictionarySP type_dict_sp(new StructuredData::Dictionary());
157   type_dict_sp->AddStringItem(GetSerializationSubclassKey(), GetResolverName());
158   type_dict_sp->AddItem(GetSerializationSubclassOptionsKey(), options_dict_sp);
159 
160   // Add the m_offset to the dictionary:
161   options_dict_sp->AddIntegerItem(GetKey(OptionNames::Offset), m_offset);
162 
163   return type_dict_sp;
164 }
165 
166 void BreakpointResolver::SetBreakpoint(Breakpoint *bkpt) {
167   m_breakpoint = bkpt;
168 }
169 
170 void BreakpointResolver::ResolveBreakpointInModules(SearchFilter &filter,
171                                                     ModuleList &modules) {
172   filter.SearchInModuleList(*this, modules);
173 }
174 
175 void BreakpointResolver::ResolveBreakpoint(SearchFilter &filter) {
176   filter.Search(*this);
177 }
178 
179 void BreakpointResolver::SetSCMatchesByLine(SearchFilter &filter,
180                                             SymbolContextList &sc_list,
181                                             bool skip_prologue,
182                                             llvm::StringRef log_ident) {
183   llvm::SmallVector<SymbolContext, 16> all_scs;
184   for (uint32_t i = 0; i < sc_list.GetSize(); ++i)
185     all_scs.push_back(sc_list[i]);
186 
187   while (all_scs.size()) {
188     // ResolveSymbolContext will always return a number that is >= the
189     // line number you pass in. So the smaller line number is always
190     // better.
191     uint32_t closest_line = UINT32_MAX;
192 
193     // Move all the elements with a matching file spec to the end.
194     auto &match = all_scs[0];
195     auto worklist_begin = std::partition(
196         all_scs.begin(), all_scs.end(), [&](const SymbolContext &sc) {
197           if (sc.line_entry.file == match.line_entry.file ||
198               sc.line_entry.original_file == match.line_entry.original_file) {
199             // When a match is found, keep track of the smallest line number.
200             closest_line = std::min(closest_line, sc.line_entry.line);
201             return false;
202           }
203           return true;
204         });
205 
206     // Within, remove all entries with a larger line number.
207     auto worklist_end = std::remove_if(
208         worklist_begin, all_scs.end(), [&](const SymbolContext &sc) {
209           return closest_line != sc.line_entry.line;
210         });
211 
212     // Sort by file address.
213     std::sort(worklist_begin, worklist_end,
214               [](const SymbolContext &a, const SymbolContext &b) {
215                 return a.line_entry.range.GetBaseAddress().GetFileAddress() <
216                        b.line_entry.range.GetBaseAddress().GetFileAddress();
217               });
218 
219     // Go through and see if there are line table entries that are
220     // contiguous, and if so keep only the first of the contiguous range.
221     // We do this by picking the first location in each lexical block.
222     llvm::SmallDenseSet<Block *, 8> blocks_with_breakpoints;
223     for (auto first = worklist_begin; first != worklist_end; ++first) {
224       assert(!blocks_with_breakpoints.count(first->block));
225       blocks_with_breakpoints.insert(first->block);
226       worklist_end =
227           std::remove_if(std::next(first), worklist_end,
228                          [&](const SymbolContext &sc) {
229                            return blocks_with_breakpoints.count(sc.block);
230                          });
231     }
232 
233     // Make breakpoints out of the closest line number match.
234     for (auto &sc : llvm::make_range(worklist_begin, worklist_end))
235       AddLocation(filter, sc, skip_prologue, log_ident);
236 
237     // Remove all contexts processed by this iteration.
238     all_scs.erase(worklist_begin, all_scs.end());
239   }
240 }
241 
242 void BreakpointResolver::AddLocation(SearchFilter &filter,
243                                      const SymbolContext &sc,
244                                      bool skip_prologue,
245                                      llvm::StringRef log_ident) {
246   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
247   Address line_start = sc.line_entry.range.GetBaseAddress();
248   if (!line_start.IsValid()) {
249     if (log)
250       log->Printf("error: Unable to set breakpoint %s at file address "
251                   "0x%" PRIx64 "\n",
252                   log_ident.str().c_str(), line_start.GetFileAddress());
253     return;
254   }
255 
256   if (!filter.AddressPasses(line_start)) {
257     if (log)
258       log->Printf("Breakpoint %s at file address 0x%" PRIx64
259                   " didn't pass the filter.\n",
260                   log_ident.str().c_str(), line_start.GetFileAddress());
261   }
262 
263   // If the line number is before the prologue end, move it there...
264   bool skipped_prologue = false;
265   if (skip_prologue && sc.function) {
266     Address prologue_addr(sc.function->GetAddressRange().GetBaseAddress());
267     if (prologue_addr.IsValid() && (line_start == prologue_addr)) {
268       const uint32_t prologue_byte_size = sc.function->GetPrologueByteSize();
269       if (prologue_byte_size) {
270         prologue_addr.Slide(prologue_byte_size);
271 
272         if (filter.AddressPasses(prologue_addr)) {
273           skipped_prologue = true;
274           line_start = prologue_addr;
275         }
276       }
277     }
278   }
279 
280   BreakpointLocationSP bp_loc_sp(AddLocation(line_start));
281   if (log && bp_loc_sp && !m_breakpoint->IsInternal()) {
282     StreamString s;
283     bp_loc_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
284     log->Printf("Added location (skipped prologue: %s): %s \n",
285                 skipped_prologue ? "yes" : "no", s.GetData());
286   }
287 }
288 
289 BreakpointLocationSP BreakpointResolver::AddLocation(Address loc_addr,
290                                                      bool *new_location) {
291   loc_addr.Slide(m_offset);
292   return m_breakpoint->AddLocation(loc_addr, new_location);
293 }
294 
295 void BreakpointResolver::SetOffset(lldb::addr_t offset) {
296   // There may already be an offset, so we are actually adjusting location
297   // addresses by the difference.
298   // lldb::addr_t slide = offset - m_offset;
299   // FIXME: We should go fix up all the already set locations for the new
300   // slide.
301 
302   m_offset = offset;
303 }
304