[llvm-dwp] Emit a rather fictional debug_cu_index
[oota-llvm.git] / tools / llvm-dwp / llvm-dwp.cpp
1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/ADT/StringSet.h"
3 #include "llvm/CodeGen/AsmPrinter.h"
4 #include "llvm/MC/MCAsmInfo.h"
5 #include "llvm/MC/MCContext.h"
6 #include "llvm/MC/MCInstrInfo.h"
7 #include "llvm/MC/MCObjectFileInfo.h"
8 #include "llvm/MC/MCRegisterInfo.h"
9 #include "llvm/MC/MCSectionELF.h"
10 #include "llvm/MC/MCStreamer.h"
11 #include "llvm/Object/ObjectFile.h"
12 #include "llvm/Support/DataExtractor.h"
13 #include "llvm/Support/Options.h"
14 #include "llvm/Support/FileSystem.h"
15 #include "llvm/Support/MemoryBuffer.h"
16 #include "llvm/Support/TargetRegistry.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Support/TargetSelect.h"
20 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
21 #include <memory>
22 #include <list>
23 #include <unordered_set>
24
25 using namespace llvm;
26 using namespace llvm::object;
27 using namespace cl;
28
29 OptionCategory DwpCategory("Specific Options");
30 static list<std::string> InputFiles(Positional, OneOrMore,
31                                     desc("<input files>"), cat(DwpCategory));
32
33 static opt<std::string> OutputFilename(Required, "o", desc("Specify the output file."),
34                                       value_desc("filename"), cat(DwpCategory));
35
36 static int error(const Twine &Error, const Twine &Context) {
37   errs() << Twine("while processing ") + Context + ":\n";
38   errs() << Twine("error: ") + Error + "\n";
39   return 1;
40 }
41
42 static std::error_code
43 writeStringsAndOffsets(MCStreamer &Out, StringMap<uint32_t> &Strings,
44                        uint32_t &StringOffset, MCSection *StrSection,
45                        MCSection *StrOffsetSection, StringRef CurStrSection,
46                        StringRef CurStrOffsetSection) {
47   // Could possibly produce an error or warning if one of these was non-null but
48   // the other was null.
49   if (CurStrSection.empty() || CurStrOffsetSection.empty())
50     return std::error_code();
51
52   DenseMap<uint32_t, uint32_t> OffsetRemapping;
53
54   DataExtractor Data(CurStrSection, true, 0);
55   uint32_t LocalOffset = 0;
56   uint32_t PrevOffset = 0;
57   while (const char *s = Data.getCStr(&LocalOffset)) {
58     StringRef Str(s, LocalOffset - PrevOffset - 1);
59     auto Pair = Strings.insert(std::make_pair(Str, StringOffset));
60     if (Pair.second) {
61       Out.SwitchSection(StrSection);
62       Out.EmitBytes(
63           StringRef(Pair.first->getKeyData(), Pair.first->getKeyLength() + 1));
64       StringOffset += Str.size() + 1;
65     }
66     OffsetRemapping[PrevOffset] = Pair.first->second;
67     PrevOffset = LocalOffset;
68   }
69
70   Data = DataExtractor(CurStrOffsetSection, true, 0);
71
72   Out.SwitchSection(StrOffsetSection);
73
74   uint32_t Offset = 0;
75   uint64_t Size = CurStrOffsetSection.size();
76   while (Offset < Size) {
77     auto OldOffset = Data.getU32(&Offset);
78     auto NewOffset = OffsetRemapping[OldOffset];
79     Out.EmitIntValue(NewOffset, 4);
80   }
81
82   return std::error_code();
83 }
84
85 static std::error_code write(MCStreamer &Out, ArrayRef<std::string> Inputs) {
86   const auto &MCOFI = *Out.getContext().getObjectFileInfo();
87   MCSection *const StrSection = MCOFI.getDwarfStrDWOSection();
88   MCSection *const StrOffsetSection = MCOFI.getDwarfStrOffDWOSection();
89   const StringMap<std::pair<MCSection *, DWARFSectionKind>> KnownSections = {
90       {"debug_info.dwo", {MCOFI.getDwarfInfoDWOSection(), DW_SECT_INFO}},
91       {"debug_types.dwo", {MCOFI.getDwarfTypesDWOSection(), DW_SECT_TYPES}},
92       {"debug_str_offsets.dwo", {StrOffsetSection, DW_SECT_STR_OFFSETS}},
93       {"debug_str.dwo", {StrSection, static_cast<DWARFSectionKind>(0)}},
94       {"debug_loc.dwo", {MCOFI.getDwarfLocDWOSection(), DW_SECT_LOC}},
95       {"debug_abbrev.dwo", {MCOFI.getDwarfAbbrevDWOSection(), DW_SECT_ABBREV}}};
96
97   struct UnitIndexEntry {
98     uint64_t Signature;
99     DWARFUnitIndex::Entry::SectionContribution Contributions[8];
100   };
101
102   std::vector<UnitIndexEntry> IndexEntries;
103
104   StringMap<uint32_t> Strings;
105   uint32_t StringOffset = 0;
106
107   uint64_t UnitIndex = 0;
108   uint32_t ContributionOffsets[8] = {};
109
110   for (const auto &Input : Inputs) {
111     auto ErrOrObj = object::ObjectFile::createObjectFile(Input);
112     if (!ErrOrObj)
113       return ErrOrObj.getError();
114
115     IndexEntries.emplace_back();
116     UnitIndexEntry &CurEntry = IndexEntries.back();
117     CurEntry.Signature = UnitIndex++;
118
119     StringRef CurStrSection;
120     StringRef CurStrOffsetSection;
121
122     for (const auto &Section : ErrOrObj->getBinary()->sections()) {
123       StringRef Name;
124       if (std::error_code Err = Section.getName(Name))
125         return Err;
126
127       auto SectionPair =
128           KnownSections.find(Name.substr(Name.find_first_not_of("._")));
129       if (SectionPair == KnownSections.end())
130         continue;
131
132       StringRef Contents;
133       if (auto Err = Section.getContents(Contents))
134         return Err;
135
136       if (DWARFSectionKind Kind = SectionPair->second.second) {
137         auto Index = Kind - DW_SECT_INFO;
138         CurEntry.Contributions[Index].Offset = ContributionOffsets[Index];
139         ContributionOffsets[Index] +=
140             (CurEntry.Contributions[Index].Length = Contents.size());
141       }
142
143       MCSection *OutSection = SectionPair->second.first;
144       if (OutSection == StrOffsetSection)
145         CurStrOffsetSection = Contents;
146       else if (OutSection == StrSection)
147         CurStrSection = Contents;
148       else {
149         Out.SwitchSection(OutSection);
150         Out.EmitBytes(Contents);
151       }
152     }
153
154     if (auto Err = writeStringsAndOffsets(Out, Strings, StringOffset,
155                                           StrSection, StrOffsetSection,
156                                           CurStrSection, CurStrOffsetSection))
157       return Err;
158   }
159
160   Out.SwitchSection(MCOFI.getDwarfCUIndexSection());
161   Out.EmitIntValue(2, 4);                   // Version
162   Out.EmitIntValue(8, 4);                   // Columns
163   Out.EmitIntValue(IndexEntries.size(), 4); // Num Units
164   // FIXME: This is not the right number of buckets for a real hash.
165   Out.EmitIntValue(IndexEntries.size(), 4); // Num Buckets
166
167   // Write the signatures.
168   for (const auto &E : IndexEntries)
169     Out.EmitIntValue(E.Signature, 8);
170
171   // Write the indexes.
172   for (size_t i = 0; i != IndexEntries.size(); ++i)
173     Out.EmitIntValue(i + 1, 4);
174
175   // Write the column headers (which sections will appear in the table)
176   for (size_t i = 1; i != 9; ++i)
177     Out.EmitIntValue(i, 4);
178
179   // Write the offsets.
180   for (const auto &E : IndexEntries)
181     for (const auto &C : E.Contributions)
182       Out.EmitIntValue(C.Offset, 4);
183
184   // Write the lengths.
185   for (const auto &E : IndexEntries)
186     for (const auto &C : E.Contributions)
187       Out.EmitIntValue(C.Length, 4);
188
189   return std::error_code();
190 }
191
192 int main(int argc, char** argv) {
193
194   ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files");
195
196   llvm::InitializeAllTargetInfos();
197   llvm::InitializeAllTargetMCs();
198   llvm::InitializeAllTargets();
199   llvm::InitializeAllAsmPrinters();
200
201   std::string ErrorStr;
202   StringRef Context = "dwarf streamer init";
203
204   Triple TheTriple("x86_64-linux-gnu");
205
206   // Get the target.
207   const Target *TheTarget =
208       TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
209   if (!TheTarget)
210     return error(ErrorStr, Context);
211   std::string TripleName = TheTriple.getTriple();
212
213   // Create all the MC Objects.
214   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
215   if (!MRI)
216     return error(Twine("no register info for target ") + TripleName, Context);
217
218   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
219   if (!MAI)
220     return error("no asm info for target " + TripleName, Context);
221
222   MCObjectFileInfo MOFI;
223   MCContext MC(MAI.get(), MRI.get(), &MOFI);
224   MOFI.InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
225                              MC);
226
227   auto MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
228   if (!MAB)
229     return error("no asm backend for target " + TripleName, Context);
230
231   std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
232   if (!MII)
233     return error("no instr info info for target " + TripleName, Context);
234
235   std::unique_ptr<MCSubtargetInfo> MSTI(
236       TheTarget->createMCSubtargetInfo(TripleName, "", ""));
237   if (!MSTI)
238     return error("no subtarget info for target " + TripleName, Context);
239
240   MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC);
241   if (!MCE)
242     return error("no code emitter for target " + TripleName, Context);
243
244   // Create the output file.
245   std::error_code EC;
246   raw_fd_ostream OutFile(OutputFilename, EC, sys::fs::F_None);
247   if (EC)
248     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
249
250   std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
251       TheTriple, MC, *MAB, OutFile, MCE, *MSTI, false,
252       /*DWARFMustBeAtTheEnd*/ false));
253   if (!MS)
254     return error("no object streamer for target " + TripleName, Context);
255
256   if (auto Err = write(*MS, InputFiles))
257     return error(Err.message(), "Writing DWP file");
258
259   MS->Finish();
260 }