LLDB mainline
SymbolFileBreakpad.cpp
Go to the documentation of this file.
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
12#include "lldb/Core/Module.h"
14#include "lldb/Core/Section.h"
19#include "lldb/Symbol/TypeMap.h"
21#include "lldb/Utility/Log.h"
23#include "llvm/ADT/StringExtras.h"
24#include <optional>
25
26using namespace lldb;
27using namespace lldb_private;
28using namespace lldb_private::breakpad;
29
31
33
35public:
36 // begin iterator for sections of given 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);
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 {
66 }
67
70 }
71
72private:
76 llvm::StringRef m_section_text;
79
80 void FindNextLine() {
82 if (m_next_line != llvm::StringRef::npos) {
84 if (m_next_line >= m_section_text.size())
85 m_next_line = llvm::StringRef::npos;
86 }
87 }
88};
89
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 =
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
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
132llvm::iterator_range<SymbolFileBreakpad::LineIterator>
134 return llvm::make_range(LineIterator(*m_objfile_sp, section_type),
136}
137
138namespace {
139// A helper class for constructing the list of support files for a given compile
140// unit.
141class SupportFileMap {
142public:
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
154private:
155 llvm::DenseMap<size_t, size_t> m_map;
156};
157} // namespace
158
159FileSpecList 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
175}
176
179}
180
182 if (!m_objfile_sp || !llvm::isa<ObjectFileBreakpad>(*m_objfile_sp))
183 return 0;
184
186}
187
189 ParseCUData();
190 return m_cu_data->GetSize();
191}
192
194 if (index >= m_cu_data->GetSize())
195 return nullptr;
196
197 CompUnitData &data = m_cu_data->GetEntryRef(index).data;
198
200
201 FileSpec spec;
202
203 // The FileSpec of the compile unit will be the file corresponding to the
204 // first LINE record.
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>(
220 m_objfile_sp->GetModule(),
221 /*user_data*/ nullptr, std::make_shared<SupportFile>(spec), index,
223 /*is_optimized*/ eLazyBoolNo);
224
225 SetCompileUnitAtIndex(index, cu_sp);
226 return cu_sp;
227}
228
230 user_id_t id = comp_unit.GetID();
231 if (FunctionSP func_sp = comp_unit.FindFunctionByUID(id))
232 return func_sp;
233
235 FunctionSP func_sp;
236 addr_t base = GetBaseFileAddress();
237 if (base == LLDB_INVALID_ADDRESS) {
238 LLDB_LOG(log, "Unable to fetch the base address of object file. Skipping "
239 "symtab population.");
240 return func_sp;
241 }
242
243 const SectionList *list = comp_unit.GetModule()->GetSectionList();
244 CompUnitData &data = m_cu_data->GetEntryRef(id).data;
246 assert(Record::classify(*It) == Record::Func);
247
248 if (auto record = FuncRecord::parse(*It)) {
249 Mangled func_name;
250 func_name.SetValue(ConstString(record->Name));
251 addr_t address = record->Address + base;
252 SectionSP section_sp = list->FindSectionContainingFileAddress(address);
253 if (section_sp) {
254 AddressRange func_range(
255 section_sp, address - section_sp->GetFileAddress(), record->Size);
256 // Use the CU's id because every CU has only one function inside.
257 func_sp = std::make_shared<Function>(&comp_unit, id, 0, func_name,
258 nullptr, func_range);
259 comp_unit.AddFunction(func_sp);
260 }
261 }
262 return func_sp;
263}
264
266 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
267 return GetOrCreateFunction(comp_unit) ? 1 : 0;
268}
269
271 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
272 CompUnitData &data = m_cu_data->GetEntryRef(comp_unit.GetID()).data;
273
274 if (!data.line_table_up)
275 ParseLineTableAndSupportFiles(comp_unit, data);
276
277 comp_unit.SetLineTable(data.line_table_up.release());
278 return true;
279}
280
282 SupportFileList &support_files) {
283 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
284 CompUnitData &data = m_cu_data->GetEntryRef(comp_unit.GetID()).data;
285 if (!data.support_files)
286 ParseLineTableAndSupportFiles(comp_unit, data);
287
288 for (auto &fs : *data.support_files)
289 support_files.Append(fs);
290 return true;
291}
292
294 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
295 CompileUnit *comp_unit = func.GetCompileUnit();
296 lldbassert(comp_unit);
298 // A vector of current each level's parent block. For example, when parsing
299 // "INLINE 0 ...", the current level is 0 and its parent block is the
300 // function block at index 0.
301 std::vector<Block *> blocks;
302 Block &block = func.GetBlock(false);
304 blocks.push_back(&block);
305
306 size_t blocks_added = 0;
307 addr_t func_base = func.GetAddressRange().GetBaseAddress().GetOffset();
308 CompUnitData &data = m_cu_data->GetEntryRef(comp_unit->GetID()).data;
310 End(*m_objfile_sp);
311 ++It; // Skip the FUNC record.
312 size_t last_added_nest_level = 0;
313 while (It != End && Record::classify(*It) == Record::Inline) {
314 if (auto record = InlineRecord::parse(*It)) {
315 if (record->InlineNestLevel == 0 ||
316 record->InlineNestLevel <= last_added_nest_level + 1) {
317 last_added_nest_level = record->InlineNestLevel;
318 BlockSP block_sp = std::make_shared<Block>(It.GetBookmark().offset);
319 FileSpec callsite_file;
320 if (record->CallSiteFileNum < m_files->size())
321 callsite_file = (*m_files)[record->CallSiteFileNum];
322 llvm::StringRef name;
323 if (record->OriginNum < m_inline_origins->size())
324 name = (*m_inline_origins)[record->OriginNum];
325
326 Declaration callsite(callsite_file, record->CallSiteLineNum);
327 block_sp->SetInlinedFunctionInfo(name.str().c_str(),
328 /*mangled=*/nullptr,
329 /*decl_ptr=*/nullptr, &callsite);
330 for (const auto &range : record->Ranges) {
331 block_sp->AddRange(
332 Block::Range(range.first - func_base, range.second));
333 }
334 block_sp->FinalizeRanges();
335
336 blocks[record->InlineNestLevel]->AddChild(block_sp);
337 if (record->InlineNestLevel + 1 >= blocks.size()) {
338 blocks.resize(blocks.size() + 1);
339 }
340 blocks[record->InlineNestLevel + 1] = block_sp.get();
341 ++blocks_added;
342 }
343 }
344 ++It;
345 }
346 return blocks_added;
347}
348
351 return;
352 m_inline_origins.emplace();
353
355 for (llvm::StringRef line : lines(Record::InlineOrigin)) {
356 auto record = InlineOriginRecord::parse(line);
357 if (!record) {
358 LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", line);
359 continue;
360 }
361
362 if (record->Number >= m_inline_origins->size())
363 m_inline_origins->resize(record->Number + 1);
364 (*m_inline_origins)[record->Number] = record->Name;
365 }
366}
367
368uint32_t
370 SymbolContextItem resolve_scope,
371 SymbolContext &sc) {
372 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
373 if (!(resolve_scope & (eSymbolContextCompUnit | eSymbolContextLineEntry |
374 eSymbolContextFunction | eSymbolContextBlock)))
375 return 0;
376
377 ParseCUData();
378 uint32_t idx =
379 m_cu_data->FindEntryIndexThatContains(so_addr.GetFileAddress());
380 if (idx == UINT32_MAX)
381 return 0;
382
383 sc.comp_unit = GetCompileUnitAtIndex(idx).get();
384 SymbolContextItem result = eSymbolContextCompUnit;
385 if (resolve_scope & eSymbolContextLineEntry) {
387 sc.line_entry)) {
388 result |= eSymbolContextLineEntry;
389 }
390 }
391
392 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) {
394 if (func_sp) {
395 sc.function = func_sp.get();
396 result |= eSymbolContextFunction;
397 if (resolve_scope & eSymbolContextBlock) {
398 Block &block = func_sp->GetBlock(true);
400 so_addr.GetFileAddress() -
402 if (sc.block)
403 result |= eSymbolContextBlock;
404 }
405 }
406 }
407
408 return result;
409}
410
412 const SourceLocationSpec &src_location_spec,
413 lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
414 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
415 if (!(resolve_scope & eSymbolContextCompUnit))
416 return 0;
417
418 uint32_t old_size = sc_list.GetSize();
419 for (size_t i = 0, size = GetNumCompileUnits(); i < size; ++i) {
421 cu.ResolveSymbolContext(src_location_spec, resolve_scope, sc_list);
422 }
423 return sc_list.GetSize() - old_size;
424}
425
427 const Module::LookupInfo &lookup_info,
428 const CompilerDeclContext &parent_decl_ctx, bool include_inlines,
429 SymbolContextList &sc_list) {
430 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
431 // TODO: Implement this with supported FunctionNameType.
432
433 ConstString name = lookup_info.GetLookupName();
434 for (uint32_t i = 0; i < GetNumCompileUnits(); ++i) {
436 FunctionSP func_sp = GetOrCreateFunction(*cu_sp);
437 if (func_sp && name == func_sp->GetNameNoArguments()) {
438 SymbolContext sc;
439 sc.comp_unit = cu_sp.get();
440 sc.function = func_sp.get();
441 sc.module_sp = func_sp->CalculateSymbolContextModule();
442 sc_list.Append(sc);
443 }
444 }
445}
446
448 bool include_inlines,
449 SymbolContextList &sc_list) {
450 // TODO
451}
452
455 Module &module = *m_objfile_sp->GetModule();
456 addr_t base = GetBaseFileAddress();
457 if (base == LLDB_INVALID_ADDRESS) {
458 LLDB_LOG(log, "Unable to fetch the base address of object file. Skipping "
459 "symtab population.");
460 return;
461 }
462
463 const SectionList &list = *module.GetSectionList();
464 llvm::DenseSet<addr_t> found_symbol_addresses;
465 std::vector<Symbol> symbols;
466 auto add_symbol = [&](addr_t address, std::optional<addr_t> size,
467 llvm::StringRef name) {
468 address += base;
469 SectionSP section_sp = list.FindSectionContainingFileAddress(address);
470 if (!section_sp) {
471 LLDB_LOG(log,
472 "Ignoring symbol {0}, whose address ({1}) is outside of the "
473 "object file. Mismatched symbol file?",
474 name, address);
475 return;
476 }
477 // Keep track of what addresses were already added so far and only add
478 // the symbol with the first address.
479 if (!found_symbol_addresses.insert(address).second)
480 return;
481 symbols.emplace_back(
482 /*symID*/ 0, Mangled(name), eSymbolTypeCode,
483 /*is_global*/ true, /*is_debug*/ false,
484 /*is_trampoline*/ false, /*is_artificial*/ false,
485 AddressRange(section_sp, address - section_sp->GetFileAddress(),
486 size.value_or(0)),
487 size.has_value(), /*contains_linker_annotations*/ false, /*flags*/ 0);
488 };
489
490 for (llvm::StringRef line : lines(Record::Public)) {
491 if (auto record = PublicRecord::parse(line))
492 add_symbol(record->Address, std::nullopt, record->Name);
493 else
494 LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", line);
495 }
496
497 for (Symbol &symbol : symbols)
498 symtab.AddSymbol(std::move(symbol));
499 symtab.Finalize();
500}
501
502llvm::Expected<lldb::addr_t>
505 if (auto *entry = m_unwind_data->win.FindEntryThatContains(
506 symbol.GetAddress().GetFileAddress())) {
507 auto record = StackWinRecord::parse(
509 assert(record);
510 return record->ParameterSize;
511 }
512 return llvm::createStringError(llvm::inconvertibleErrorCode(),
513 "Parameter size unknown.");
514}
515
516static std::optional<std::pair<llvm::StringRef, llvm::StringRef>>
517GetRule(llvm::StringRef &unwind_rules) {
518 // Unwind rules are of the form
519 // register1: expression1 register2: expression2 ...
520 // We assume none of the tokens in expression<n> end with a colon.
521
522 llvm::StringRef lhs, rest;
523 std::tie(lhs, rest) = getToken(unwind_rules);
524 if (!lhs.consume_back(":"))
525 return std::nullopt;
526
527 // Seek forward to the next register: expression pair
528 llvm::StringRef::size_type pos = rest.find(": ");
529 if (pos == llvm::StringRef::npos) {
530 // No pair found, this means the rest of the string is a single expression.
531 unwind_rules = llvm::StringRef();
532 return std::make_pair(lhs, rest);
533 }
534
535 // Go back one token to find the end of the current rule.
536 pos = rest.rfind(' ', pos);
537 if (pos == llvm::StringRef::npos)
538 return std::nullopt;
539
540 llvm::StringRef rhs = rest.take_front(pos);
541 unwind_rules = rest.drop_front(pos);
542 return std::make_pair(lhs, rhs);
543}
544
545static const RegisterInfo *
546ResolveRegister(const llvm::Triple &triple,
547 const SymbolFile::RegisterInfoResolver &resolver,
548 llvm::StringRef name) {
549 if (triple.isX86() || triple.isMIPS()) {
550 // X86 and MIPS registers have '$' in front of their register names. Arm and
551 // AArch64 don't.
552 if (!name.consume_front("$"))
553 return nullptr;
554 }
555 return resolver.ResolveName(name);
556}
557
558static const RegisterInfo *
559ResolveRegisterOrRA(const llvm::Triple &triple,
560 const SymbolFile::RegisterInfoResolver &resolver,
561 llvm::StringRef name) {
562 if (name == ".ra")
564 return ResolveRegister(triple, resolver, name);
565}
566
567llvm::ArrayRef<uint8_t> SymbolFileBreakpad::SaveAsDWARF(postfix::Node &node) {
568 ArchSpec arch = m_objfile_sp->GetArchitecture();
570 arch.GetByteOrder());
571 ToDWARF(node, dwarf);
572 uint8_t *saved = m_allocator.Allocate<uint8_t>(dwarf.GetSize());
573 std::memcpy(saved, dwarf.GetData(), dwarf.GetSize());
574 return {saved, dwarf.GetSize()};
575}
576
577bool SymbolFileBreakpad::ParseCFIUnwindRow(llvm::StringRef unwind_rules,
578 const RegisterInfoResolver &resolver,
579 UnwindPlan::Row &row) {
581
582 llvm::BumpPtrAllocator node_alloc;
583 llvm::Triple triple = m_objfile_sp->GetArchitecture().GetTriple();
584 while (auto rule = GetRule(unwind_rules)) {
585 node_alloc.Reset();
586 llvm::StringRef lhs = rule->first;
587 postfix::Node *rhs = postfix::ParseOneExpression(rule->second, node_alloc);
588 if (!rhs) {
589 LLDB_LOG(log, "Could not parse `{0}` as unwind rhs.", rule->second);
590 return false;
591 }
592
593 bool success = postfix::ResolveSymbols(
594 rhs, [&](postfix::SymbolNode &symbol) -> postfix::Node * {
595 llvm::StringRef name = symbol.GetName();
596 if (name == ".cfa" && lhs != ".cfa")
597 return postfix::MakeNode<postfix::InitialValueNode>(node_alloc);
598
599 if (const RegisterInfo *info =
600 ResolveRegister(triple, resolver, name)) {
601 return postfix::MakeNode<postfix::RegisterNode>(
602 node_alloc, info->kinds[eRegisterKindLLDB]);
603 }
604 return nullptr;
605 });
606
607 if (!success) {
608 LLDB_LOG(log, "Resolving symbols in `{0}` failed.", rule->second);
609 return false;
610 }
611
612 llvm::ArrayRef<uint8_t> saved = SaveAsDWARF(*rhs);
613 if (lhs == ".cfa") {
614 row.GetCFAValue().SetIsDWARFExpression(saved.data(), saved.size());
615 } else if (const RegisterInfo *info =
616 ResolveRegisterOrRA(triple, resolver, lhs)) {
618 loc.SetIsDWARFExpression(saved.data(), saved.size());
619 row.SetRegisterInfo(info->kinds[eRegisterKindLLDB], loc);
620 } else
621 LLDB_LOG(log, "Invalid register `{0}` in unwind rule.", lhs);
622 }
623 if (unwind_rules.empty())
624 return true;
625
626 LLDB_LOG(log, "Could not parse `{0}` as an unwind rule.", unwind_rules);
627 return false;
628}
629
632 const RegisterInfoResolver &resolver) {
634 if (auto *entry =
635 m_unwind_data->cfi.FindEntryThatContains(address.GetFileAddress()))
636 return ParseCFIUnwindPlan(entry->data, resolver);
637 if (auto *entry =
638 m_unwind_data->win.FindEntryThatContains(address.GetFileAddress()))
639 return ParseWinUnwindPlan(entry->data, resolver);
640 return nullptr;
641}
642
645 const RegisterInfoResolver &resolver) {
646 addr_t base = GetBaseFileAddress();
647 if (base == LLDB_INVALID_ADDRESS)
648 return nullptr;
649
651 End(*m_objfile_sp);
652 std::optional<StackCFIRecord> init_record = StackCFIRecord::parse(*It);
653 assert(init_record && init_record->Size &&
654 "Record already parsed successfully in ParseUnwindData!");
655
656 auto plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindLLDB);
657 plan_sp->SetSourceName("breakpad STACK CFI");
658 plan_sp->SetUnwindPlanValidAtAllInstructions(eLazyBoolNo);
659 plan_sp->SetUnwindPlanForSignalTrap(eLazyBoolNo);
660 plan_sp->SetSourcedFromCompiler(eLazyBoolYes);
661 plan_sp->SetPlanValidAddressRange(
662 AddressRange(base + init_record->Address, *init_record->Size,
663 m_objfile_sp->GetModule()->GetSectionList()));
664
665 auto row_sp = std::make_shared<UnwindPlan::Row>();
666 row_sp->SetOffset(0);
667 if (!ParseCFIUnwindRow(init_record->UnwindRules, resolver, *row_sp))
668 return nullptr;
669 plan_sp->AppendRow(row_sp);
670 for (++It; It != End; ++It) {
671 std::optional<StackCFIRecord> record = StackCFIRecord::parse(*It);
672 if (!record)
673 return nullptr;
674 if (record->Size)
675 break;
676
677 row_sp = std::make_shared<UnwindPlan::Row>(*row_sp);
678 row_sp->SetOffset(record->Address - init_record->Address);
679 if (!ParseCFIUnwindRow(record->UnwindRules, resolver, *row_sp))
680 return nullptr;
681 plan_sp->AppendRow(row_sp);
682 }
683 return plan_sp;
684}
685
688 const RegisterInfoResolver &resolver) {
690 addr_t base = GetBaseFileAddress();
691 if (base == LLDB_INVALID_ADDRESS)
692 return nullptr;
693
695 std::optional<StackWinRecord> record = StackWinRecord::parse(*It);
696 assert(record && "Record already parsed successfully in ParseUnwindData!");
697
698 auto plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindLLDB);
699 plan_sp->SetSourceName("breakpad STACK WIN");
700 plan_sp->SetUnwindPlanValidAtAllInstructions(eLazyBoolNo);
701 plan_sp->SetUnwindPlanForSignalTrap(eLazyBoolNo);
702 plan_sp->SetSourcedFromCompiler(eLazyBoolYes);
703 plan_sp->SetPlanValidAddressRange(
704 AddressRange(base + record->RVA, record->CodeSize,
705 m_objfile_sp->GetModule()->GetSectionList()));
706
707 auto row_sp = std::make_shared<UnwindPlan::Row>();
708 row_sp->SetOffset(0);
709
710 llvm::BumpPtrAllocator node_alloc;
711 std::vector<std::pair<llvm::StringRef, postfix::Node *>> program =
712 postfix::ParseFPOProgram(record->ProgramString, node_alloc);
713
714 if (program.empty()) {
715 LLDB_LOG(log, "Invalid unwind rule: {0}.", record->ProgramString);
716 return nullptr;
717 }
718 auto it = program.begin();
719 llvm::Triple triple = m_objfile_sp->GetArchitecture().GetTriple();
720 const auto &symbol_resolver =
721 [&](postfix::SymbolNode &symbol) -> postfix::Node * {
722 llvm::StringRef name = symbol.GetName();
723 for (const auto &rule : llvm::make_range(program.begin(), it)) {
724 if (rule.first == name)
725 return rule.second;
726 }
727 if (const RegisterInfo *info = ResolveRegister(triple, resolver, name))
728 return postfix::MakeNode<postfix::RegisterNode>(
729 node_alloc, info->kinds[eRegisterKindLLDB]);
730 return nullptr;
731 };
732
733 // We assume the first value will be the CFA. It is usually called T0, but
734 // clang will use T1, if it needs to realign the stack.
735 auto *symbol = llvm::dyn_cast<postfix::SymbolNode>(it->second);
736 if (symbol && symbol->GetName() == ".raSearch") {
737 row_sp->GetCFAValue().SetRaSearch(record->LocalSize +
738 record->SavedRegisterSize);
739 } else {
740 if (!postfix::ResolveSymbols(it->second, symbol_resolver)) {
741 LLDB_LOG(log, "Resolving symbols in `{0}` failed.",
742 record->ProgramString);
743 return nullptr;
744 }
745 llvm::ArrayRef<uint8_t> saved = SaveAsDWARF(*it->second);
746 row_sp->GetCFAValue().SetIsDWARFExpression(saved.data(), saved.size());
747 }
748
749 // Replace the node value with InitialValueNode, so that subsequent
750 // expressions refer to the CFA value instead of recomputing the whole
751 // expression.
752 it->second = postfix::MakeNode<postfix::InitialValueNode>(node_alloc);
753
754
755 // Now process the rest of the assignments.
756 for (++it; it != program.end(); ++it) {
757 const RegisterInfo *info = ResolveRegister(triple, resolver, it->first);
758 // It is not an error if the resolution fails because the program may
759 // contain temporary variables.
760 if (!info)
761 continue;
762 if (!postfix::ResolveSymbols(it->second, symbol_resolver)) {
763 LLDB_LOG(log, "Resolving symbols in `{0}` failed.",
764 record->ProgramString);
765 return nullptr;
766 }
767
768 llvm::ArrayRef<uint8_t> saved = SaveAsDWARF(*it->second);
770 loc.SetIsDWARFExpression(saved.data(), saved.size());
771 row_sp->SetRegisterInfo(info->kinds[eRegisterKindLLDB], loc);
772 }
773
774 plan_sp->AppendRow(row_sp);
775 return plan_sp;
776}
777
779 return m_objfile_sp->GetModule()
780 ->GetObjectFile()
781 ->GetBaseAddress()
782 .GetFileAddress();
783}
784
785// Parse out all the FILE records from the breakpad file. These will be needed
786// when constructing the support file lists for individual compile units.
788 if (m_files)
789 return;
790 m_files.emplace();
791
793 for (llvm::StringRef line : lines(Record::File)) {
794 auto record = FileRecord::parse(line);
795 if (!record) {
796 LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", line);
797 continue;
798 }
799
800 if (record->Number >= m_files->size())
801 m_files->resize(record->Number + 1);
802 FileSpec::Style style = FileSpec::GuessPathStyle(record->Name)
803 .value_or(FileSpec::Style::native);
804 (*m_files)[record->Number] = FileSpec(record->Name, style);
805 }
806}
807
809 if (m_cu_data)
810 return;
811
812 m_cu_data.emplace();
814 addr_t base = GetBaseFileAddress();
815 if (base == LLDB_INVALID_ADDRESS) {
816 LLDB_LOG(log, "SymbolFile parsing failed: Unable to fetch the base address "
817 "of object file.");
818 }
819
820 // We shall create one compile unit for each FUNC record. So, count the number
821 // of FUNC records, and store them in m_cu_data, together with their ranges.
823 It != End; ++It) {
824 if (auto record = FuncRecord::parse(*It)) {
825 m_cu_data->Append(CompUnitMap::Entry(base + record->Address, record->Size,
826 CompUnitData(It.GetBookmark())));
827 } else
828 LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", *It);
829 }
830 m_cu_data->Sort();
831}
832
833// Construct the list of support files and line table entries for the given
834// compile unit.
836 CompUnitData &data) {
837 addr_t base = GetBaseFileAddress();
838 assert(base != LLDB_INVALID_ADDRESS &&
839 "How did we create compile units without a base address?");
840
841 SupportFileMap map;
842 std::vector<std::unique_ptr<LineSequence>> sequences;
843 std::unique_ptr<LineSequence> line_seq_up =
845 std::optional<addr_t> next_addr;
846 auto finish_sequence = [&]() {
848 line_seq_up.get(), *next_addr, /*line=*/0, /*column=*/0,
849 /*file_idx=*/0, /*is_start_of_statement=*/false,
850 /*is_start_of_basic_block=*/false, /*is_prologue_end=*/false,
851 /*is_epilogue_begin=*/false, /*is_terminal_entry=*/true);
852 sequences.push_back(std::move(line_seq_up));
854 };
855
857 End(*m_objfile_sp);
858 assert(Record::classify(*It) == Record::Func);
859 for (++It; It != End; ++It) {
860 // Skip INLINE records
862 continue;
863
864 auto record = LineRecord::parse(*It);
865 if (!record)
866 break;
867
868 record->Address += base;
869
870 if (next_addr && *next_addr != record->Address) {
871 // Discontiguous entries. Finish off the previous sequence and reset.
872 finish_sequence();
873 }
875 line_seq_up.get(), record->Address, record->LineNum, /*column=*/0,
876 map[record->FileNum], /*is_start_of_statement=*/true,
877 /*is_start_of_basic_block=*/false, /*is_prologue_end=*/false,
878 /*is_epilogue_begin=*/false, /*is_terminal_entry=*/false);
879 next_addr = record->Address + record->Size;
880 }
881 if (next_addr)
882 finish_sequence();
883 data.line_table_up = std::make_unique<LineTable>(&cu, std::move(sequences));
884 data.support_files = map.translate(cu.GetPrimaryFile(), *m_files);
885}
886
888 if (m_unwind_data)
889 return;
890 m_unwind_data.emplace();
891
893 addr_t base = GetBaseFileAddress();
894 if (base == LLDB_INVALID_ADDRESS) {
895 LLDB_LOG(log, "SymbolFile parsing failed: Unable to fetch the base address "
896 "of object file.");
897 }
898
900 It != End; ++It) {
901 if (auto record = StackCFIRecord::parse(*It)) {
902 if (record->Size)
904 base + record->Address, *record->Size, It.GetBookmark()));
905 } else
906 LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", *It);
907 }
908 m_unwind_data->cfi.Sort();
909
911 It != End; ++It) {
912 if (auto record = StackWinRecord::parse(*It)) {
914 base + record->RVA, record->CodeSize, It.GetBookmark()));
915 } else
916 LLDB_LOG(log, "Failed to parse: {0}. Skipping record.", *It);
917 }
918 m_unwind_data->win.Sort();
919}
920
921uint64_t SymbolFileBreakpad::GetDebugInfoSize(bool load_all_debug_info) {
922 // Breakpad files are all debug info.
923 return m_objfile_sp->GetByteSize();
924}
#define lldbassert(x)
Definition: LLDBAssert.h:15
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition: Log.h:359
#define LLDB_PLUGIN_DEFINE(PluginName)
Definition: PluginManager.h:31
static std::optional< std::pair< llvm::StringRef, llvm::StringRef > > GetRule(llvm::StringRef &unwind_rules)
static const RegisterInfo * ResolveRegister(const llvm::Triple &triple, const SymbolFile::RegisterInfoResolver &resolver, llvm::StringRef name)
static const RegisterInfo * ResolveRegisterOrRA(const llvm::Triple &triple, const SymbolFile::RegisterInfoResolver &resolver, llvm::StringRef name)
friend bool operator!=(const LineIterator &lhs, const LineIterator &rhs)
LineIterator(ObjectFile &obj, Record::Kind section_type)
A section + offset based address range class.
Definition: AddressRange.h:25
Address & GetBaseAddress()
Get accessor for the base address of the range.
Definition: AddressRange.h:211
lldb::addr_t GetByteSize() const
Get accessor for the byte size of this range.
Definition: AddressRange.h:223
A section + offset based address class.
Definition: Address.h:62
lldb::addr_t GetFileAddress() const
Get the file address.
Definition: Address.cpp:293
lldb::addr_t GetOffset() const
Get the section relative offset value.
Definition: Address.h:329
An architecture specification class.
Definition: ArchSpec.h:31
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition: ArchSpec.cpp:691
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition: ArchSpec.cpp:738
A class that describes a single lexical block.
Definition: Block.h:41
Block * FindInnermostBlockByOffset(const lldb::addr_t offset)
Definition: Block.cpp:126
void AddRange(const Range &range)
Add a new offset range to this block.
Definition: Block.cpp:351
A class that describes a compilation unit.
Definition: CompileUnit.h:41
const FileSpec & GetPrimaryFile() const
Return the primary source spec associated with this compile unit.
Definition: CompileUnit.h:230
void ResolveSymbolContext(const SourceLocationSpec &src_location_spec, lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list)
Resolve symbol contexts by file and line.
void SetLineTable(LineTable *line_table)
Set the line table for the compile unit.
void AddFunction(lldb::FunctionSP &function_sp)
Add a function to this compile unit.
lldb::FunctionSP FindFunctionByUID(lldb::user_id_t uid)
Finds a function by user ID.
LineTable * GetLineTable()
Get the line table for the compile unit.
Represents a generic declaration context in a program.
A uniqued constant string class.
Definition: ConstString.h:40
An data extractor class.
Definition: DataExtractor.h:48
const void * GetData(lldb::offset_t *offset_ptr, lldb::offset_t length) const
Extract length bytes from *offset_ptr.
A class that describes the declaration location of a lldb object.
Definition: Declaration.h:24
A file collection class.
Definition: FileSpecList.h:85
A file utility class.
Definition: FileSpec.h:56
static std::optional< Style > GuessPathStyle(llvm::StringRef absolute_path)
Attempt to guess path style for a given path string.
Definition: FileSpec.cpp:310
llvm::sys::path::Style Style
Definition: FileSpec.h:58
A class that describes a function.
Definition: Function.h:399
const AddressRange & GetAddressRange()
Definition: Function.h:447
CompileUnit * GetCompileUnit()
Get accessor for the compile unit that owns this function.
Definition: Function.cpp:386
Block & GetBlock(bool can_create)
Get accessor for the block list.
Definition: Function.cpp:371
static std::unique_ptr< LineSequence > CreateLineSequenceContainer()
Definition: LineTable.cpp:65
bool FindLineEntryByAddress(const Address &so_addr, LineEntry &line_entry, uint32_t *index_ptr=nullptr)
Find a line entry that contains the section offset address so_addr.
Definition: LineTable.cpp:188
static void AppendLineEntryToSequence(LineSequence *sequence, lldb::addr_t file_addr, uint32_t line, uint16_t column, uint16_t file_idx, bool is_start_of_statement, bool is_start_of_basic_block, bool is_prologue_end, bool is_epilogue_begin, bool is_terminal_entry)
Definition: LineTable.cpp:69
A class that handles mangled names.
Definition: Mangled.h:33
void SetValue(ConstString name)
Set the string value in this object.
Definition: Mangled.cpp:120
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
Definition: ModuleChild.cpp:24
A class that encapsulates name lookup information.
Definition: Module.h:904
ConstString GetLookupName() const
Definition: Module.h:915
A class that describes an executable image and its associated object and symbol files.
Definition: Module.h:88
virtual SectionList * GetSectionList()
Get the unified section list for the module.
Definition: Module.cpp:1224
A plug-in interface definition class for object file parsers.
Definition: ObjectFile.h:44
virtual SectionList * GetSectionList(bool update_module_section_list=true)
Gets the section list for the currently selected architecture (and object for archives).
Definition: ObjectFile.cpp:590
virtual size_t ReadSectionData(Section *section, lldb::offset_t section_offset, void *dst, size_t dst_len)
Definition: ObjectFile.cpp:476
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
size_t GetNumSections(uint32_t depth) const
Definition: Section.cpp:533
lldb::SectionSP FindSectionContainingFileAddress(lldb::addr_t addr, uint32_t depth=UINT32_MAX) const
Definition: Section.cpp:611
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition: Section.cpp:544
ConstString GetName() const
Definition: Section.h:184
"lldb/Core/SourceLocationSpec.h" A source location specifier class.
@ eBinary
Get and put data as binary instead of as the default string mode.
Definition: Stream.h:32
A list of support files for a CompileUnit.
Definition: FileSpecList.h:23
void Append(const FileSpec &file)
Definition: FileSpecList.h:34
Defines a list of symbol context objects.
uint32_t GetSize() const
Get accessor for a symbol context list size.
void Append(const SymbolContext &sc)
Append a new symbol context to the list.
Defines a symbol context baton that can be handed other debug core functions.
Definition: SymbolContext.h:34
Function * function
The Function for a given query.
Block * block
The Block for a given query.
lldb::ModuleSP module_sp
The Module for a given query.
CompileUnit * comp_unit
The CompileUnit for a given query.
LineEntry line_entry
The LineEntry for a given query.
lldb::CompUnitSP GetCompileUnitAtIndex(uint32_t idx) override
Definition: SymbolFile.cpp:192
lldb::ObjectFileSP m_objfile_sp
Definition: SymbolFile.h:601
void SetCompileUnitAtIndex(uint32_t idx, const lldb::CompUnitSP &cu_sp)
Definition: SymbolFile.cpp:203
uint32_t GetNumCompileUnits() override
Definition: SymbolFile.cpp:182
virtual std::recursive_mutex & GetModuleMutex() const
Symbols file subclasses should override this to return the Module that owns the TypeSystem that this ...
Definition: SymbolFile.cpp:36
Address GetAddress() const
Definition: Symbol.h:88
uint32_t AddSymbol(const Symbol &symbol)
Definition: Symtab.cpp:64
void SetIsDWARFExpression(const uint8_t *opcodes, uint32_t len)
Definition: UnwindPlan.h:244
void SetIsDWARFExpression(const uint8_t *opcodes, uint32_t len)
Definition: UnwindPlan.cpp:65
void SetRegisterInfo(uint32_t reg_num, const RegisterLocation register_location)
Definition: UnwindPlan.cpp:273
static std::optional< FileRecord > parse(llvm::StringRef Line)
static std::optional< FuncRecord > parse(llvm::StringRef Line)
static std::optional< InlineOriginRecord > parse(llvm::StringRef Line)
static std::optional< InlineRecord > parse(llvm::StringRef Line)
static std::optional< LineRecord > parse(llvm::StringRef Line)
static std::optional< PublicRecord > parse(llvm::StringRef Line)
static std::optional< Kind > classify(llvm::StringRef Line)
Attempt to guess the kind of the record present in the argument without doing a full parse.
static std::optional< StackCFIRecord > parse(llvm::StringRef Line)
static std::optional< StackWinRecord > parse(llvm::StringRef Line)
size_t ParseBlocksRecursive(Function &func) override
uint64_t GetDebugInfoSize(bool load_all_debug_info=false) override
Metrics gathering functions.
size_t ParseFunctions(CompileUnit &comp_unit) override
static void DebuggerInitialize(Debugger &debugger)
lldb::CompUnitSP ParseCompileUnitAtIndex(uint32_t index) override
lldb::UnwindPlanSP ParseCFIUnwindPlan(const Bookmark &bookmark, const RegisterInfoResolver &resolver)
lldb::UnwindPlanSP ParseWinUnwindPlan(const Bookmark &bookmark, const RegisterInfoResolver &resolver)
llvm::ArrayRef< uint8_t > SaveAsDWARF(postfix::Node &node)
bool ParseCFIUnwindRow(llvm::StringRef unwind_rules, const RegisterInfoResolver &resolver, UnwindPlan::Row &row)
lldb::UnwindPlanSP GetUnwindPlan(const Address &address, const RegisterInfoResolver &resolver) override
llvm::Expected< lldb::addr_t > GetParameterStackSize(Symbol &symbol) override
Return the number of stack bytes taken up by the parameters to this function.
std::optional< std::vector< llvm::StringRef > > m_inline_origins
static llvm::StringRef GetPluginDescriptionStatic()
std::optional< std::vector< FileSpec > > m_files
bool ParseLineTable(CompileUnit &comp_unit) override
uint32_t ResolveSymbolContext(const Address &so_addr, lldb::SymbolContextItem resolve_scope, SymbolContext &sc) override
static SymbolFile * CreateInstance(lldb::ObjectFileSP objfile_sp)
void FindFunctions(const Module::LookupInfo &lookup_info, const CompilerDeclContext &parent_decl_ctx, bool include_inlines, SymbolContextList &sc_list) override
bool ParseSupportFiles(CompileUnit &comp_unit, SupportFileList &support_files) override
void ParseLineTableAndSupportFiles(CompileUnit &cu, CompUnitData &data)
lldb::FunctionSP GetOrCreateFunction(CompileUnit &comp_unit)
llvm::iterator_range< LineIterator > lines(Record::Kind section_type)
The base class for all nodes in the parsed postfix tree.
A node representing a symbolic reference to a named entity.
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
#define UINT32_MAX
Definition: lldb-defines.h:19
#define LLDB_REGNUM_GENERIC_PC
Definition: lldb-defines.h:56
llvm::StringRef toString(Record::Kind K)
Node * ParseOneExpression(llvm::StringRef expr, llvm::BumpPtrAllocator &alloc)
Parse the given postfix expression.
bool ResolveSymbols(Node *&node, llvm::function_ref< Node *(SymbolNode &symbol)> replacer)
A utility function for "resolving" SymbolNodes.
std::vector< std::pair< llvm::StringRef, Node * > > ParseFPOProgram(llvm::StringRef prog, llvm::BumpPtrAllocator &alloc)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:331
const char * toString(AppleArm64ExceptionClass EC)
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::Function > FunctionSP
Definition: lldb-forward.h:350
std::shared_ptr< lldb_private::Block > BlockSP
Definition: lldb-forward.h:315
@ eLanguageTypeUnknown
Unknown or invalid language value.
std::shared_ptr< lldb_private::UnwindPlan > UnwindPlanSP
Definition: lldb-forward.h:474
uint64_t user_id_t
Definition: lldb-types.h:82
std::shared_ptr< lldb_private::Section > SectionSP
Definition: lldb-forward.h:409
uint64_t addr_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::CompileUnit > CompUnitSP
Definition: lldb-forward.h:330
@ eRegisterKindGeneric
insn ptr reg, stack ptr reg, etc not specific to any particular target
@ eRegisterKindLLDB
lldb's internal register numbers
Definition: Debugger.h:54
Every register is described in detail including its name, alternate name (optional),...
uint32_t kinds[lldb::kNumRegisterKinds]
Holds all of the various register numbers for all register kinds.
virtual const RegisterInfo * ResolveNumber(lldb::RegisterKind kind, uint32_t number) const =0
virtual const RegisterInfo * ResolveName(llvm::StringRef name) const =0
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:47