1 //===-- BreakpointResolverName.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/BreakpointResolverName.h"
10 
11 #include "lldb/Breakpoint/BreakpointLocation.h"
12 #include "lldb/Core/Architecture.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Symbol/Block.h"
15 #include "lldb/Symbol/Function.h"
16 #include "lldb/Symbol/Symbol.h"
17 #include "lldb/Symbol/SymbolContext.h"
18 #include "lldb/Target/Target.h"
19 #include "lldb/Target/Language.h"
20 #include "lldb/Utility/Log.h"
21 #include "lldb/Utility/StreamString.h"
22 
23 using namespace lldb;
24 using namespace lldb_private;
25 
26 BreakpointResolverName::BreakpointResolverName(
27     Breakpoint *bkpt, const char *name_cstr, FunctionNameType name_type_mask,
28     LanguageType language, Breakpoint::MatchType type, lldb::addr_t offset,
29     bool skip_prologue)
30     : BreakpointResolver(bkpt, BreakpointResolver::NameResolver, offset),
31       m_class_name(), m_regex(), m_match_type(type), m_language(language),
32       m_skip_prologue(skip_prologue) {
33   if (m_match_type == Breakpoint::Regexp) {
34     m_regex = RegularExpression(llvm::StringRef::withNullAsEmpty(name_cstr));
35     if (!m_regex.IsValid()) {
36       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
37 
38       if (log)
39         log->Warning("function name regexp: \"%s\" did not compile.",
40                      name_cstr);
41     }
42   } else {
43     AddNameLookup(ConstString(name_cstr), name_type_mask);
44   }
45 }
46 
47 BreakpointResolverName::BreakpointResolverName(
48     Breakpoint *bkpt, const char *names[], size_t num_names,
49     FunctionNameType name_type_mask, LanguageType language, lldb::addr_t offset,
50     bool skip_prologue)
51     : BreakpointResolver(bkpt, BreakpointResolver::NameResolver, offset),
52       m_match_type(Breakpoint::Exact), m_language(language),
53       m_skip_prologue(skip_prologue) {
54   for (size_t i = 0; i < num_names; i++) {
55     AddNameLookup(ConstString(names[i]), name_type_mask);
56   }
57 }
58 
59 BreakpointResolverName::BreakpointResolverName(Breakpoint *bkpt,
60                                                std::vector<std::string> names,
61                                                FunctionNameType name_type_mask,
62                                                LanguageType language,
63                                                lldb::addr_t offset,
64                                                bool skip_prologue)
65     : BreakpointResolver(bkpt, BreakpointResolver::NameResolver, offset),
66       m_match_type(Breakpoint::Exact), m_language(language),
67       m_skip_prologue(skip_prologue) {
68   for (const std::string &name : names) {
69     AddNameLookup(ConstString(name.c_str(), name.size()), name_type_mask);
70   }
71 }
72 
73 BreakpointResolverName::BreakpointResolverName(Breakpoint *bkpt,
74                                                RegularExpression func_regex,
75                                                lldb::LanguageType language,
76                                                lldb::addr_t offset,
77                                                bool skip_prologue)
78     : BreakpointResolver(bkpt, BreakpointResolver::NameResolver, offset),
79       m_class_name(nullptr), m_regex(std::move(func_regex)),
80       m_match_type(Breakpoint::Regexp), m_language(language),
81       m_skip_prologue(skip_prologue) {}
82 
83 BreakpointResolverName::~BreakpointResolverName() = default;
84 
85 BreakpointResolverName::BreakpointResolverName(
86     const BreakpointResolverName &rhs)
87     : BreakpointResolver(rhs.m_breakpoint, BreakpointResolver::NameResolver,
88                          rhs.m_offset),
89       m_lookups(rhs.m_lookups), m_class_name(rhs.m_class_name),
90       m_regex(rhs.m_regex), m_match_type(rhs.m_match_type),
91       m_language(rhs.m_language), m_skip_prologue(rhs.m_skip_prologue) {}
92 
93 BreakpointResolver *BreakpointResolverName::CreateFromStructuredData(
94     Breakpoint *bkpt, const StructuredData::Dictionary &options_dict,
95     Status &error) {
96   LanguageType language = eLanguageTypeUnknown;
97   llvm::StringRef language_name;
98   bool success = options_dict.GetValueForKeyAsString(
99       GetKey(OptionNames::LanguageName), language_name);
100   if (success) {
101     language = Language::GetLanguageTypeFromString(language_name);
102     if (language == eLanguageTypeUnknown) {
103       error.SetErrorStringWithFormatv("BRN::CFSD: Unknown language: {0}.",
104                                       language_name);
105       return nullptr;
106     }
107   }
108 
109   lldb::addr_t offset = 0;
110   success =
111       options_dict.GetValueForKeyAsInteger(GetKey(OptionNames::Offset), offset);
112   if (!success) {
113     error.SetErrorStringWithFormat("BRN::CFSD: Missing offset entry.");
114     return nullptr;
115   }
116 
117   bool skip_prologue;
118   success = options_dict.GetValueForKeyAsBoolean(
119       GetKey(OptionNames::SkipPrologue), skip_prologue);
120   if (!success) {
121     error.SetErrorStringWithFormat("BRN::CFSD: Missing Skip prologue entry.");
122     return nullptr;
123   }
124 
125   llvm::StringRef regex_text;
126   success = options_dict.GetValueForKeyAsString(
127       GetKey(OptionNames::RegexString), regex_text);
128   if (success) {
129     return new BreakpointResolverName(bkpt, RegularExpression(regex_text),
130                                       language, offset, skip_prologue);
131   } else {
132     StructuredData::Array *names_array;
133     success = options_dict.GetValueForKeyAsArray(
134         GetKey(OptionNames::SymbolNameArray), names_array);
135     if (!success) {
136       error.SetErrorStringWithFormat("BRN::CFSD: Missing symbol names entry.");
137       return nullptr;
138     }
139     StructuredData::Array *names_mask_array;
140     success = options_dict.GetValueForKeyAsArray(
141         GetKey(OptionNames::NameMaskArray), names_mask_array);
142     if (!success) {
143       error.SetErrorStringWithFormat(
144           "BRN::CFSD: Missing symbol names mask entry.");
145       return nullptr;
146     }
147 
148     size_t num_elem = names_array->GetSize();
149     if (num_elem != names_mask_array->GetSize()) {
150       error.SetErrorString(
151           "BRN::CFSD: names and names mask arrays have different sizes.");
152       return nullptr;
153     }
154 
155     if (num_elem == 0) {
156       error.SetErrorString(
157           "BRN::CFSD: no name entry in a breakpoint by name breakpoint.");
158       return nullptr;
159     }
160     std::vector<std::string> names;
161     std::vector<FunctionNameType> name_masks;
162     for (size_t i = 0; i < num_elem; i++) {
163       llvm::StringRef name;
164 
165       success = names_array->GetItemAtIndexAsString(i, name);
166       if (!success) {
167         error.SetErrorString("BRN::CFSD: name entry is not a string.");
168         return nullptr;
169       }
170       std::underlying_type<FunctionNameType>::type fnt;
171       success = names_mask_array->GetItemAtIndexAsInteger(i, fnt);
172       if (!success) {
173         error.SetErrorString("BRN::CFSD: name mask entry is not an integer.");
174         return nullptr;
175       }
176       names.push_back(std::string(name));
177       name_masks.push_back(static_cast<FunctionNameType>(fnt));
178     }
179 
180     BreakpointResolverName *resolver = new BreakpointResolverName(
181         bkpt, names[0].c_str(), name_masks[0], language,
182         Breakpoint::MatchType::Exact, offset, skip_prologue);
183     for (size_t i = 1; i < num_elem; i++) {
184       resolver->AddNameLookup(ConstString(names[i]), name_masks[i]);
185     }
186     return resolver;
187   }
188 }
189 
190 StructuredData::ObjectSP BreakpointResolverName::SerializeToStructuredData() {
191   StructuredData::DictionarySP options_dict_sp(
192       new StructuredData::Dictionary());
193 
194   if (m_regex.IsValid()) {
195     options_dict_sp->AddStringItem(GetKey(OptionNames::RegexString),
196                                    m_regex.GetText());
197   } else {
198     StructuredData::ArraySP names_sp(new StructuredData::Array());
199     StructuredData::ArraySP name_masks_sp(new StructuredData::Array());
200     for (auto lookup : m_lookups) {
201       names_sp->AddItem(StructuredData::StringSP(
202           new StructuredData::String(lookup.GetName().GetStringRef())));
203       name_masks_sp->AddItem(StructuredData::IntegerSP(
204           new StructuredData::Integer(lookup.GetNameTypeMask())));
205     }
206     options_dict_sp->AddItem(GetKey(OptionNames::SymbolNameArray), names_sp);
207     options_dict_sp->AddItem(GetKey(OptionNames::NameMaskArray), name_masks_sp);
208   }
209   if (m_language != eLanguageTypeUnknown)
210     options_dict_sp->AddStringItem(
211         GetKey(OptionNames::LanguageName),
212         Language::GetNameForLanguageType(m_language));
213   options_dict_sp->AddBooleanItem(GetKey(OptionNames::SkipPrologue),
214                                   m_skip_prologue);
215 
216   return WrapOptionsDict(options_dict_sp);
217 }
218 
219 void BreakpointResolverName::AddNameLookup(ConstString name,
220                                            FunctionNameType name_type_mask) {
221 
222   Module::LookupInfo lookup(name, name_type_mask, m_language);
223   m_lookups.emplace_back(lookup);
224 
225   auto add_variant_funcs = [&](Language *lang) {
226     for (ConstString variant_name : lang->GetMethodNameVariants(name)) {
227       Module::LookupInfo variant_lookup(name, name_type_mask,
228                                         lang->GetLanguageType());
229       variant_lookup.SetLookupName(variant_name);
230       m_lookups.emplace_back(variant_lookup);
231     }
232     return true;
233   };
234 
235   if (Language *lang = Language::FindPlugin(m_language)) {
236     add_variant_funcs(lang);
237   } else {
238     // Most likely m_language is eLanguageTypeUnknown. We check each language for
239     // possible variants or more qualified names and create lookups for those as
240     // well.
241     Language::ForEach(add_variant_funcs);
242   }
243 }
244 
245 // FIXME: Right now we look at the module level, and call the module's
246 // "FindFunctions".
247 // Greg says he will add function tables, maybe at the CompileUnit level to
248 // accelerate function lookup.  At that point, we should switch the depth to
249 // CompileUnit, and look in these tables.
250 
251 Searcher::CallbackReturn
252 BreakpointResolverName::SearchCallback(SearchFilter &filter,
253                                        SymbolContext &context, Address *addr) {
254   SymbolContextList func_list;
255   // SymbolContextList sym_list;
256 
257   uint32_t i;
258   bool new_location;
259   Address break_addr;
260   assert(m_breakpoint != nullptr);
261 
262   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
263 
264   if (m_class_name) {
265     if (log)
266       log->Warning("Class/method function specification not supported yet.\n");
267     return Searcher::eCallbackReturnStop;
268   }
269   bool filter_by_cu =
270       (filter.GetFilterRequiredItems() & eSymbolContextCompUnit) != 0;
271   bool filter_by_language = (m_language != eLanguageTypeUnknown);
272   const bool include_symbols = !filter_by_cu;
273   const bool include_inlines = true;
274 
275   switch (m_match_type) {
276   case Breakpoint::Exact:
277     if (context.module_sp) {
278       for (const auto &lookup : m_lookups) {
279         const size_t start_func_idx = func_list.GetSize();
280         context.module_sp->FindFunctions(
281             lookup.GetLookupName(), CompilerDeclContext(),
282             lookup.GetNameTypeMask(), include_symbols, include_inlines,
283             func_list);
284 
285         const size_t end_func_idx = func_list.GetSize();
286 
287         if (start_func_idx < end_func_idx)
288           lookup.Prune(func_list, start_func_idx);
289       }
290     }
291     break;
292   case Breakpoint::Regexp:
293     if (context.module_sp) {
294       context.module_sp->FindFunctions(
295           m_regex,
296           !filter_by_cu, // include symbols only if we aren't filtering by CU
297           include_inlines, func_list);
298     }
299     break;
300   case Breakpoint::Glob:
301     if (log)
302       log->Warning("glob is not supported yet.");
303     break;
304   }
305 
306   // If the filter specifies a Compilation Unit, remove the ones that don't
307   // pass at this point.
308   if (filter_by_cu || filter_by_language) {
309     uint32_t num_functions = func_list.GetSize();
310 
311     for (size_t idx = 0; idx < num_functions; idx++) {
312       bool remove_it = false;
313       SymbolContext sc;
314       func_list.GetContextAtIndex(idx, sc);
315       if (filter_by_cu) {
316         if (!sc.comp_unit || !filter.CompUnitPasses(*sc.comp_unit))
317           remove_it = true;
318       }
319 
320       if (filter_by_language) {
321         LanguageType sym_language = sc.GetLanguage();
322         if ((Language::GetPrimaryLanguage(sym_language) !=
323              Language::GetPrimaryLanguage(m_language)) &&
324             (sym_language != eLanguageTypeUnknown)) {
325           remove_it = true;
326         }
327       }
328 
329       if (remove_it) {
330         func_list.RemoveContextAtIndex(idx);
331         num_functions--;
332         idx--;
333       }
334     }
335   }
336 
337   // Remove any duplicates between the function list and the symbol list
338   SymbolContext sc;
339   if (func_list.GetSize()) {
340     for (i = 0; i < func_list.GetSize(); i++) {
341       if (func_list.GetContextAtIndex(i, sc)) {
342         bool is_reexported = false;
343 
344         if (sc.block && sc.block->GetInlinedFunctionInfo()) {
345           if (!sc.block->GetStartAddress(break_addr))
346             break_addr.Clear();
347         } else if (sc.function) {
348           break_addr = sc.function->GetAddressRange().GetBaseAddress();
349           if (m_skip_prologue && break_addr.IsValid()) {
350             const uint32_t prologue_byte_size =
351                 sc.function->GetPrologueByteSize();
352             if (prologue_byte_size)
353               break_addr.SetOffset(break_addr.GetOffset() + prologue_byte_size);
354           }
355         } else if (sc.symbol) {
356           if (sc.symbol->GetType() == eSymbolTypeReExported) {
357             const Symbol *actual_symbol =
358                 sc.symbol->ResolveReExportedSymbol(m_breakpoint->GetTarget());
359             if (actual_symbol) {
360               is_reexported = true;
361               break_addr = actual_symbol->GetAddress();
362             }
363           } else {
364             break_addr = sc.symbol->GetAddress();
365           }
366 
367           if (m_skip_prologue && break_addr.IsValid()) {
368             const uint32_t prologue_byte_size =
369                 sc.symbol->GetPrologueByteSize();
370             if (prologue_byte_size)
371               break_addr.SetOffset(break_addr.GetOffset() + prologue_byte_size);
372             else {
373               const Architecture *arch =
374                   m_breakpoint->GetTarget().GetArchitecturePlugin();
375               if (arch)
376                 arch->AdjustBreakpointAddress(*sc.symbol, break_addr);
377             }
378           }
379         }
380 
381         if (break_addr.IsValid()) {
382           if (filter.AddressPasses(break_addr)) {
383             BreakpointLocationSP bp_loc_sp(
384                 AddLocation(break_addr, &new_location));
385             bp_loc_sp->SetIsReExported(is_reexported);
386             if (bp_loc_sp && new_location && !m_breakpoint->IsInternal()) {
387               if (log) {
388                 StreamString s;
389                 bp_loc_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
390                 LLDB_LOGF(log, "Added location: %s\n", s.GetData());
391               }
392             }
393           }
394         }
395       }
396     }
397   }
398 
399   return Searcher::eCallbackReturnContinue;
400 }
401 
402 lldb::SearchDepth BreakpointResolverName::GetDepth() {
403   return lldb::eSearchDepthModule;
404 }
405 
406 void BreakpointResolverName::GetDescription(Stream *s) {
407   if (m_match_type == Breakpoint::Regexp)
408     s->Printf("regex = '%s'", m_regex.GetText().str().c_str());
409   else {
410     size_t num_names = m_lookups.size();
411     if (num_names == 1)
412       s->Printf("name = '%s'", m_lookups[0].GetName().GetCString());
413     else {
414       s->Printf("names = {");
415       for (size_t i = 0; i < num_names; i++) {
416         s->Printf("%s'%s'", (i == 0 ? "" : ", "),
417                   m_lookups[i].GetName().GetCString());
418       }
419       s->Printf("}");
420     }
421   }
422   if (m_language != eLanguageTypeUnknown) {
423     s->Printf(", language = %s", Language::GetNameForLanguageType(m_language));
424   }
425 }
426 
427 void BreakpointResolverName::Dump(Stream *s) const {}
428 
429 lldb::BreakpointResolverSP
430 BreakpointResolverName::CopyForBreakpoint(Breakpoint &breakpoint) {
431   lldb::BreakpointResolverSP ret_sp(new BreakpointResolverName(*this));
432   ret_sp->SetBreakpoint(&breakpoint);
433   return ret_sp;
434 }
435