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