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     if (CUIndex.getVersion() != 2)
622       return make_error<DWPError>(
623           "unsupported cu_index version: " + utostr(CUIndex.getVersion()) +
624           " (only version 2 is supported)");
625 
626     for (const DWARFUnitIndex::Entry &E : CUIndex.getRows()) {
627       auto *I = E.getContributions();
628       if (!I)
629         continue;
630       auto P = IndexEntries.insert(std::make_pair(E.getSignature(), CurEntry));
631       Expected<CompileUnitIdentifiers> EID = getCUIdentifiers(
632           getSubsection(AbbrevSection, E, DW_SECT_ABBREV),
633           getSubsection(InfoSection, E, DW_SECT_INFO),
634           getSubsection(CurStrOffsetSection, E, DW_SECT_STR_OFFSETS),
635           CurStrSection);
636       if (!EID)
637         return createFileError(Input, EID.takeError());
638       const auto &ID = *EID;
639       if (!P.second)
640         return buildDuplicateError(*P.first, ID, Input);
641       auto &NewEntry = P.first->second;
642       NewEntry.Name = ID.Name;
643       NewEntry.DWOName = ID.DWOName;
644       NewEntry.DWPName = Input;
645       for (auto Kind : CUIndex.getColumnKinds()) {
646         if (!isSupportedSectionKind(Kind))
647           continue;
648         auto &C = NewEntry.Contributions[getContributionIndex(Kind)];
649         C.Offset += I->Offset;
650         C.Length = I->Length;
651         ++I;
652       }
653     }
654 
655     if (!CurTypesSection.empty()) {
656       if (CurTypesSection.size() != 1)
657         return make_error<DWPError>("multiple type unit sections in .dwp file");
658       DWARFUnitIndex TUIndex(DW_SECT_EXT_TYPES);
659       DataExtractor TUIndexData(CurTUIndexSection, Obj.isLittleEndian(), 0);
660       if (!TUIndex.parse(TUIndexData))
661         return make_error<DWPError>("failed to parse tu_index");
662       if (TUIndex.getVersion() != 2)
663         return make_error<DWPError>(
664             "unsupported tu_index version: " + utostr(TUIndex.getVersion()) +
665             " (only version 2 is supported)");
666 
667       addAllTypesFromDWP(
668           Out, TypeIndexEntries, TUIndex, TypesSection, CurTypesSection.front(),
669           CurEntry,
670           ContributionOffsets[getContributionIndex(DW_SECT_EXT_TYPES)]);
671     }
672   }
673 
674   // Lie about there being no info contributions so the TU index only includes
675   // the type unit contribution
676   ContributionOffsets[0] = 0;
677   writeIndex(Out, MCOFI.getDwarfTUIndexSection(), ContributionOffsets,
678              TypeIndexEntries);
679 
680   // Lie about the type contribution
681   ContributionOffsets[getContributionIndex(DW_SECT_EXT_TYPES)] = 0;
682   // Unlie about the info contribution
683   ContributionOffsets[0] = 1;
684 
685   writeIndex(Out, MCOFI.getDwarfCUIndexSection(), ContributionOffsets,
686              IndexEntries);
687 
688   return Error::success();
689 }
690 
691 static int error(const Twine &Error, const Twine &Context) {
692   errs() << Twine("while processing ") + Context + ":\n";
693   errs() << Twine("error: ") + Error + "\n";
694   return 1;
695 }
696 
697 int main(int argc, char **argv) {
698   InitLLVM X(argc, argv);
699 
700   cl::ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files\n");
701 
702   llvm::InitializeAllTargetInfos();
703   llvm::InitializeAllTargetMCs();
704   llvm::InitializeAllTargets();
705   llvm::InitializeAllAsmPrinters();
706 
707   std::string ErrorStr;
708   StringRef Context = "dwarf streamer init";
709 
710   Triple TheTriple("x86_64-linux-gnu");
711 
712   // Get the target.
713   const Target *TheTarget =
714       TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
715   if (!TheTarget)
716     return error(ErrorStr, Context);
717   std::string TripleName = TheTriple.getTriple();
718 
719   // Create all the MC Objects.
720   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
721   if (!MRI)
722     return error(Twine("no register info for target ") + TripleName, Context);
723 
724   MCTargetOptions MCOptions = llvm::mc::InitMCTargetOptionsFromFlags();
725   std::unique_ptr<MCAsmInfo> MAI(
726       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
727   if (!MAI)
728     return error("no asm info for target " + TripleName, Context);
729 
730   MCObjectFileInfo MOFI;
731   MCContext MC(MAI.get(), MRI.get(), &MOFI);
732   MOFI.InitMCObjectFileInfo(TheTriple, /*PIC*/ false, MC);
733 
734   std::unique_ptr<MCSubtargetInfo> MSTI(
735       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
736   if (!MSTI)
737     return error("no subtarget info for target " + TripleName, Context);
738 
739   MCTargetOptions Options;
740   auto MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, Options);
741   if (!MAB)
742     return error("no asm backend for target " + TripleName, Context);
743 
744   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
745   if (!MII)
746     return error("no instr info info for target " + TripleName, Context);
747 
748   MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC);
749   if (!MCE)
750     return error("no code emitter for target " + TripleName, Context);
751 
752   // Create the output file.
753   std::error_code EC;
754   ToolOutputFile OutFile(OutputFilename, EC, sys::fs::OF_None);
755   Optional<buffer_ostream> BOS;
756   raw_pwrite_stream *OS;
757   if (EC)
758     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
759   if (OutFile.os().supportsSeeking()) {
760     OS = &OutFile.os();
761   } else {
762     BOS.emplace(OutFile.os());
763     OS = BOS.getPointer();
764   }
765 
766   std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
767       TheTriple, MC, std::unique_ptr<MCAsmBackend>(MAB),
768       MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(MCE), *MSTI,
769       MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
770       /*DWARFMustBeAtTheEnd*/ false));
771   if (!MS)
772     return error("no object streamer for target " + TripleName, Context);
773 
774   std::vector<std::string> DWOFilenames = InputFiles;
775   for (const auto &ExecFilename : ExecFilenames) {
776     auto DWOs = getDWOFilenames(ExecFilename);
777     if (!DWOs) {
778       logAllUnhandledErrors(DWOs.takeError(), WithColor::error());
779       return 1;
780     }
781     DWOFilenames.insert(DWOFilenames.end(),
782                         std::make_move_iterator(DWOs->begin()),
783                         std::make_move_iterator(DWOs->end()));
784   }
785 
786   if (auto Err = write(*MS, DWOFilenames)) {
787     logAllUnhandledErrors(std::move(Err), WithColor::error());
788     return 1;
789   }
790 
791   MS->Finish();
792   OutFile.keep();
793   return 0;
794 }
795