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