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