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