1 //===-- llvm-dwp.cpp - Split DWARF merging tool for llvm ------------------===// 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 // A utility for merging DWARF 5 Split DWARF .dwo files into .dwp (DWARF 10 // package files). 11 // 12 //===----------------------------------------------------------------------===// 13 #include "DWPError.h" 14 #include "DWPStringPool.h" 15 #include "llvm/ADT/MapVector.h" 16 #include "llvm/ADT/Optional.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 19 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h" 20 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h" 21 #include "llvm/MC/MCAsmBackend.h" 22 #include "llvm/MC/MCAsmInfo.h" 23 #include "llvm/MC/MCCodeEmitter.h" 24 #include "llvm/MC/MCContext.h" 25 #include "llvm/MC/MCInstrInfo.h" 26 #include "llvm/MC/MCObjectFileInfo.h" 27 #include "llvm/MC/MCObjectWriter.h" 28 #include "llvm/MC/MCRegisterInfo.h" 29 #include "llvm/MC/MCStreamer.h" 30 #include "llvm/MC/MCTargetOptionsCommandFlags.h" 31 #include "llvm/Object/Decompressor.h" 32 #include "llvm/Object/ObjectFile.h" 33 #include "llvm/Support/DataExtractor.h" 34 #include "llvm/Support/Error.h" 35 #include "llvm/Support/FileSystem.h" 36 #include "llvm/Support/InitLLVM.h" 37 #include "llvm/Support/MathExtras.h" 38 #include "llvm/Support/MemoryBuffer.h" 39 #include "llvm/Support/Path.h" 40 #include "llvm/Support/TargetRegistry.h" 41 #include "llvm/Support/TargetSelect.h" 42 #include "llvm/Support/ToolOutputFile.h" 43 #include "llvm/Support/WithColor.h" 44 #include "llvm/Support/raw_ostream.h" 45 46 using namespace llvm; 47 using namespace llvm::object; 48 49 static mc::RegisterMCTargetOptionsFlags MCTargetOptionsFlags; 50 51 cl::OptionCategory DwpCategory("Specific Options"); 52 static cl::list<std::string> InputFiles(cl::Positional, cl::ZeroOrMore, 53 cl::desc("<input files>"), 54 cl::cat(DwpCategory)); 55 56 static cl::list<std::string> ExecFilenames( 57 "e", cl::ZeroOrMore, 58 cl::desc("Specify the executable/library files to get the list of *.dwo from"), 59 cl::value_desc("filename"), cl::cat(DwpCategory)); 60 61 static cl::opt<std::string> OutputFilename(cl::Required, "o", 62 cl::desc("Specify the output file."), 63 cl::value_desc("filename"), 64 cl::cat(DwpCategory)); 65 66 static void writeStringsAndOffsets(MCStreamer &Out, DWPStringPool &Strings, 67 MCSection *StrOffsetSection, 68 StringRef CurStrSection, 69 StringRef CurStrOffsetSection) { 70 // Could possibly produce an error or warning if one of these was non-null but 71 // the other was null. 72 if (CurStrSection.empty() || CurStrOffsetSection.empty()) 73 return; 74 75 DenseMap<uint64_t, uint32_t> OffsetRemapping; 76 77 DataExtractor Data(CurStrSection, true, 0); 78 uint64_t LocalOffset = 0; 79 uint64_t PrevOffset = 0; 80 while (const char *s = Data.getCStr(&LocalOffset)) { 81 OffsetRemapping[PrevOffset] = 82 Strings.getOffset(s, LocalOffset - PrevOffset); 83 PrevOffset = LocalOffset; 84 } 85 86 Data = DataExtractor(CurStrOffsetSection, true, 0); 87 88 Out.SwitchSection(StrOffsetSection); 89 90 uint64_t Offset = 0; 91 uint64_t Size = CurStrOffsetSection.size(); 92 while (Offset < Size) { 93 auto OldOffset = Data.getU32(&Offset); 94 auto NewOffset = OffsetRemapping[OldOffset]; 95 Out.emitIntValue(NewOffset, 4); 96 } 97 } 98 99 static uint64_t getCUAbbrev(StringRef Abbrev, uint64_t AbbrCode) { 100 uint64_t CurCode; 101 uint64_t Offset = 0; 102 DataExtractor AbbrevData(Abbrev, true, 0); 103 while ((CurCode = AbbrevData.getULEB128(&Offset)) != AbbrCode) { 104 // Tag 105 AbbrevData.getULEB128(&Offset); 106 // DW_CHILDREN 107 AbbrevData.getU8(&Offset); 108 // Attributes 109 while (AbbrevData.getULEB128(&Offset) | AbbrevData.getULEB128(&Offset)) 110 ; 111 } 112 return Offset; 113 } 114 115 struct CompileUnitIdentifiers { 116 uint64_t Signature = 0; 117 const char *Name = ""; 118 const char *DWOName = ""; 119 }; 120 121 static Expected<const char *> 122 getIndexedString(dwarf::Form Form, DataExtractor InfoData, 123 uint64_t &InfoOffset, StringRef StrOffsets, StringRef Str) { 124 if (Form == dwarf::DW_FORM_string) 125 return InfoData.getCStr(&InfoOffset); 126 if (Form != dwarf::DW_FORM_GNU_str_index) 127 return make_error<DWPError>( 128 "string field encoded without DW_FORM_string or DW_FORM_GNU_str_index"); 129 auto StrIndex = InfoData.getULEB128(&InfoOffset); 130 DataExtractor StrOffsetsData(StrOffsets, true, 0); 131 uint64_t StrOffsetsOffset = 4 * StrIndex; 132 uint64_t StrOffset = StrOffsetsData.getU32(&StrOffsetsOffset); 133 DataExtractor StrData(Str, true, 0); 134 return StrData.getCStr(&StrOffset); 135 } 136 137 static Expected<CompileUnitIdentifiers> getCUIdentifiers(StringRef Abbrev, 138 StringRef Info, 139 StringRef StrOffsets, 140 StringRef Str) { 141 uint64_t Offset = 0; 142 DataExtractor InfoData(Info, true, 0); 143 dwarf::DwarfFormat Format = dwarf::DwarfFormat::DWARF32; 144 uint64_t Length = InfoData.getU32(&Offset); 145 CompileUnitIdentifiers ID; 146 Optional<uint64_t> Signature = None; 147 // If the length is 0xffffffff, then this indictes that this is a DWARF 64 148 // stream and the length is actually encoded into a 64 bit value that follows. 149 if (Length == 0xffffffffU) { 150 Format = dwarf::DwarfFormat::DWARF64; 151 Length = InfoData.getU64(&Offset); 152 } 153 uint16_t Version = InfoData.getU16(&Offset); 154 if (Version >= 5) { 155 auto UnitType = InfoData.getU8(&Offset); 156 if (UnitType != dwarf::DW_UT_split_compile) 157 return make_error<DWPError>( 158 std::string("unit type DW_UT_split_compile type not found in " 159 "debug_info header. Unexpected unit type 0x" + 160 utostr(UnitType) + " found")); 161 } 162 InfoData.getU32(&Offset); // Abbrev offset (should be zero) 163 uint8_t AddrSize = InfoData.getU8(&Offset); 164 if (Version >= 5) 165 Signature = InfoData.getU64(&Offset); 166 uint32_t AbbrCode = InfoData.getULEB128(&Offset); 167 168 DataExtractor AbbrevData(Abbrev, true, 0); 169 uint64_t AbbrevOffset = getCUAbbrev(Abbrev, AbbrCode); 170 auto Tag = static_cast<dwarf::Tag>(AbbrevData.getULEB128(&AbbrevOffset)); 171 if (Tag != dwarf::DW_TAG_compile_unit) 172 return make_error<DWPError>("top level DIE is not a compile unit"); 173 // DW_CHILDREN 174 AbbrevData.getU8(&AbbrevOffset); 175 uint32_t Name; 176 dwarf::Form Form; 177 while ((Name = AbbrevData.getULEB128(&AbbrevOffset)) | 178 (Form = static_cast<dwarf::Form>(AbbrevData.getULEB128(&AbbrevOffset))) && 179 (Name != 0 || Form != 0)) { 180 switch (Name) { 181 case dwarf::DW_AT_name: { 182 Expected<const char *> EName = 183 getIndexedString(Form, InfoData, Offset, StrOffsets, Str); 184 if (!EName) 185 return EName.takeError(); 186 ID.Name = *EName; 187 break; 188 } 189 case dwarf::DW_AT_GNU_dwo_name: 190 case dwarf::DW_AT_dwo_name: { 191 Expected<const char *> EName = 192 getIndexedString(Form, InfoData, Offset, StrOffsets, Str); 193 if (!EName) 194 return EName.takeError(); 195 ID.DWOName = *EName; 196 break; 197 } 198 case dwarf::DW_AT_GNU_dwo_id: 199 Signature = InfoData.getU64(&Offset); 200 break; 201 default: 202 DWARFFormValue::skipValue(Form, InfoData, &Offset, 203 dwarf::FormParams({Version, AddrSize, Format})); 204 } 205 } 206 if (!Signature) 207 return make_error<DWPError>("compile unit missing dwo_id"); 208 ID.Signature = *Signature; 209 return ID; 210 } 211 212 struct UnitIndexEntry { 213 DWARFUnitIndex::Entry::SectionContribution Contributions[8]; 214 std::string Name; 215 std::string DWOName; 216 StringRef DWPName; 217 }; 218 219 static bool isSupportedSectionKind(DWARFSectionKind Kind) { 220 return Kind != DW_SECT_EXT_unknown; 221 } 222 223 // Convert an internal section identifier into the index to use with 224 // UnitIndexEntry::Contributions. 225 static unsigned getContributionIndex(DWARFSectionKind Kind) { 226 // Assuming the pre-standard DWP format. 227 assert(serializeSectionKind(Kind, 2) >= DW_SECT_INFO); 228 return serializeSectionKind(Kind, 2) - DW_SECT_INFO; 229 } 230 231 // Convert a UnitIndexEntry::Contributions index to the corresponding on-disk 232 // value of the section identifier. 233 static unsigned getOnDiskSectionId(unsigned Index) { 234 return Index + DW_SECT_INFO; 235 } 236 237 static StringRef getSubsection(StringRef Section, 238 const DWARFUnitIndex::Entry &Entry, 239 DWARFSectionKind Kind) { 240 const auto *Off = Entry.getContribution(Kind); 241 if (!Off) 242 return StringRef(); 243 return Section.substr(Off->Offset, Off->Length); 244 } 245 246 static void addAllTypesFromDWP( 247 MCStreamer &Out, MapVector<uint64_t, UnitIndexEntry> &TypeIndexEntries, 248 const DWARFUnitIndex &TUIndex, MCSection *OutputTypes, StringRef Types, 249 const UnitIndexEntry &TUEntry, uint32_t &TypesOffset) { 250 Out.SwitchSection(OutputTypes); 251 for (const DWARFUnitIndex::Entry &E : TUIndex.getRows()) { 252 auto *I = E.getContributions(); 253 if (!I) 254 continue; 255 auto P = TypeIndexEntries.insert(std::make_pair(E.getSignature(), TUEntry)); 256 if (!P.second) 257 continue; 258 auto &Entry = P.first->second; 259 // Zero out the debug_info contribution 260 Entry.Contributions[0] = {}; 261 for (auto Kind : TUIndex.getColumnKinds()) { 262 if (!isSupportedSectionKind(Kind)) 263 continue; 264 auto &C = Entry.Contributions[getContributionIndex(Kind)]; 265 C.Offset += I->Offset; 266 C.Length = I->Length; 267 ++I; 268 } 269 unsigned TypesIndex = getContributionIndex(DW_SECT_EXT_TYPES); 270 auto &C = Entry.Contributions[TypesIndex]; 271 Out.emitBytes(Types.substr( 272 C.Offset - TUEntry.Contributions[TypesIndex].Offset, C.Length)); 273 C.Offset = TypesOffset; 274 TypesOffset += C.Length; 275 } 276 } 277 278 static void addAllTypes(MCStreamer &Out, 279 MapVector<uint64_t, UnitIndexEntry> &TypeIndexEntries, 280 MCSection *OutputTypes, 281 const std::vector<StringRef> &TypesSections, 282 const UnitIndexEntry &CUEntry, uint32_t &TypesOffset) { 283 for (StringRef Types : TypesSections) { 284 Out.SwitchSection(OutputTypes); 285 uint64_t Offset = 0; 286 DataExtractor Data(Types, true, 0); 287 while (Data.isValidOffset(Offset)) { 288 UnitIndexEntry Entry = CUEntry; 289 // Zero out the debug_info contribution 290 Entry.Contributions[0] = {}; 291 auto &C = Entry.Contributions[getContributionIndex(DW_SECT_EXT_TYPES)]; 292 C.Offset = TypesOffset; 293 auto PrevOffset = Offset; 294 // Length of the unit, including the 4 byte length field. 295 C.Length = Data.getU32(&Offset) + 4; 296 297 Data.getU16(&Offset); // Version 298 Data.getU32(&Offset); // Abbrev offset 299 Data.getU8(&Offset); // Address size 300 auto Signature = Data.getU64(&Offset); 301 Offset = PrevOffset + C.Length; 302 303 auto P = TypeIndexEntries.insert(std::make_pair(Signature, Entry)); 304 if (!P.second) 305 continue; 306 307 Out.emitBytes(Types.substr(PrevOffset, C.Length)); 308 TypesOffset += C.Length; 309 } 310 } 311 } 312 313 static void 314 writeIndexTable(MCStreamer &Out, ArrayRef<unsigned> ContributionOffsets, 315 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries, 316 uint32_t DWARFUnitIndex::Entry::SectionContribution::*Field) { 317 for (const auto &E : IndexEntries) 318 for (size_t i = 0; i != array_lengthof(E.second.Contributions); ++i) 319 if (ContributionOffsets[i]) 320 Out.emitIntValue(E.second.Contributions[i].*Field, 4); 321 } 322 323 static void 324 writeIndex(MCStreamer &Out, MCSection *Section, 325 ArrayRef<unsigned> ContributionOffsets, 326 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries) { 327 if (IndexEntries.empty()) 328 return; 329 330 unsigned Columns = 0; 331 for (auto &C : ContributionOffsets) 332 if (C) 333 ++Columns; 334 335 std::vector<unsigned> Buckets(NextPowerOf2(3 * IndexEntries.size() / 2)); 336 uint64_t Mask = Buckets.size() - 1; 337 size_t i = 0; 338 for (const auto &P : IndexEntries) { 339 auto S = P.first; 340 auto H = S & Mask; 341 auto HP = ((S >> 32) & Mask) | 1; 342 while (Buckets[H]) { 343 assert(S != IndexEntries.begin()[Buckets[H] - 1].first && 344 "Duplicate unit"); 345 H = (H + HP) & Mask; 346 } 347 Buckets[H] = i + 1; 348 ++i; 349 } 350 351 Out.SwitchSection(Section); 352 Out.emitIntValue(2, 4); // Version 353 Out.emitIntValue(Columns, 4); // Columns 354 Out.emitIntValue(IndexEntries.size(), 4); // Num Units 355 Out.emitIntValue(Buckets.size(), 4); // Num Buckets 356 357 // Write the signatures. 358 for (const auto &I : Buckets) 359 Out.emitIntValue(I ? IndexEntries.begin()[I - 1].first : 0, 8); 360 361 // Write the indexes. 362 for (const auto &I : Buckets) 363 Out.emitIntValue(I, 4); 364 365 // Write the column headers (which sections will appear in the table) 366 for (size_t i = 0; i != ContributionOffsets.size(); ++i) 367 if (ContributionOffsets[i]) 368 Out.emitIntValue(getOnDiskSectionId(i), 4); 369 370 // Write the offsets. 371 writeIndexTable(Out, ContributionOffsets, IndexEntries, 372 &DWARFUnitIndex::Entry::SectionContribution::Offset); 373 374 // Write the lengths. 375 writeIndexTable(Out, ContributionOffsets, IndexEntries, 376 &DWARFUnitIndex::Entry::SectionContribution::Length); 377 } 378 379 std::string buildDWODescription(StringRef Name, StringRef DWPName, StringRef DWOName) { 380 std::string Text = "\'"; 381 Text += Name; 382 Text += '\''; 383 if (!DWPName.empty()) { 384 Text += " (from "; 385 if (!DWOName.empty()) { 386 Text += '\''; 387 Text += DWOName; 388 Text += "' in "; 389 } 390 Text += '\''; 391 Text += DWPName; 392 Text += "')"; 393 } 394 return Text; 395 } 396 397 static Error createError(StringRef Name, Error E) { 398 return make_error<DWPError>( 399 ("failure while decompressing compressed section: '" + Name + "', " + 400 llvm::toString(std::move(E))) 401 .str()); 402 } 403 404 static Error 405 handleCompressedSection(std::deque<SmallString<32>> &UncompressedSections, 406 StringRef &Name, StringRef &Contents) { 407 if (!Decompressor::isGnuStyle(Name)) 408 return Error::success(); 409 410 Expected<Decompressor> Dec = 411 Decompressor::create(Name, Contents, false /*IsLE*/, false /*Is64Bit*/); 412 if (!Dec) 413 return createError(Name, Dec.takeError()); 414 415 UncompressedSections.emplace_back(); 416 if (Error E = Dec->resizeAndDecompress(UncompressedSections.back())) 417 return createError(Name, std::move(E)); 418 419 Name = Name.substr(2); // Drop ".z" 420 Contents = UncompressedSections.back(); 421 return Error::success(); 422 } 423 424 static Error handleSection( 425 const StringMap<std::pair<MCSection *, DWARFSectionKind>> &KnownSections, 426 const MCSection *StrSection, const MCSection *StrOffsetSection, 427 const MCSection *TypesSection, const MCSection *CUIndexSection, 428 const MCSection *TUIndexSection, const SectionRef &Section, MCStreamer &Out, 429 std::deque<SmallString<32>> &UncompressedSections, 430 uint32_t (&ContributionOffsets)[8], UnitIndexEntry &CurEntry, 431 StringRef &CurStrSection, StringRef &CurStrOffsetSection, 432 std::vector<StringRef> &CurTypesSection, StringRef &InfoSection, 433 StringRef &AbbrevSection, StringRef &CurCUIndexSection, 434 StringRef &CurTUIndexSection) { 435 if (Section.isBSS()) 436 return Error::success(); 437 438 if (Section.isVirtual()) 439 return Error::success(); 440 441 Expected<StringRef> NameOrErr = Section.getName(); 442 if (!NameOrErr) 443 return NameOrErr.takeError(); 444 StringRef Name = *NameOrErr; 445 446 Expected<StringRef> ContentsOrErr = Section.getContents(); 447 if (!ContentsOrErr) 448 return ContentsOrErr.takeError(); 449 StringRef Contents = *ContentsOrErr; 450 451 if (auto Err = handleCompressedSection(UncompressedSections, Name, Contents)) 452 return Err; 453 454 Name = Name.substr(Name.find_first_not_of("._")); 455 456 auto SectionPair = KnownSections.find(Name); 457 if (SectionPair == KnownSections.end()) 458 return Error::success(); 459 460 if (DWARFSectionKind Kind = SectionPair->second.second) { 461 auto Index = getContributionIndex(Kind); 462 if (Kind != DW_SECT_EXT_TYPES) { 463 CurEntry.Contributions[Index].Offset = ContributionOffsets[Index]; 464 ContributionOffsets[Index] += 465 (CurEntry.Contributions[Index].Length = Contents.size()); 466 } 467 468 switch (Kind) { 469 case DW_SECT_INFO: 470 InfoSection = Contents; 471 break; 472 case DW_SECT_ABBREV: 473 AbbrevSection = Contents; 474 break; 475 default: 476 break; 477 } 478 } 479 480 MCSection *OutSection = SectionPair->second.first; 481 if (OutSection == StrOffsetSection) 482 CurStrOffsetSection = Contents; 483 else if (OutSection == StrSection) 484 CurStrSection = Contents; 485 else if (OutSection == TypesSection) 486 CurTypesSection.push_back(Contents); 487 else if (OutSection == CUIndexSection) 488 CurCUIndexSection = Contents; 489 else if (OutSection == TUIndexSection) 490 CurTUIndexSection = Contents; 491 else { 492 Out.SwitchSection(OutSection); 493 Out.emitBytes(Contents); 494 } 495 return Error::success(); 496 } 497 498 static Error 499 buildDuplicateError(const std::pair<uint64_t, UnitIndexEntry> &PrevE, 500 const CompileUnitIdentifiers &ID, StringRef DWPName) { 501 return make_error<DWPError>( 502 std::string("duplicate DWO ID (") + utohexstr(PrevE.first) + ") in " + 503 buildDWODescription(PrevE.second.Name, PrevE.second.DWPName, 504 PrevE.second.DWOName) + 505 " and " + buildDWODescription(ID.Name, DWPName, ID.DWOName)); 506 } 507 508 static Expected<SmallVector<std::string, 16>> 509 getDWOFilenames(StringRef ExecFilename) { 510 auto ErrOrObj = object::ObjectFile::createObjectFile(ExecFilename); 511 if (!ErrOrObj) 512 return ErrOrObj.takeError(); 513 514 const ObjectFile &Obj = *ErrOrObj.get().getBinary(); 515 std::unique_ptr<DWARFContext> DWARFCtx = DWARFContext::create(Obj); 516 517 SmallVector<std::string, 16> DWOPaths; 518 for (const auto &CU : DWARFCtx->compile_units()) { 519 const DWARFDie &Die = CU->getUnitDIE(); 520 std::string DWOName = dwarf::toString( 521 Die.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), ""); 522 if (DWOName.empty()) 523 continue; 524 std::string DWOCompDir = 525 dwarf::toString(Die.find(dwarf::DW_AT_comp_dir), ""); 526 if (!DWOCompDir.empty()) { 527 SmallString<16> DWOPath; 528 sys::path::append(DWOPath, DWOCompDir, DWOName); 529 DWOPaths.emplace_back(DWOPath.data(), DWOPath.size()); 530 } else { 531 DWOPaths.push_back(std::move(DWOName)); 532 } 533 } 534 return std::move(DWOPaths); 535 } 536 537 static Error write(MCStreamer &Out, ArrayRef<std::string> Inputs) { 538 const auto &MCOFI = *Out.getContext().getObjectFileInfo(); 539 MCSection *const StrSection = MCOFI.getDwarfStrDWOSection(); 540 MCSection *const StrOffsetSection = MCOFI.getDwarfStrOffDWOSection(); 541 MCSection *const TypesSection = MCOFI.getDwarfTypesDWOSection(); 542 MCSection *const CUIndexSection = MCOFI.getDwarfCUIndexSection(); 543 MCSection *const TUIndexSection = MCOFI.getDwarfTUIndexSection(); 544 const StringMap<std::pair<MCSection *, DWARFSectionKind>> KnownSections = { 545 {"debug_info.dwo", {MCOFI.getDwarfInfoDWOSection(), DW_SECT_INFO}}, 546 {"debug_types.dwo", {MCOFI.getDwarfTypesDWOSection(), DW_SECT_EXT_TYPES}}, 547 {"debug_str_offsets.dwo", {StrOffsetSection, DW_SECT_STR_OFFSETS}}, 548 {"debug_str.dwo", {StrSection, static_cast<DWARFSectionKind>(0)}}, 549 {"debug_loc.dwo", {MCOFI.getDwarfLocDWOSection(), DW_SECT_EXT_LOC}}, 550 {"debug_line.dwo", {MCOFI.getDwarfLineDWOSection(), DW_SECT_LINE}}, 551 {"debug_abbrev.dwo", {MCOFI.getDwarfAbbrevDWOSection(), DW_SECT_ABBREV}}, 552 {"debug_cu_index", {CUIndexSection, static_cast<DWARFSectionKind>(0)}}, 553 {"debug_tu_index", {TUIndexSection, static_cast<DWARFSectionKind>(0)}}}; 554 555 MapVector<uint64_t, UnitIndexEntry> IndexEntries; 556 MapVector<uint64_t, UnitIndexEntry> TypeIndexEntries; 557 558 uint32_t ContributionOffsets[8] = {}; 559 560 DWPStringPool Strings(Out, StrSection); 561 562 SmallVector<OwningBinary<object::ObjectFile>, 128> Objects; 563 Objects.reserve(Inputs.size()); 564 565 std::deque<SmallString<32>> UncompressedSections; 566 567 for (const auto &Input : Inputs) { 568 auto ErrOrObj = object::ObjectFile::createObjectFile(Input); 569 if (!ErrOrObj) 570 return ErrOrObj.takeError(); 571 572 auto &Obj = *ErrOrObj->getBinary(); 573 Objects.push_back(std::move(*ErrOrObj)); 574 575 UnitIndexEntry CurEntry = {}; 576 577 StringRef CurStrSection; 578 StringRef CurStrOffsetSection; 579 std::vector<StringRef> CurTypesSection; 580 StringRef InfoSection; 581 StringRef AbbrevSection; 582 StringRef CurCUIndexSection; 583 StringRef CurTUIndexSection; 584 585 for (const auto &Section : Obj.sections()) 586 if (auto Err = handleSection( 587 KnownSections, StrSection, StrOffsetSection, TypesSection, 588 CUIndexSection, TUIndexSection, Section, Out, 589 UncompressedSections, ContributionOffsets, CurEntry, 590 CurStrSection, CurStrOffsetSection, CurTypesSection, InfoSection, 591 AbbrevSection, CurCUIndexSection, CurTUIndexSection)) 592 return Err; 593 594 if (InfoSection.empty()) 595 continue; 596 597 writeStringsAndOffsets(Out, Strings, StrOffsetSection, CurStrSection, 598 CurStrOffsetSection); 599 600 if (CurCUIndexSection.empty()) { 601 Expected<CompileUnitIdentifiers> EID = getCUIdentifiers( 602 AbbrevSection, InfoSection, CurStrOffsetSection, CurStrSection); 603 if (!EID) 604 return createFileError(Input, EID.takeError()); 605 const auto &ID = *EID; 606 auto P = IndexEntries.insert(std::make_pair(ID.Signature, CurEntry)); 607 if (!P.second) 608 return buildDuplicateError(*P.first, ID, ""); 609 P.first->second.Name = ID.Name; 610 P.first->second.DWOName = ID.DWOName; 611 addAllTypes(Out, TypeIndexEntries, TypesSection, CurTypesSection, 612 CurEntry, 613 ContributionOffsets[getContributionIndex(DW_SECT_EXT_TYPES)]); 614 continue; 615 } 616 617 DWARFUnitIndex CUIndex(DW_SECT_INFO); 618 DataExtractor CUIndexData(CurCUIndexSection, Obj.isLittleEndian(), 0); 619 if (!CUIndex.parse(CUIndexData)) 620 return make_error<DWPError>("failed to parse cu_index"); 621 622 for (const DWARFUnitIndex::Entry &E : CUIndex.getRows()) { 623 auto *I = E.getContributions(); 624 if (!I) 625 continue; 626 auto P = IndexEntries.insert(std::make_pair(E.getSignature(), CurEntry)); 627 Expected<CompileUnitIdentifiers> EID = getCUIdentifiers( 628 getSubsection(AbbrevSection, E, DW_SECT_ABBREV), 629 getSubsection(InfoSection, E, DW_SECT_INFO), 630 getSubsection(CurStrOffsetSection, E, DW_SECT_STR_OFFSETS), 631 CurStrSection); 632 if (!EID) 633 return createFileError(Input, EID.takeError()); 634 const auto &ID = *EID; 635 if (!P.second) 636 return buildDuplicateError(*P.first, ID, Input); 637 auto &NewEntry = P.first->second; 638 NewEntry.Name = ID.Name; 639 NewEntry.DWOName = ID.DWOName; 640 NewEntry.DWPName = Input; 641 for (auto Kind : CUIndex.getColumnKinds()) { 642 if (!isSupportedSectionKind(Kind)) 643 continue; 644 auto &C = NewEntry.Contributions[getContributionIndex(Kind)]; 645 C.Offset += I->Offset; 646 C.Length = I->Length; 647 ++I; 648 } 649 } 650 651 if (!CurTypesSection.empty()) { 652 if (CurTypesSection.size() != 1) 653 return make_error<DWPError>("multiple type unit sections in .dwp file"); 654 DWARFUnitIndex TUIndex(DW_SECT_EXT_TYPES); 655 DataExtractor TUIndexData(CurTUIndexSection, Obj.isLittleEndian(), 0); 656 if (!TUIndex.parse(TUIndexData)) 657 return make_error<DWPError>("failed to parse tu_index"); 658 addAllTypesFromDWP( 659 Out, TypeIndexEntries, TUIndex, TypesSection, CurTypesSection.front(), 660 CurEntry, 661 ContributionOffsets[getContributionIndex(DW_SECT_EXT_TYPES)]); 662 } 663 } 664 665 // Lie about there being no info contributions so the TU index only includes 666 // the type unit contribution 667 ContributionOffsets[0] = 0; 668 writeIndex(Out, MCOFI.getDwarfTUIndexSection(), ContributionOffsets, 669 TypeIndexEntries); 670 671 // Lie about the type contribution 672 ContributionOffsets[getContributionIndex(DW_SECT_EXT_TYPES)] = 0; 673 // Unlie about the info contribution 674 ContributionOffsets[0] = 1; 675 676 writeIndex(Out, MCOFI.getDwarfCUIndexSection(), ContributionOffsets, 677 IndexEntries); 678 679 return Error::success(); 680 } 681 682 static int error(const Twine &Error, const Twine &Context) { 683 errs() << Twine("while processing ") + Context + ":\n"; 684 errs() << Twine("error: ") + Error + "\n"; 685 return 1; 686 } 687 688 int main(int argc, char **argv) { 689 InitLLVM X(argc, argv); 690 691 cl::ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files\n"); 692 693 llvm::InitializeAllTargetInfos(); 694 llvm::InitializeAllTargetMCs(); 695 llvm::InitializeAllTargets(); 696 llvm::InitializeAllAsmPrinters(); 697 698 std::string ErrorStr; 699 StringRef Context = "dwarf streamer init"; 700 701 Triple TheTriple("x86_64-linux-gnu"); 702 703 // Get the target. 704 const Target *TheTarget = 705 TargetRegistry::lookupTarget("", TheTriple, ErrorStr); 706 if (!TheTarget) 707 return error(ErrorStr, Context); 708 std::string TripleName = TheTriple.getTriple(); 709 710 // Create all the MC Objects. 711 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName)); 712 if (!MRI) 713 return error(Twine("no register info for target ") + TripleName, Context); 714 715 MCTargetOptions MCOptions = llvm::mc::InitMCTargetOptionsFromFlags(); 716 std::unique_ptr<MCAsmInfo> MAI( 717 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); 718 if (!MAI) 719 return error("no asm info for target " + TripleName, Context); 720 721 MCObjectFileInfo MOFI; 722 MCContext MC(MAI.get(), MRI.get(), &MOFI); 723 MOFI.InitMCObjectFileInfo(TheTriple, /*PIC*/ false, MC); 724 725 std::unique_ptr<MCSubtargetInfo> MSTI( 726 TheTarget->createMCSubtargetInfo(TripleName, "", "")); 727 if (!MSTI) 728 return error("no subtarget info for target " + TripleName, Context); 729 730 MCTargetOptions Options; 731 auto MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, Options); 732 if (!MAB) 733 return error("no asm backend for target " + TripleName, Context); 734 735 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 736 if (!MII) 737 return error("no instr info info for target " + TripleName, Context); 738 739 MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC); 740 if (!MCE) 741 return error("no code emitter for target " + TripleName, Context); 742 743 // Create the output file. 744 std::error_code EC; 745 ToolOutputFile OutFile(OutputFilename, EC, sys::fs::OF_None); 746 Optional<buffer_ostream> BOS; 747 raw_pwrite_stream *OS; 748 if (EC) 749 return error(Twine(OutputFilename) + ": " + EC.message(), Context); 750 if (OutFile.os().supportsSeeking()) { 751 OS = &OutFile.os(); 752 } else { 753 BOS.emplace(OutFile.os()); 754 OS = BOS.getPointer(); 755 } 756 757 std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer( 758 TheTriple, MC, std::unique_ptr<MCAsmBackend>(MAB), 759 MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(MCE), *MSTI, 760 MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible, 761 /*DWARFMustBeAtTheEnd*/ false)); 762 if (!MS) 763 return error("no object streamer for target " + TripleName, Context); 764 765 std::vector<std::string> DWOFilenames = InputFiles; 766 for (const auto &ExecFilename : ExecFilenames) { 767 auto DWOs = getDWOFilenames(ExecFilename); 768 if (!DWOs) { 769 logAllUnhandledErrors(DWOs.takeError(), WithColor::error()); 770 return 1; 771 } 772 DWOFilenames.insert(DWOFilenames.end(), 773 std::make_move_iterator(DWOs->begin()), 774 std::make_move_iterator(DWOs->end())); 775 } 776 777 if (auto Err = write(*MS, DWOFilenames)) { 778 logAllUnhandledErrors(std::move(Err), WithColor::error()); 779 return 1; 780 } 781 782 MS->Finish(); 783 OutFile.keep(); 784 return 0; 785 } 786