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