[llvm-dwp] Retrieve the DWOID from the CU for the cu_index entry
[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 <memory>
23 #include <list>
24 #include <unordered_set>
25
26 using namespace llvm;
27 using namespace llvm::object;
28 using namespace cl;
29
30 OptionCategory DwpCategory("Specific Options");
31 static list<std::string> InputFiles(Positional, OneOrMore,
32                                     desc("<input files>"), cat(DwpCategory));
33
34 static opt<std::string> OutputFilename(Required, "o", desc("Specify the output file."),
35                                       value_desc("filename"), cat(DwpCategory));
36
37 static int error(const Twine &Error, const Twine &Context) {
38   errs() << Twine("while processing ") + Context + ":\n";
39   errs() << Twine("error: ") + Error + "\n";
40   return 1;
41 }
42
43 static std::error_code
44 writeStringsAndOffsets(MCStreamer &Out, StringMap<uint32_t> &Strings,
45                        uint32_t &StringOffset, MCSection *StrSection,
46                        MCSection *StrOffsetSection, StringRef CurStrSection,
47                        StringRef CurStrOffsetSection) {
48   // Could possibly produce an error or warning if one of these was non-null but
49   // the other was null.
50   if (CurStrSection.empty() || CurStrOffsetSection.empty())
51     return std::error_code();
52
53   DenseMap<uint32_t, uint32_t> OffsetRemapping;
54
55   DataExtractor Data(CurStrSection, true, 0);
56   uint32_t LocalOffset = 0;
57   uint32_t PrevOffset = 0;
58   while (const char *s = Data.getCStr(&LocalOffset)) {
59     StringRef Str(s, LocalOffset - PrevOffset - 1);
60     auto Pair = Strings.insert(std::make_pair(Str, StringOffset));
61     if (Pair.second) {
62       Out.SwitchSection(StrSection);
63       Out.EmitBytes(
64           StringRef(Pair.first->getKeyData(), Pair.first->getKeyLength() + 1));
65       StringOffset += Str.size() + 1;
66     }
67     OffsetRemapping[PrevOffset] = Pair.first->second;
68     PrevOffset = LocalOffset;
69   }
70
71   Data = DataExtractor(CurStrOffsetSection, true, 0);
72
73   Out.SwitchSection(StrOffsetSection);
74
75   uint32_t Offset = 0;
76   uint64_t Size = CurStrOffsetSection.size();
77   while (Offset < Size) {
78     auto OldOffset = Data.getU32(&Offset);
79     auto NewOffset = OffsetRemapping[OldOffset];
80     Out.EmitIntValue(NewOffset, 4);
81   }
82
83   return std::error_code();
84 }
85
86 static uint32_t getCUAbbrev(StringRef Abbrev, uint64_t AbbrCode) {
87   uint64_t CurCode;
88   uint32_t Offset = 0;
89   DataExtractor AbbrevData(Abbrev, true, 0);
90   while ((CurCode = AbbrevData.getULEB128(&Offset)) != AbbrCode) {
91     // Tag
92     AbbrevData.getULEB128(&Offset);
93     // DW_CHILDREN
94     AbbrevData.getU8(&Offset);
95     // Attributes
96     while (AbbrevData.getULEB128(&Offset) | AbbrevData.getULEB128(&Offset))
97       ;
98   }
99   return Offset;
100 }
101
102 static uint64_t getCUSignature(StringRef Abbrev, StringRef Info) {
103   uint32_t Offset = 0;
104   DataExtractor InfoData(Info, true, 0);
105   InfoData.getU32(&Offset); // Length
106   uint16_t Version = InfoData.getU16(&Offset);
107   InfoData.getU32(&Offset); // Abbrev offset (should be zero)
108   uint8_t AddrSize = InfoData.getU8(&Offset);
109
110   uint32_t AbbrCode = InfoData.getULEB128(&Offset);
111
112   DataExtractor AbbrevData(Abbrev, true, 0);
113   uint32_t AbbrevOffset = getCUAbbrev(Abbrev, AbbrCode);
114   uint64_t Tag = AbbrevData.getULEB128(&AbbrevOffset);
115   (void)Tag;
116   // FIXME: Real error handling
117   assert(Tag == dwarf::DW_TAG_compile_unit);
118   // DW_CHILDREN
119   AbbrevData.getU8(&AbbrevOffset);
120   uint32_t Name;
121   uint32_t Form;
122   while ((Name = AbbrevData.getULEB128(&AbbrevOffset)) |
123              (Form = AbbrevData.getULEB128(&AbbrevOffset)) &&
124          Name != dwarf::DW_AT_GNU_dwo_id) {
125     DWARFFormValue::skipValue(Form, InfoData, &Offset, Version, AddrSize);
126   }
127   // FIXME: Real error handling
128   assert(Name == dwarf::DW_AT_GNU_dwo_id);
129   return InfoData.getU64(&Offset);
130 }
131
132 static std::error_code write(MCStreamer &Out, ArrayRef<std::string> Inputs) {
133   const auto &MCOFI = *Out.getContext().getObjectFileInfo();
134   MCSection *const StrSection = MCOFI.getDwarfStrDWOSection();
135   MCSection *const StrOffsetSection = MCOFI.getDwarfStrOffDWOSection();
136   const StringMap<std::pair<MCSection *, DWARFSectionKind>> KnownSections = {
137       {"debug_info.dwo", {MCOFI.getDwarfInfoDWOSection(), DW_SECT_INFO}},
138       {"debug_types.dwo", {MCOFI.getDwarfTypesDWOSection(), DW_SECT_TYPES}},
139       {"debug_str_offsets.dwo", {StrOffsetSection, DW_SECT_STR_OFFSETS}},
140       {"debug_str.dwo", {StrSection, static_cast<DWARFSectionKind>(0)}},
141       {"debug_loc.dwo", {MCOFI.getDwarfLocDWOSection(), DW_SECT_LOC}},
142       {"debug_abbrev.dwo", {MCOFI.getDwarfAbbrevDWOSection(), DW_SECT_ABBREV}}};
143
144   struct UnitIndexEntry {
145     uint64_t Signature;
146     DWARFUnitIndex::Entry::SectionContribution Contributions[8];
147   };
148
149   std::vector<UnitIndexEntry> IndexEntries;
150
151   StringMap<uint32_t> Strings;
152   uint32_t StringOffset = 0;
153
154   uint32_t ContributionOffsets[8] = {};
155
156   for (const auto &Input : Inputs) {
157     auto ErrOrObj = object::ObjectFile::createObjectFile(Input);
158     if (!ErrOrObj)
159       return ErrOrObj.getError();
160
161     IndexEntries.emplace_back();
162     UnitIndexEntry &CurEntry = IndexEntries.back();
163
164     StringRef CurStrSection;
165     StringRef CurStrOffsetSection;
166     StringRef InfoSection;
167     StringRef AbbrevSection;
168
169     for (const auto &Section : ErrOrObj->getBinary()->sections()) {
170       StringRef Name;
171       if (std::error_code Err = Section.getName(Name))
172         return Err;
173
174       auto SectionPair =
175           KnownSections.find(Name.substr(Name.find_first_not_of("._")));
176       if (SectionPair == KnownSections.end())
177         continue;
178
179       StringRef Contents;
180       if (auto Err = Section.getContents(Contents))
181         return Err;
182
183       if (DWARFSectionKind Kind = SectionPair->second.second) {
184         auto Index = Kind - DW_SECT_INFO;
185         CurEntry.Contributions[Index].Offset = ContributionOffsets[Index];
186         ContributionOffsets[Index] +=
187             (CurEntry.Contributions[Index].Length = Contents.size());
188
189         if (Kind == DW_SECT_INFO) {
190           assert(InfoSection.empty());
191           InfoSection = Contents;
192         } else if (Kind == DW_SECT_ABBREV) {
193           assert(AbbrevSection.empty());
194           AbbrevSection = Contents;
195         }
196       }
197
198       MCSection *OutSection = SectionPair->second.first;
199       if (OutSection == StrOffsetSection)
200         CurStrOffsetSection = Contents;
201       else if (OutSection == StrSection)
202         CurStrSection = Contents;
203       else {
204         Out.SwitchSection(OutSection);
205         Out.EmitBytes(Contents);
206       }
207     }
208
209     assert(!AbbrevSection.empty());
210     assert(!InfoSection.empty());
211     CurEntry.Signature = getCUSignature(AbbrevSection, InfoSection);
212
213     if (auto Err = writeStringsAndOffsets(Out, Strings, StringOffset,
214                                           StrSection, StrOffsetSection,
215                                           CurStrSection, CurStrOffsetSection))
216       return Err;
217   }
218
219   unsigned Columns = 0;
220   for (auto &C : ContributionOffsets)
221     if (C)
222       ++Columns;
223
224   Out.SwitchSection(MCOFI.getDwarfCUIndexSection());
225   Out.EmitIntValue(2, 4);                   // Version
226   Out.EmitIntValue(Columns, 4);             // Columns
227   Out.EmitIntValue(IndexEntries.size(), 4); // Num Units
228   // FIXME: This is not the right number of buckets for a real hash.
229   Out.EmitIntValue(IndexEntries.size(), 4); // Num Buckets
230
231   // Write the signatures.
232   for (const auto &E : IndexEntries)
233     Out.EmitIntValue(E.Signature, 8);
234
235   // Write the indexes.
236   for (size_t i = 0; i != IndexEntries.size(); ++i)
237     Out.EmitIntValue(i + 1, 4);
238
239   // Write the column headers (which sections will appear in the table)
240   for (size_t i = 0; i != array_lengthof(ContributionOffsets); ++i)
241     if (ContributionOffsets[i])
242       Out.EmitIntValue(i + DW_SECT_INFO, 4);
243
244   // Write the offsets.
245   for (const auto &E : IndexEntries)
246     for (size_t i = 0; i != array_lengthof(E.Contributions); ++i)
247       if (ContributionOffsets[i])
248         Out.EmitIntValue(E.Contributions[i].Offset, 4);
249
250   // Write the lengths.
251   for (const auto &E : IndexEntries)
252     for (size_t i = 0; i != array_lengthof(E.Contributions); ++i)
253       if (ContributionOffsets[i])
254         Out.EmitIntValue(E.Contributions[i].Length, 4);
255
256   return std::error_code();
257 }
258
259 int main(int argc, char** argv) {
260
261   ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files");
262
263   llvm::InitializeAllTargetInfos();
264   llvm::InitializeAllTargetMCs();
265   llvm::InitializeAllTargets();
266   llvm::InitializeAllAsmPrinters();
267
268   std::string ErrorStr;
269   StringRef Context = "dwarf streamer init";
270
271   Triple TheTriple("x86_64-linux-gnu");
272
273   // Get the target.
274   const Target *TheTarget =
275       TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
276   if (!TheTarget)
277     return error(ErrorStr, Context);
278   std::string TripleName = TheTriple.getTriple();
279
280   // Create all the MC Objects.
281   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
282   if (!MRI)
283     return error(Twine("no register info for target ") + TripleName, Context);
284
285   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
286   if (!MAI)
287     return error("no asm info for target " + TripleName, Context);
288
289   MCObjectFileInfo MOFI;
290   MCContext MC(MAI.get(), MRI.get(), &MOFI);
291   MOFI.InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
292                              MC);
293
294   auto MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
295   if (!MAB)
296     return error("no asm backend for target " + TripleName, Context);
297
298   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
299   if (!MII)
300     return error("no instr info info for target " + TripleName, Context);
301
302   std::unique_ptr<MCSubtargetInfo> MSTI(
303       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
304   if (!MSTI)
305     return error("no subtarget info for target " + TripleName, Context);
306
307   MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC);
308   if (!MCE)
309     return error("no code emitter for target " + TripleName, Context);
310
311   // Create the output file.
312   std::error_code EC;
313   raw_fd_ostream OutFile(OutputFilename, EC, sys::fs::F_None);
314   if (EC)
315     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
316
317   std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
318       TheTriple, MC, *MAB, OutFile, MCE, *MSTI, false,
319       /*DWARFMustBeAtTheEnd*/ false));
320   if (!MS)
321     return error("no object streamer for target " + TripleName, Context);
322
323   if (auto Err = write(*MS, InputFiles))
324     return error(Err.message(), "Writing DWP file");
325
326   MS->Finish();
327 }