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