1 //===-- SymbolFileBreakpad.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 "Plugins/SymbolFile/Breakpad/SymbolFileBreakpad.h"
10 #include "Plugins/ObjectFile/Breakpad/BreakpadRecords.h"
11 #include "Plugins/ObjectFile/Breakpad/ObjectFileBreakpad.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/PluginManager.h"
14 #include "lldb/Core/Section.h"
15 #include "lldb/Host/FileSystem.h"
16 #include "lldb/Symbol/CompileUnit.h"
17 #include "lldb/Symbol/ObjectFile.h"
18 #include "lldb/Symbol/SymbolVendor.h"
19 #include "lldb/Symbol/TypeMap.h"
20 #include "lldb/Utility/Log.h"
21 #include "lldb/Utility/StreamString.h"
22 #include "llvm/ADT/StringExtras.h"
23 
24 using namespace lldb;
25 using namespace lldb_private;
26 using namespace lldb_private::breakpad;
27 
28 LLDB_PLUGIN_DEFINE(SymbolFileBreakpad)
29 
30 char SymbolFileBreakpad::ID;
31 
32 class SymbolFileBreakpad::LineIterator {
33 public:
34   // begin iterator for sections of given type
35   LineIterator(ObjectFile &obj, Record::Kind section_type)
36       : m_obj(&obj), m_section_type(toString(section_type)),
37         m_next_section_idx(0), m_next_line(llvm::StringRef::npos) {
38     ++*this;
39   }
40 
41   // An iterator starting at the position given by the bookmark.
42   LineIterator(ObjectFile &obj, Record::Kind section_type, Bookmark bookmark);
43 
44   // end iterator
45   explicit LineIterator(ObjectFile &obj)
46       : m_obj(&obj),
47         m_next_section_idx(m_obj->GetSectionList()->GetNumSections(0)),
48         m_current_line(llvm::StringRef::npos),
49         m_next_line(llvm::StringRef::npos) {}
50 
51   friend bool operator!=(const LineIterator &lhs, const LineIterator &rhs) {
52     assert(lhs.m_obj == rhs.m_obj);
53     if (lhs.m_next_section_idx != rhs.m_next_section_idx)
54       return true;
55     if (lhs.m_current_line != rhs.m_current_line)
56       return true;
57     assert(lhs.m_next_line == rhs.m_next_line);
58     return false;
59   }
60 
61   const LineIterator &operator++();
62   llvm::StringRef operator*() const {
63     return m_section_text.slice(m_current_line, m_next_line);
64   }
65 
66   Bookmark GetBookmark() const {
67     return Bookmark{m_next_section_idx, m_current_line};
68   }
69 
70 private:
71   ObjectFile *m_obj;
72   ConstString m_section_type;
73   uint32_t m_next_section_idx;
74   llvm::StringRef m_section_text;
75   size_t m_current_line;
76   size_t m_next_line;
77 
78   void FindNextLine() {
79     m_next_line = m_section_text.find('\n', m_current_line);
80     if (m_next_line != llvm::StringRef::npos) {
81       ++m_next_line;
82       if (m_next_line >= m_section_text.size())
83         m_next_line = llvm::StringRef::npos;
84     }
85   }
86 };
87 
88 SymbolFileBreakpad::LineIterator::LineIterator(ObjectFile &obj,
89                                                Record::Kind section_type,
90                                                Bookmark bookmark)
91     : m_obj(&obj), m_section_type(toString(section_type)),
92       m_next_section_idx(bookmark.section), m_current_line(bookmark.offset) {
93   Section &sect =
94       *obj.GetSectionList()->GetSectionAtIndex(m_next_section_idx - 1);
95   assert(sect.GetName() == m_section_type);
96 
97   DataExtractor data;
98   obj.ReadSectionData(&sect, data);
99   m_section_text = toStringRef(data.GetData());
100 
101   assert(m_current_line < m_section_text.size());
102   FindNextLine();
103 }
104 
105 const SymbolFileBreakpad::LineIterator &
106 SymbolFileBreakpad::LineIterator::operator++() {
107   const SectionList &list = *m_obj->GetSectionList();
108   size_t num_sections = list.GetNumSections(0);
109   while (m_next_line != llvm::StringRef::npos ||
110          m_next_section_idx < num_sections) {
111     if (m_next_line != llvm::StringRef::npos) {
112       m_current_line = m_next_line;
113       FindNextLine();
114       return *this;
115     }
116 
117     Section &sect = *list.GetSectionAtIndex(m_next_section_idx++);
118     if (sect.GetName() != m_section_type)
119       continue;
120     DataExtractor data;
121     m_obj->ReadSectionData(&sect, data);
122     m_section_text = toStringRef(data.GetData());
123     m_next_line = 0;
124   }
125   // We've reached the end.
126   m_current_line = m_next_line;
127   return *this;
128 }
129 
130 llvm::iterator_range<SymbolFileBreakpad::LineIterator>
131 SymbolFileBreakpad::lines(Record::Kind section_type) {
132   return llvm::make_range(LineIterator(*m_objfile_sp, section_type),
133                           LineIterator(*m_objfile_sp));
134 }
135 
136 namespace {
137 // A helper class for constructing the list of support files for a given compile
138 // unit.
139 class SupportFileMap {
140 public:
141   // Given a breakpad file ID, return a file ID to be used in the support files
142   // for this compile unit.
143   size_t operator[](size_t file) {
144     return m_map.try_emplace(file, m_map.size() + 1).first->second;
145   }
146 
147   // Construct a FileSpecList containing only the support files relevant for
148   // this compile unit (in the correct order).
149   FileSpecList translate(const FileSpec &cu_spec,
150                          llvm::ArrayRef<FileSpec> all_files);
151 
152 private:
153   llvm::DenseMap<size_t, size_t> m_map;
154 };
155 } // namespace
156 
157 FileSpecList SupportFileMap::translate(const FileSpec &cu_spec,
158                                        llvm::ArrayRef<FileSpec> all_files) {
159   std::vector<FileSpec> result;
160   result.resize(m_map.size() + 1);
161   result[0] = cu_spec;
162   for (const auto &KV : m_map) {
163     if (KV.first < all_files.size())
164       result[KV.second] = all_files[KV.first];
165   }
166   return FileSpecList(std::move(result));
167 }
168 
169 void SymbolFileBreakpad::Initialize() {
170   PluginManager::RegisterPlugin(GetPluginNameStatic(),
171                                 GetPluginDescriptionStatic(), CreateInstance,
172                                 DebuggerInitialize);
173 }
174 
175 void SymbolFileBreakpad::Terminate() {
176   PluginManager::UnregisterPlugin(CreateInstance);
177 }
178 
179 ConstString SymbolFileBreakpad::GetPluginNameStatic() {
180   static ConstString g_name("breakpad");
181   return g_name;
182 }
183 
184 uint32_t SymbolFileBreakpad::CalculateAbilities() {
185   if (!m_objfile_sp || !llvm::isa<ObjectFileBreakpad>(*m_objfile_sp))
186     return 0;
187 
188   return CompileUnits | Functions | LineTables;
189 }
190 
191 uint32_t SymbolFileBreakpad::CalculateNumCompileUnits() {
192   ParseCUData();
193   return m_cu_data->GetSize();
194 }
195 
196 CompUnitSP SymbolFileBreakpad::ParseCompileUnitAtIndex(uint32_t index) {
197   if (index >= m_cu_data->GetSize())
198     return nullptr;
199 
200   CompUnitData &data = m_cu_data->GetEntryRef(index).data;
201 
202   ParseFileRecords();
203 
204   FileSpec spec;
205 
206   // The FileSpec of the compile unit will be the file corresponding to the
207   // first LINE record.
208   LineIterator It(*m_objfile_sp, Record::Func, data.bookmark),
209       End(*m_objfile_sp);
210   assert(Record::classify(*It) == Record::Func);
211   ++It; // Skip FUNC record.
212   if (It != End) {
213     auto record = LineRecord::parse(*It);
214     if (record && record->FileNum < m_files->size())
215       spec = (*m_files)[record->FileNum];
216   }
217 
218   auto cu_sp = std::make_shared<CompileUnit>(m_objfile_sp->GetModule(),
219                                              /*user_data*/ nullptr, spec, index,
220                                              eLanguageTypeUnknown,
221                                              /*is_optimized*/ eLazyBoolNo);
222 
223   SetCompileUnitAtIndex(index, cu_sp);
224   return cu_sp;
225 }
226 
227 size_t SymbolFileBreakpad::ParseFunctions(CompileUnit &comp_unit) {
228   // TODO
229   return 0;
230 }
231 
232 bool SymbolFileBreakpad::ParseLineTable(CompileUnit &comp_unit) {
233   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
234   CompUnitData &data = m_cu_data->GetEntryRef(comp_unit.GetID()).data;
235 
236   if (!data.line_table_up)
237     ParseLineTableAndSupportFiles(comp_unit, data);
238 
239   comp_unit.SetLineTable(data.line_table_up.release());
240   return true;
241 }
242 
243 bool SymbolFileBreakpad::ParseSupportFiles(CompileUnit &comp_unit,
244                                            FileSpecList &support_files) {
245   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
246   CompUnitData &data = m_cu_data->GetEntryRef(comp_unit.GetID()).data;
247   if (!data.support_files)
248     ParseLineTableAndSupportFiles(comp_unit, data);
249 
250   support_files = std::move(*data.support_files);
251   return true;
252 }
253 
254 uint32_t
255 SymbolFileBreakpad::ResolveSymbolContext(const Address &so_addr,
256                                          SymbolContextItem resolve_scope,
257                                          SymbolContext &sc) {
258   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
259   if (!(resolve_scope & (eSymbolContextCompUnit | eSymbolContextLineEntry)))
260     return 0;
261 
262   ParseCUData();
263   uint32_t idx =
264       m_cu_data->FindEntryIndexThatContains(so_addr.GetFileAddress());
265   if (idx == UINT32_MAX)
266     return 0;
267 
268   sc.comp_unit = GetCompileUnitAtIndex(idx).get();
269   SymbolContextItem result = eSymbolContextCompUnit;
270   if (resolve_scope & eSymbolContextLineEntry) {
271     if (sc.comp_unit->GetLineTable()->FindLineEntryByAddress(so_addr,
272                                                              sc.line_entry)) {
273       result |= eSymbolContextLineEntry;
274     }
275   }
276 
277   return result;
278 }
279 
280 uint32_t SymbolFileBreakpad::ResolveSymbolContext(
281     const FileSpec &file_spec, uint32_t line, bool check_inlines,
282     lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
283   std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
284   if (!(resolve_scope & eSymbolContextCompUnit))
285     return 0;
286 
287   uint32_t old_size = sc_list.GetSize();
288   for (size_t i = 0, size = GetNumCompileUnits(); i < size; ++i) {
289     CompileUnit &cu = *GetCompileUnitAtIndex(i);
290     cu.ResolveSymbolContext(file_spec, line, check_inlines,
291                             /*exact*/ false, resolve_scope, sc_list);
292   }
293   return sc_list.GetSize() - old_size;
294 }
295 
296 void SymbolFileBreakpad::FindFunctions(
297     ConstString name, const CompilerDeclContext &parent_decl_ctx,
298     FunctionNameType name_type_mask, bool include_inlines,
299     SymbolContextList &sc_list) {
300   // TODO
301 }
302 
303 void SymbolFileBreakpad::FindFunctions(const RegularExpression &regex,
304                                        bool include_inlines,
305                                        SymbolContextList &sc_list) {
306   // TODO
307 }
308 
309 void SymbolFileBreakpad::FindTypes(
310     ConstString name, const CompilerDeclContext &parent_decl_ctx,
311     uint32_t max_matches, llvm::DenseSet<SymbolFile *> &searched_symbol_files,
312     TypeMap &types) {}
313 
314 void SymbolFileBreakpad::FindTypes(
315     llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
316     llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {}
317 
318 void SymbolFileBreakpad::AddSymbols(Symtab &symtab) {
319   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
320   Module &module = *m_objfile_sp->GetModule();
321   addr_t base = GetBaseFileAddress();
322   if (base == LLDB_INVALID_ADDRESS) {
323     LLDB_LOG(log, "Unable to fetch the base address of object file. Skipping "
324                   "symtab population.");
325     return;
326   }
327 
328   const SectionList &list = *module.GetSectionList();
329   llvm::DenseMap<addr_t, Symbol> symbols;
330   auto add_symbol = [&](addr_t address, llvm::Optional<addr_t> size,
331                         llvm::StringRef name) {
332     address += base;
333     SectionSP section_sp = list.FindSectionContainingFileAddress(address);
334     if (!section_sp) {
335       LLDB_LOG(log,
336                "Ignoring symbol {0}, whose address ({1}) is outside of the "
337                "object file. Mismatched symbol file?",
338                name, address);
339       return;
340     }
341     symbols.try_emplace(
342         address, /*symID*/ 0, Mangled(name), eSymbolTypeCode,
343         /*is_global*/ true, /*is_debug*/ false,
344         /*is_trampoline*/ false, /*is_artificial*/ false,
345         AddressRange(section_sp, address - section_sp->GetFileAddress(),
346                      size.getValueOr(0)),
347         size.hasValue(), /*contains_linker_annotations*/ false, /*flags*/ 0);
348   };
349 
350   for (llvm::StringRef line : lines(Record::Func)) {
351     if (auto record = FuncRecord::parse(line))
352       add_symbol(record->Address, record->Size, record->Name);
353   }
354 
355   for (llvm::StringRef line : lines(Record::Public)) {
356     if (auto record = PublicRecord::parse(line))
357       add_symbol(record->Address, llvm::None, record->Name);
358     else
359       LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", line);
360   }
361 
362   for (auto &KV : symbols)
363     symtab.AddSymbol(std::move(KV.second));
364   symtab.CalculateSymbolSizes();
365 }
366 
367 llvm::Expected<lldb::addr_t>
368 SymbolFileBreakpad::GetParameterStackSize(Symbol &symbol) {
369   ParseUnwindData();
370   if (auto *entry = m_unwind_data->win.FindEntryThatContains(
371           symbol.GetAddress().GetFileAddress())) {
372     auto record = StackWinRecord::parse(
373         *LineIterator(*m_objfile_sp, Record::StackWin, entry->data));
374     assert(record.hasValue());
375     return record->ParameterSize;
376   }
377   return llvm::createStringError(llvm::inconvertibleErrorCode(),
378                                  "Parameter size unknown.");
379 }
380 
381 static llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
382 GetRule(llvm::StringRef &unwind_rules) {
383   // Unwind rules are of the form
384   //   register1: expression1 register2: expression2 ...
385   // We assume none of the tokens in expression<n> end with a colon.
386 
387   llvm::StringRef lhs, rest;
388   std::tie(lhs, rest) = getToken(unwind_rules);
389   if (!lhs.consume_back(":"))
390     return llvm::None;
391 
392   // Seek forward to the next register: expression pair
393   llvm::StringRef::size_type pos = rest.find(": ");
394   if (pos == llvm::StringRef::npos) {
395     // No pair found, this means the rest of the string is a single expression.
396     unwind_rules = llvm::StringRef();
397     return std::make_pair(lhs, rest);
398   }
399 
400   // Go back one token to find the end of the current rule.
401   pos = rest.rfind(' ', pos);
402   if (pos == llvm::StringRef::npos)
403     return llvm::None;
404 
405   llvm::StringRef rhs = rest.take_front(pos);
406   unwind_rules = rest.drop_front(pos);
407   return std::make_pair(lhs, rhs);
408 }
409 
410 static const RegisterInfo *
411 ResolveRegister(const llvm::Triple &triple,
412                 const SymbolFile::RegisterInfoResolver &resolver,
413                 llvm::StringRef name) {
414   if (triple.isX86() || triple.isMIPS()) {
415     // X86 and MIPS registers have '$' in front of their register names. Arm and
416     // AArch64 don't.
417     if (!name.consume_front("$"))
418       return nullptr;
419   }
420   return resolver.ResolveName(name);
421 }
422 
423 static const RegisterInfo *
424 ResolveRegisterOrRA(const llvm::Triple &triple,
425                     const SymbolFile::RegisterInfoResolver &resolver,
426                     llvm::StringRef name) {
427   if (name == ".ra")
428     return resolver.ResolveNumber(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
429   return ResolveRegister(triple, resolver, name);
430 }
431 
432 llvm::ArrayRef<uint8_t> SymbolFileBreakpad::SaveAsDWARF(postfix::Node &node) {
433   ArchSpec arch = m_objfile_sp->GetArchitecture();
434   StreamString dwarf(Stream::eBinary, arch.GetAddressByteSize(),
435                      arch.GetByteOrder());
436   ToDWARF(node, dwarf);
437   uint8_t *saved = m_allocator.Allocate<uint8_t>(dwarf.GetSize());
438   std::memcpy(saved, dwarf.GetData(), dwarf.GetSize());
439   return {saved, dwarf.GetSize()};
440 }
441 
442 bool SymbolFileBreakpad::ParseCFIUnwindRow(llvm::StringRef unwind_rules,
443                                         const RegisterInfoResolver &resolver,
444                                         UnwindPlan::Row &row) {
445   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
446 
447   llvm::BumpPtrAllocator node_alloc;
448   llvm::Triple triple = m_objfile_sp->GetArchitecture().GetTriple();
449   while (auto rule = GetRule(unwind_rules)) {
450     node_alloc.Reset();
451     llvm::StringRef lhs = rule->first;
452     postfix::Node *rhs = postfix::ParseOneExpression(rule->second, node_alloc);
453     if (!rhs) {
454       LLDB_LOG(log, "Could not parse `{0}` as unwind rhs.", rule->second);
455       return false;
456     }
457 
458     bool success = postfix::ResolveSymbols(
459         rhs, [&](postfix::SymbolNode &symbol) -> postfix::Node * {
460           llvm::StringRef name = symbol.GetName();
461           if (name == ".cfa" && lhs != ".cfa")
462             return postfix::MakeNode<postfix::InitialValueNode>(node_alloc);
463 
464           if (const RegisterInfo *info =
465                   ResolveRegister(triple, resolver, name)) {
466             return postfix::MakeNode<postfix::RegisterNode>(
467                 node_alloc, info->kinds[eRegisterKindLLDB]);
468           }
469           return nullptr;
470         });
471 
472     if (!success) {
473       LLDB_LOG(log, "Resolving symbols in `{0}` failed.", rule->second);
474       return false;
475     }
476 
477     llvm::ArrayRef<uint8_t> saved = SaveAsDWARF(*rhs);
478     if (lhs == ".cfa") {
479       row.GetCFAValue().SetIsDWARFExpression(saved.data(), saved.size());
480     } else if (const RegisterInfo *info =
481                    ResolveRegisterOrRA(triple, resolver, lhs)) {
482       UnwindPlan::Row::RegisterLocation loc;
483       loc.SetIsDWARFExpression(saved.data(), saved.size());
484       row.SetRegisterInfo(info->kinds[eRegisterKindLLDB], loc);
485     } else
486       LLDB_LOG(log, "Invalid register `{0}` in unwind rule.", lhs);
487   }
488   if (unwind_rules.empty())
489     return true;
490 
491   LLDB_LOG(log, "Could not parse `{0}` as an unwind rule.", unwind_rules);
492   return false;
493 }
494 
495 UnwindPlanSP
496 SymbolFileBreakpad::GetUnwindPlan(const Address &address,
497                                   const RegisterInfoResolver &resolver) {
498   ParseUnwindData();
499   if (auto *entry =
500           m_unwind_data->cfi.FindEntryThatContains(address.GetFileAddress()))
501     return ParseCFIUnwindPlan(entry->data, resolver);
502   if (auto *entry =
503           m_unwind_data->win.FindEntryThatContains(address.GetFileAddress()))
504     return ParseWinUnwindPlan(entry->data, resolver);
505   return nullptr;
506 }
507 
508 UnwindPlanSP
509 SymbolFileBreakpad::ParseCFIUnwindPlan(const Bookmark &bookmark,
510                                        const RegisterInfoResolver &resolver) {
511   addr_t base = GetBaseFileAddress();
512   if (base == LLDB_INVALID_ADDRESS)
513     return nullptr;
514 
515   LineIterator It(*m_objfile_sp, Record::StackCFI, bookmark),
516       End(*m_objfile_sp);
517   llvm::Optional<StackCFIRecord> init_record = StackCFIRecord::parse(*It);
518   assert(init_record.hasValue() && init_record->Size.hasValue() &&
519          "Record already parsed successfully in ParseUnwindData!");
520 
521   auto plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindLLDB);
522   plan_sp->SetSourceName("breakpad STACK CFI");
523   plan_sp->SetUnwindPlanValidAtAllInstructions(eLazyBoolNo);
524   plan_sp->SetUnwindPlanForSignalTrap(eLazyBoolNo);
525   plan_sp->SetSourcedFromCompiler(eLazyBoolYes);
526   plan_sp->SetPlanValidAddressRange(
527       AddressRange(base + init_record->Address, *init_record->Size,
528                    m_objfile_sp->GetModule()->GetSectionList()));
529 
530   auto row_sp = std::make_shared<UnwindPlan::Row>();
531   row_sp->SetOffset(0);
532   if (!ParseCFIUnwindRow(init_record->UnwindRules, resolver, *row_sp))
533     return nullptr;
534   plan_sp->AppendRow(row_sp);
535   for (++It; It != End; ++It) {
536     llvm::Optional<StackCFIRecord> record = StackCFIRecord::parse(*It);
537     if (!record.hasValue())
538       return nullptr;
539     if (record->Size.hasValue())
540       break;
541 
542     row_sp = std::make_shared<UnwindPlan::Row>(*row_sp);
543     row_sp->SetOffset(record->Address - init_record->Address);
544     if (!ParseCFIUnwindRow(record->UnwindRules, resolver, *row_sp))
545       return nullptr;
546     plan_sp->AppendRow(row_sp);
547   }
548   return plan_sp;
549 }
550 
551 UnwindPlanSP
552 SymbolFileBreakpad::ParseWinUnwindPlan(const Bookmark &bookmark,
553                                        const RegisterInfoResolver &resolver) {
554   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
555   addr_t base = GetBaseFileAddress();
556   if (base == LLDB_INVALID_ADDRESS)
557     return nullptr;
558 
559   LineIterator It(*m_objfile_sp, Record::StackWin, bookmark);
560   llvm::Optional<StackWinRecord> record = StackWinRecord::parse(*It);
561   assert(record.hasValue() &&
562          "Record already parsed successfully in ParseUnwindData!");
563 
564   auto plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindLLDB);
565   plan_sp->SetSourceName("breakpad STACK WIN");
566   plan_sp->SetUnwindPlanValidAtAllInstructions(eLazyBoolNo);
567   plan_sp->SetUnwindPlanForSignalTrap(eLazyBoolNo);
568   plan_sp->SetSourcedFromCompiler(eLazyBoolYes);
569   plan_sp->SetPlanValidAddressRange(
570       AddressRange(base + record->RVA, record->CodeSize,
571                    m_objfile_sp->GetModule()->GetSectionList()));
572 
573   auto row_sp = std::make_shared<UnwindPlan::Row>();
574   row_sp->SetOffset(0);
575 
576   llvm::BumpPtrAllocator node_alloc;
577   std::vector<std::pair<llvm::StringRef, postfix::Node *>> program =
578       postfix::ParseFPOProgram(record->ProgramString, node_alloc);
579 
580   if (program.empty()) {
581     LLDB_LOG(log, "Invalid unwind rule: {0}.", record->ProgramString);
582     return nullptr;
583   }
584   auto it = program.begin();
585   llvm::Triple triple = m_objfile_sp->GetArchitecture().GetTriple();
586   const auto &symbol_resolver =
587       [&](postfix::SymbolNode &symbol) -> postfix::Node * {
588     llvm::StringRef name = symbol.GetName();
589     for (const auto &rule : llvm::make_range(program.begin(), it)) {
590       if (rule.first == name)
591         return rule.second;
592     }
593     if (const RegisterInfo *info = ResolveRegister(triple, resolver, name))
594       return postfix::MakeNode<postfix::RegisterNode>(
595           node_alloc, info->kinds[eRegisterKindLLDB]);
596     return nullptr;
597   };
598 
599   // We assume the first value will be the CFA. It is usually called T0, but
600   // clang will use T1, if it needs to realign the stack.
601   auto *symbol = llvm::dyn_cast<postfix::SymbolNode>(it->second);
602   if (symbol && symbol->GetName() == ".raSearch") {
603     row_sp->GetCFAValue().SetRaSearch(record->LocalSize +
604                                       record->SavedRegisterSize);
605   } else {
606     if (!postfix::ResolveSymbols(it->second, symbol_resolver)) {
607       LLDB_LOG(log, "Resolving symbols in `{0}` failed.",
608                record->ProgramString);
609       return nullptr;
610     }
611     llvm::ArrayRef<uint8_t> saved  = SaveAsDWARF(*it->second);
612     row_sp->GetCFAValue().SetIsDWARFExpression(saved.data(), saved.size());
613   }
614 
615   // Replace the node value with InitialValueNode, so that subsequent
616   // expressions refer to the CFA value instead of recomputing the whole
617   // expression.
618   it->second = postfix::MakeNode<postfix::InitialValueNode>(node_alloc);
619 
620 
621   // Now process the rest of the assignments.
622   for (++it; it != program.end(); ++it) {
623     const RegisterInfo *info = ResolveRegister(triple, resolver, it->first);
624     // It is not an error if the resolution fails because the program may
625     // contain temporary variables.
626     if (!info)
627       continue;
628     if (!postfix::ResolveSymbols(it->second, symbol_resolver)) {
629       LLDB_LOG(log, "Resolving symbols in `{0}` failed.",
630                record->ProgramString);
631       return nullptr;
632     }
633 
634     llvm::ArrayRef<uint8_t> saved = SaveAsDWARF(*it->second);
635     UnwindPlan::Row::RegisterLocation loc;
636     loc.SetIsDWARFExpression(saved.data(), saved.size());
637     row_sp->SetRegisterInfo(info->kinds[eRegisterKindLLDB], loc);
638   }
639 
640   plan_sp->AppendRow(row_sp);
641   return plan_sp;
642 }
643 
644 addr_t SymbolFileBreakpad::GetBaseFileAddress() {
645   return m_objfile_sp->GetModule()
646       ->GetObjectFile()
647       ->GetBaseAddress()
648       .GetFileAddress();
649 }
650 
651 // Parse out all the FILE records from the breakpad file. These will be needed
652 // when constructing the support file lists for individual compile units.
653 void SymbolFileBreakpad::ParseFileRecords() {
654   if (m_files)
655     return;
656   m_files.emplace();
657 
658   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
659   for (llvm::StringRef line : lines(Record::File)) {
660     auto record = FileRecord::parse(line);
661     if (!record) {
662       LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", line);
663       continue;
664     }
665 
666     if (record->Number >= m_files->size())
667       m_files->resize(record->Number + 1);
668     FileSpec::Style style = FileSpec::GuessPathStyle(record->Name)
669                                 .getValueOr(FileSpec::Style::native);
670     (*m_files)[record->Number] = FileSpec(record->Name, style);
671   }
672 }
673 
674 void SymbolFileBreakpad::ParseCUData() {
675   if (m_cu_data)
676     return;
677 
678   m_cu_data.emplace();
679   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
680   addr_t base = GetBaseFileAddress();
681   if (base == LLDB_INVALID_ADDRESS) {
682     LLDB_LOG(log, "SymbolFile parsing failed: Unable to fetch the base address "
683                   "of object file.");
684   }
685 
686   // We shall create one compile unit for each FUNC record. So, count the number
687   // of FUNC records, and store them in m_cu_data, together with their ranges.
688   for (LineIterator It(*m_objfile_sp, Record::Func), End(*m_objfile_sp);
689        It != End; ++It) {
690     if (auto record = FuncRecord::parse(*It)) {
691       m_cu_data->Append(CompUnitMap::Entry(base + record->Address, record->Size,
692                                            CompUnitData(It.GetBookmark())));
693     } else
694       LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", *It);
695   }
696   m_cu_data->Sort();
697 }
698 
699 // Construct the list of support files and line table entries for the given
700 // compile unit.
701 void SymbolFileBreakpad::ParseLineTableAndSupportFiles(CompileUnit &cu,
702                                                        CompUnitData &data) {
703   addr_t base = GetBaseFileAddress();
704   assert(base != LLDB_INVALID_ADDRESS &&
705          "How did we create compile units without a base address?");
706 
707   SupportFileMap map;
708   std::vector<std::unique_ptr<LineSequence>> sequences;
709   std::unique_ptr<LineSequence> line_seq_up =
710       LineTable::CreateLineSequenceContainer();
711   llvm::Optional<addr_t> next_addr;
712   auto finish_sequence = [&]() {
713     LineTable::AppendLineEntryToSequence(
714         line_seq_up.get(), *next_addr, /*line*/ 0, /*column*/ 0,
715         /*file_idx*/ 0, /*is_start_of_statement*/ false,
716         /*is_start_of_basic_block*/ false, /*is_prologue_end*/ false,
717         /*is_epilogue_begin*/ false, /*is_terminal_entry*/ true);
718     sequences.push_back(std::move(line_seq_up));
719     line_seq_up = LineTable::CreateLineSequenceContainer();
720   };
721 
722   LineIterator It(*m_objfile_sp, Record::Func, data.bookmark),
723       End(*m_objfile_sp);
724   assert(Record::classify(*It) == Record::Func);
725   for (++It; It != End; ++It) {
726     auto record = LineRecord::parse(*It);
727     if (!record)
728       break;
729 
730     record->Address += base;
731 
732     if (next_addr && *next_addr != record->Address) {
733       // Discontiguous entries. Finish off the previous sequence and reset.
734       finish_sequence();
735     }
736     LineTable::AppendLineEntryToSequence(
737         line_seq_up.get(), record->Address, record->LineNum, /*column*/ 0,
738         map[record->FileNum], /*is_start_of_statement*/ true,
739         /*is_start_of_basic_block*/ false, /*is_prologue_end*/ false,
740         /*is_epilogue_begin*/ false, /*is_terminal_entry*/ false);
741     next_addr = record->Address + record->Size;
742   }
743   if (next_addr)
744     finish_sequence();
745   data.line_table_up = std::make_unique<LineTable>(&cu, std::move(sequences));
746   data.support_files = map.translate(cu.GetPrimaryFile(), *m_files);
747 }
748 
749 void SymbolFileBreakpad::ParseUnwindData() {
750   if (m_unwind_data)
751     return;
752   m_unwind_data.emplace();
753 
754   Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS);
755   addr_t base = GetBaseFileAddress();
756   if (base == LLDB_INVALID_ADDRESS) {
757     LLDB_LOG(log, "SymbolFile parsing failed: Unable to fetch the base address "
758                   "of object file.");
759   }
760 
761   for (LineIterator It(*m_objfile_sp, Record::StackCFI), End(*m_objfile_sp);
762        It != End; ++It) {
763     if (auto record = StackCFIRecord::parse(*It)) {
764       if (record->Size)
765         m_unwind_data->cfi.Append(UnwindMap::Entry(
766             base + record->Address, *record->Size, It.GetBookmark()));
767     } else
768       LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", *It);
769   }
770   m_unwind_data->cfi.Sort();
771 
772   for (LineIterator It(*m_objfile_sp, Record::StackWin), End(*m_objfile_sp);
773        It != End; ++It) {
774     if (auto record = StackWinRecord::parse(*It)) {
775       m_unwind_data->win.Append(UnwindMap::Entry(
776           base + record->RVA, record->CodeSize, It.GetBookmark()));
777     } else
778       LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", *It);
779   }
780   m_unwind_data->win.Sort();
781 }
782