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