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