608eca152d94fb3297acced0db86d9b80a718b44
[oota-llvm.git] / tools / llvm-dwp / llvm-dwp.cpp
1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/ADT/StringSet.h"
3 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
4 #include "llvm/CodeGen/AsmPrinter.h"
5 #include "llvm/MC/MCAsmInfo.h"
6 #include "llvm/MC/MCContext.h"
7 #include "llvm/MC/MCInstrInfo.h"
8 #include "llvm/MC/MCObjectFileInfo.h"
9 #include "llvm/MC/MCRegisterInfo.h"
10 #include "llvm/MC/MCSectionELF.h"
11 #include "llvm/MC/MCStreamer.h"
12 #include "llvm/Object/ObjectFile.h"
13 #include "llvm/Support/DataExtractor.h"
14 #include "llvm/Support/Options.h"
15 #include "llvm/Support/FileSystem.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "llvm/Support/TargetRegistry.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Support/TargetSelect.h"
21 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
22 #include "llvm/Support/MathExtras.h"
23 #include <memory>
24 #include <list>
25 #include <unordered_set>
26
27 using namespace llvm;
28 using namespace llvm::object;
29 using namespace cl;
30
31 OptionCategory DwpCategory("Specific Options");
32 static list<std::string> InputFiles(Positional, OneOrMore,
33                                     desc("<input files>"), cat(DwpCategory));
34
35 static opt<std::string> OutputFilename(Required, "o", desc("Specify the output file."),
36                                       value_desc("filename"), cat(DwpCategory));
37
38 static int error(const Twine &Error, const Twine &Context) {
39   errs() << Twine("while processing ") + Context + ":\n";
40   errs() << Twine("error: ") + Error + "\n";
41   return 1;
42 }
43
44 static std::error_code
45 writeStringsAndOffsets(MCStreamer &Out, StringMap<uint32_t> &Strings,
46                        uint32_t &StringOffset, MCSection *StrSection,
47                        MCSection *StrOffsetSection, StringRef CurStrSection,
48                        StringRef CurStrOffsetSection) {
49   // Could possibly produce an error or warning if one of these was non-null but
50   // the other was null.
51   if (CurStrSection.empty() || CurStrOffsetSection.empty())
52     return std::error_code();
53
54   DenseMap<uint32_t, uint32_t> OffsetRemapping;
55
56   DataExtractor Data(CurStrSection, true, 0);
57   uint32_t LocalOffset = 0;
58   uint32_t PrevOffset = 0;
59   while (const char *s = Data.getCStr(&LocalOffset)) {
60     StringRef Str(s, LocalOffset - PrevOffset - 1);
61     auto Pair = Strings.insert(std::make_pair(Str, StringOffset));
62     if (Pair.second) {
63       Out.SwitchSection(StrSection);
64       Out.EmitBytes(
65           StringRef(Pair.first->getKeyData(), Pair.first->getKeyLength() + 1));
66       StringOffset += Str.size() + 1;
67     }
68     OffsetRemapping[PrevOffset] = Pair.first->second;
69     PrevOffset = LocalOffset;
70   }
71
72   Data = DataExtractor(CurStrOffsetSection, true, 0);
73
74   Out.SwitchSection(StrOffsetSection);
75
76   uint32_t Offset = 0;
77   uint64_t Size = CurStrOffsetSection.size();
78   while (Offset < Size) {
79     auto OldOffset = Data.getU32(&Offset);
80     auto NewOffset = OffsetRemapping[OldOffset];
81     Out.EmitIntValue(NewOffset, 4);
82   }
83
84   return std::error_code();
85 }
86
87 static uint32_t getCUAbbrev(StringRef Abbrev, uint64_t AbbrCode) {
88   uint64_t CurCode;
89   uint32_t Offset = 0;
90   DataExtractor AbbrevData(Abbrev, true, 0);
91   while ((CurCode = AbbrevData.getULEB128(&Offset)) != AbbrCode) {
92     // Tag
93     AbbrevData.getULEB128(&Offset);
94     // DW_CHILDREN
95     AbbrevData.getU8(&Offset);
96     // Attributes
97     while (AbbrevData.getULEB128(&Offset) | AbbrevData.getULEB128(&Offset))
98       ;
99   }
100   return Offset;
101 }
102
103 static uint64_t getCUSignature(StringRef Abbrev, StringRef Info) {
104   uint32_t Offset = 0;
105   DataExtractor InfoData(Info, true, 0);
106   InfoData.getU32(&Offset); // Length
107   uint16_t Version = InfoData.getU16(&Offset);
108   InfoData.getU32(&Offset); // Abbrev offset (should be zero)
109   uint8_t AddrSize = InfoData.getU8(&Offset);
110
111   uint32_t AbbrCode = InfoData.getULEB128(&Offset);
112
113   DataExtractor AbbrevData(Abbrev, true, 0);
114   uint32_t AbbrevOffset = getCUAbbrev(Abbrev, AbbrCode);
115   uint64_t Tag = AbbrevData.getULEB128(&AbbrevOffset);
116   (void)Tag;
117   // FIXME: Real error handling
118   assert(Tag == dwarf::DW_TAG_compile_unit);
119   // DW_CHILDREN
120   AbbrevData.getU8(&AbbrevOffset);
121   uint32_t Name;
122   uint32_t Form;
123   while ((Name = AbbrevData.getULEB128(&AbbrevOffset)) |
124              (Form = AbbrevData.getULEB128(&AbbrevOffset)) &&
125          Name != dwarf::DW_AT_GNU_dwo_id) {
126     DWARFFormValue::skipValue(Form, InfoData, &Offset, Version, AddrSize);
127   }
128   // FIXME: Real error handling
129   assert(Name == dwarf::DW_AT_GNU_dwo_id);
130   return InfoData.getU64(&Offset);
131 }
132
133 struct UnitIndexEntry {
134   uint64_t Signature;
135   DWARFUnitIndex::Entry::SectionContribution Contributions[8];
136 };
137
138 static void addAllTypes(std::vector<UnitIndexEntry> &TypeIndexEntries,
139                         uint32_t OutTypesOffset, StringRef Types,
140                         const UnitIndexEntry &CUEntry) {
141   uint32_t Offset = 0;
142   DataExtractor Data(Types, true, 0);
143   while (Data.isValidOffset(Offset)) {
144     TypeIndexEntries.push_back(CUEntry);
145     auto &Entry = TypeIndexEntries.back();
146     // Zero out the debug_info contribution
147     Entry.Contributions[0] = {};
148     auto &C = Entry.Contributions[DW_SECT_TYPES - DW_SECT_INFO];
149     C.Offset = OutTypesOffset + Offset;
150     auto PrevOffset = Offset;
151     // Length of the unit, including the 4 byte length field.
152     C.Length = Data.getU32(&Offset) + 4;
153
154     Data.getU16(&Offset); // Version
155     Data.getU32(&Offset); // Abbrev offset
156     Data.getU8(&Offset);  // Address size
157     Entry.Signature = Data.getU64(&Offset);
158     Offset = PrevOffset + C.Length;
159   }
160 }
161
162 static void
163 writeIndexTable(MCStreamer &Out, ArrayRef<unsigned> ContributionOffsets,
164                 ArrayRef<UnitIndexEntry> IndexEntries,
165                 uint32_t DWARFUnitIndex::Entry::SectionContribution::*Field) {
166   for (const auto &E : IndexEntries)
167     for (size_t i = 0; i != array_lengthof(E.Contributions); ++i)
168       if (ContributionOffsets[i])
169         Out.EmitIntValue(E.Contributions[i].*Field, 4);
170 }
171
172 static void writeIndex(MCStreamer &Out, MCSection *Section,
173                        ArrayRef<unsigned> ContributionOffsets,
174                        ArrayRef<UnitIndexEntry> IndexEntries) {
175   unsigned Columns = 0;
176   for (auto &C : ContributionOffsets)
177     if (C)
178       ++Columns;
179
180   std::vector<unsigned> Buckets(NextPowerOf2(3 * IndexEntries.size() / 2));
181   uint64_t Mask = Buckets.size() - 1;
182   for (size_t i = 0; i != IndexEntries.size(); ++i) {
183     auto S = IndexEntries[i].Signature;
184     auto H = S & Mask;
185     while (Buckets[H])
186       H += ((S >> 32) & Mask) | 1;
187     Buckets[H] = i + 1;
188   }
189
190   Out.SwitchSection(Section);
191   Out.EmitIntValue(2, 4);                   // Version
192   Out.EmitIntValue(Columns, 4);             // Columns
193   Out.EmitIntValue(IndexEntries.size(), 4); // Num Units
194   Out.EmitIntValue(Buckets.size(), 4); // Num Buckets
195
196   // Write the signatures.
197   for (const auto &I : Buckets)
198     Out.EmitIntValue(I ? IndexEntries[I - 1].Signature : 0, 8);
199
200   // Write the indexes.
201   for (const auto &I : Buckets)
202     Out.EmitIntValue(I, 4);
203
204   // Write the column headers (which sections will appear in the table)
205   for (size_t i = 0; i != ContributionOffsets.size(); ++i)
206     if (ContributionOffsets[i])
207       Out.EmitIntValue(i + DW_SECT_INFO, 4);
208
209   // Write the offsets.
210   writeIndexTable(Out, ContributionOffsets, IndexEntries,
211                   &DWARFUnitIndex::Entry::SectionContribution::Offset);
212
213   // Write the lengths.
214   writeIndexTable(Out, ContributionOffsets, IndexEntries,
215                   &DWARFUnitIndex::Entry::SectionContribution::Length);
216 }
217 static std::error_code write(MCStreamer &Out, ArrayRef<std::string> Inputs) {
218   const auto &MCOFI = *Out.getContext().getObjectFileInfo();
219   MCSection *const StrSection = MCOFI.getDwarfStrDWOSection();
220   MCSection *const StrOffsetSection = MCOFI.getDwarfStrOffDWOSection();
221   const StringMap<std::pair<MCSection *, DWARFSectionKind>> KnownSections = {
222       {"debug_info.dwo", {MCOFI.getDwarfInfoDWOSection(), DW_SECT_INFO}},
223       {"debug_types.dwo", {MCOFI.getDwarfTypesDWOSection(), DW_SECT_TYPES}},
224       {"debug_str_offsets.dwo", {StrOffsetSection, DW_SECT_STR_OFFSETS}},
225       {"debug_str.dwo", {StrSection, static_cast<DWARFSectionKind>(0)}},
226       {"debug_loc.dwo", {MCOFI.getDwarfLocDWOSection(), DW_SECT_LOC}},
227       {"debug_line.dwo", {MCOFI.getDwarfLineDWOSection(), DW_SECT_LINE}},
228       {"debug_abbrev.dwo", {MCOFI.getDwarfAbbrevDWOSection(), DW_SECT_ABBREV}}};
229
230   std::vector<UnitIndexEntry> IndexEntries;
231   std::vector<UnitIndexEntry> TypeIndexEntries;
232
233   StringMap<uint32_t> Strings;
234   uint32_t StringOffset = 0;
235
236   uint32_t ContributionOffsets[8] = {};
237
238   for (const auto &Input : Inputs) {
239     auto ErrOrObj = object::ObjectFile::createObjectFile(Input);
240     if (!ErrOrObj)
241       return ErrOrObj.getError();
242
243     IndexEntries.emplace_back();
244     UnitIndexEntry &CurEntry = IndexEntries.back();
245
246     StringRef CurStrSection;
247     StringRef CurStrOffsetSection;
248     StringRef InfoSection;
249     StringRef AbbrevSection;
250     StringRef TypesSection;
251
252     auto TypesOffset = ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO];
253
254     for (const auto &Section : ErrOrObj->getBinary()->sections()) {
255       StringRef Name;
256       if (std::error_code Err = Section.getName(Name))
257         return Err;
258
259       auto SectionPair =
260           KnownSections.find(Name.substr(Name.find_first_not_of("._")));
261       if (SectionPair == KnownSections.end())
262         continue;
263
264       StringRef Contents;
265       if (auto Err = Section.getContents(Contents))
266         return Err;
267
268       if (DWARFSectionKind Kind = SectionPair->second.second) {
269         auto Index = Kind - DW_SECT_INFO;
270         CurEntry.Contributions[Index].Offset = ContributionOffsets[Index];
271         ContributionOffsets[Index] +=
272             (CurEntry.Contributions[Index].Length = Contents.size());
273
274         switch (Kind) {
275         case DW_SECT_INFO:
276           InfoSection = Contents;
277           break;
278         case DW_SECT_ABBREV:
279           AbbrevSection = Contents;
280           break;
281         case DW_SECT_TYPES:
282           TypesSection = Contents;
283           break;
284         default:
285           break;
286         }
287       }
288
289       MCSection *OutSection = SectionPair->second.first;
290       if (OutSection == StrOffsetSection)
291         CurStrOffsetSection = Contents;
292       else if (OutSection == StrSection)
293         CurStrSection = Contents;
294       else {
295         Out.SwitchSection(OutSection);
296         Out.EmitBytes(Contents);
297       }
298     }
299
300     assert(!AbbrevSection.empty());
301     assert(!InfoSection.empty());
302     CurEntry.Signature = getCUSignature(AbbrevSection, InfoSection);
303     addAllTypes(TypeIndexEntries, TypesOffset, TypesSection, CurEntry);
304
305     if (auto Err = writeStringsAndOffsets(Out, Strings, StringOffset,
306                                           StrSection, StrOffsetSection,
307                                           CurStrSection, CurStrOffsetSection))
308       return Err;
309   }
310
311   // Lie about there being no info contributions so the TU index only includes
312   // the type unit contribution
313   ContributionOffsets[0] = 0;
314   writeIndex(Out, MCOFI.getDwarfTUIndexSection(), ContributionOffsets,
315              TypeIndexEntries);
316
317   // Lie about the type contribution
318   ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO] = 0;
319   // Unlie about the info contribution
320   ContributionOffsets[0] = 1;
321
322   writeIndex(Out, MCOFI.getDwarfCUIndexSection(), ContributionOffsets,
323              IndexEntries);
324
325   return std::error_code();
326 }
327
328 int main(int argc, char** argv) {
329
330   ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files");
331
332   llvm::InitializeAllTargetInfos();
333   llvm::InitializeAllTargetMCs();
334   llvm::InitializeAllTargets();
335   llvm::InitializeAllAsmPrinters();
336
337   std::string ErrorStr;
338   StringRef Context = "dwarf streamer init";
339
340   Triple TheTriple("x86_64-linux-gnu");
341
342   // Get the target.
343   const Target *TheTarget =
344       TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
345   if (!TheTarget)
346     return error(ErrorStr, Context);
347   std::string TripleName = TheTriple.getTriple();
348
349   // Create all the MC Objects.
350   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
351   if (!MRI)
352     return error(Twine("no register info for target ") + TripleName, Context);
353
354   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
355   if (!MAI)
356     return error("no asm info for target " + TripleName, Context);
357
358   MCObjectFileInfo MOFI;
359   MCContext MC(MAI.get(), MRI.get(), &MOFI);
360   MOFI.InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
361                              MC);
362
363   auto MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
364   if (!MAB)
365     return error("no asm backend for target " + TripleName, Context);
366
367   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
368   if (!MII)
369     return error("no instr info info for target " + TripleName, Context);
370
371   std::unique_ptr<MCSubtargetInfo> MSTI(
372       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
373   if (!MSTI)
374     return error("no subtarget info for target " + TripleName, Context);
375
376   MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC);
377   if (!MCE)
378     return error("no code emitter for target " + TripleName, Context);
379
380   // Create the output file.
381   std::error_code EC;
382   raw_fd_ostream OutFile(OutputFilename, EC, sys::fs::F_None);
383   if (EC)
384     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
385
386   std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
387       TheTriple, MC, *MAB, OutFile, MCE, *MSTI, false,
388       /*DWARFMustBeAtTheEnd*/ false));
389   if (!MS)
390     return error("no object streamer for target " + TripleName, Context);
391
392   if (auto Err = write(*MS, InputFiles))
393     return error(Err.message(), "Writing DWP file");
394
395   MS->Finish();
396 }