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