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"
25 #include <unordered_set>
28 using namespace llvm::object;
31 OptionCategory DwpCategory("Specific Options");
32 static list<std::string> InputFiles(Positional, OneOrMore,
33 desc("<input files>"), cat(DwpCategory));
35 static opt<std::string> OutputFilename(Required, "o", desc("Specify the output file."),
36 value_desc("filename"), cat(DwpCategory));
38 static int error(const Twine &Error, const Twine &Context) {
39 errs() << Twine("while processing ") + Context + ":\n";
40 errs() << Twine("error: ") + Error + "\n";
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();
54 DenseMap<uint32_t, uint32_t> OffsetRemapping;
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));
63 Out.SwitchSection(StrSection);
65 StringRef(Pair.first->getKeyData(), Pair.first->getKeyLength() + 1));
66 StringOffset += Str.size() + 1;
68 OffsetRemapping[PrevOffset] = Pair.first->second;
69 PrevOffset = LocalOffset;
72 Data = DataExtractor(CurStrOffsetSection, true, 0);
74 Out.SwitchSection(StrOffsetSection);
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);
84 return std::error_code();
87 static uint32_t getCUAbbrev(StringRef Abbrev, uint64_t AbbrCode) {
90 DataExtractor AbbrevData(Abbrev, true, 0);
91 while ((CurCode = AbbrevData.getULEB128(&Offset)) != AbbrCode) {
93 AbbrevData.getULEB128(&Offset);
95 AbbrevData.getU8(&Offset);
97 while (AbbrevData.getULEB128(&Offset) | AbbrevData.getULEB128(&Offset))
103 static uint64_t getCUSignature(StringRef Abbrev, StringRef Info) {
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);
111 uint32_t AbbrCode = InfoData.getULEB128(&Offset);
113 DataExtractor AbbrevData(Abbrev, true, 0);
114 uint32_t AbbrevOffset = getCUAbbrev(Abbrev, AbbrCode);
115 uint64_t Tag = AbbrevData.getULEB128(&AbbrevOffset);
117 // FIXME: Real error handling
118 assert(Tag == dwarf::DW_TAG_compile_unit);
120 AbbrevData.getU8(&AbbrevOffset);
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);
128 // FIXME: Real error handling
129 assert(Name == dwarf::DW_AT_GNU_dwo_id);
130 return InfoData.getU64(&Offset);
133 static std::error_code write(MCStreamer &Out, ArrayRef<std::string> Inputs) {
134 const auto &MCOFI = *Out.getContext().getObjectFileInfo();
135 MCSection *const StrSection = MCOFI.getDwarfStrDWOSection();
136 MCSection *const StrOffsetSection = MCOFI.getDwarfStrOffDWOSection();
137 const StringMap<std::pair<MCSection *, DWARFSectionKind>> KnownSections = {
138 {"debug_info.dwo", {MCOFI.getDwarfInfoDWOSection(), DW_SECT_INFO}},
139 {"debug_types.dwo", {MCOFI.getDwarfTypesDWOSection(), DW_SECT_TYPES}},
140 {"debug_str_offsets.dwo", {StrOffsetSection, DW_SECT_STR_OFFSETS}},
141 {"debug_str.dwo", {StrSection, static_cast<DWARFSectionKind>(0)}},
142 {"debug_loc.dwo", {MCOFI.getDwarfLocDWOSection(), DW_SECT_LOC}},
143 {"debug_line.dwo", {MCOFI.getDwarfLineDWOSection(), DW_SECT_LINE}},
144 {"debug_abbrev.dwo", {MCOFI.getDwarfAbbrevDWOSection(), DW_SECT_ABBREV}}};
146 struct UnitIndexEntry {
148 DWARFUnitIndex::Entry::SectionContribution Contributions[8];
151 std::vector<UnitIndexEntry> IndexEntries;
153 StringMap<uint32_t> Strings;
154 uint32_t StringOffset = 0;
156 uint32_t ContributionOffsets[8] = {};
158 for (const auto &Input : Inputs) {
159 auto ErrOrObj = object::ObjectFile::createObjectFile(Input);
161 return ErrOrObj.getError();
163 IndexEntries.emplace_back();
164 UnitIndexEntry &CurEntry = IndexEntries.back();
166 StringRef CurStrSection;
167 StringRef CurStrOffsetSection;
168 StringRef InfoSection;
169 StringRef AbbrevSection;
171 for (const auto &Section : ErrOrObj->getBinary()->sections()) {
173 if (std::error_code Err = Section.getName(Name))
177 KnownSections.find(Name.substr(Name.find_first_not_of("._")));
178 if (SectionPair == KnownSections.end())
182 if (auto Err = Section.getContents(Contents))
185 if (DWARFSectionKind Kind = SectionPair->second.second) {
186 auto Index = Kind - DW_SECT_INFO;
187 CurEntry.Contributions[Index].Offset = ContributionOffsets[Index];
188 ContributionOffsets[Index] +=
189 (CurEntry.Contributions[Index].Length = Contents.size());
191 if (Kind == DW_SECT_INFO) {
192 assert(InfoSection.empty());
193 InfoSection = Contents;
194 } else if (Kind == DW_SECT_ABBREV) {
195 assert(AbbrevSection.empty());
196 AbbrevSection = Contents;
200 MCSection *OutSection = SectionPair->second.first;
201 if (OutSection == StrOffsetSection)
202 CurStrOffsetSection = Contents;
203 else if (OutSection == StrSection)
204 CurStrSection = Contents;
206 Out.SwitchSection(OutSection);
207 Out.EmitBytes(Contents);
211 assert(!AbbrevSection.empty());
212 assert(!InfoSection.empty());
213 CurEntry.Signature = getCUSignature(AbbrevSection, InfoSection);
215 if (auto Err = writeStringsAndOffsets(Out, Strings, StringOffset,
216 StrSection, StrOffsetSection,
217 CurStrSection, CurStrOffsetSection))
221 unsigned Columns = 0;
222 for (auto &C : ContributionOffsets)
226 std::vector<unsigned> Buckets(NextPowerOf2(3 * IndexEntries.size() / 2));
227 uint64_t Mask = Buckets.size() - 1;
228 for (size_t i = 0; i != IndexEntries.size(); ++i) {
229 auto S = IndexEntries[i].Signature;
232 H += ((S >> 32) & Mask) | 1;
236 Out.SwitchSection(MCOFI.getDwarfCUIndexSection());
237 Out.EmitIntValue(2, 4); // Version
238 Out.EmitIntValue(Columns, 4); // Columns
239 Out.EmitIntValue(IndexEntries.size(), 4); // Num Units
240 // FIXME: This is not the right number of buckets for a real hash.
241 Out.EmitIntValue(Buckets.size(), 4); // Num Buckets
243 // Write the signatures.
244 for (const auto &I : Buckets)
245 Out.EmitIntValue(I ? IndexEntries[I - 1].Signature : 0, 8);
247 // Write the indexes.
248 for (const auto &I : Buckets)
249 Out.EmitIntValue(I, 4);
251 // Write the column headers (which sections will appear in the table)
252 for (size_t i = 0; i != array_lengthof(ContributionOffsets); ++i)
253 if (ContributionOffsets[i])
254 Out.EmitIntValue(i + DW_SECT_INFO, 4);
256 // Write the offsets.
257 for (const auto &E : IndexEntries)
258 for (size_t i = 0; i != array_lengthof(E.Contributions); ++i)
259 if (ContributionOffsets[i])
260 Out.EmitIntValue(E.Contributions[i].Offset, 4);
262 // Write the lengths.
263 for (const auto &E : IndexEntries)
264 for (size_t i = 0; i != array_lengthof(E.Contributions); ++i)
265 if (ContributionOffsets[i])
266 Out.EmitIntValue(E.Contributions[i].Length, 4);
268 return std::error_code();
271 int main(int argc, char** argv) {
273 ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files");
275 llvm::InitializeAllTargetInfos();
276 llvm::InitializeAllTargetMCs();
277 llvm::InitializeAllTargets();
278 llvm::InitializeAllAsmPrinters();
280 std::string ErrorStr;
281 StringRef Context = "dwarf streamer init";
283 Triple TheTriple("x86_64-linux-gnu");
286 const Target *TheTarget =
287 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
289 return error(ErrorStr, Context);
290 std::string TripleName = TheTriple.getTriple();
292 // Create all the MC Objects.
293 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
295 return error(Twine("no register info for target ") + TripleName, Context);
297 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
299 return error("no asm info for target " + TripleName, Context);
301 MCObjectFileInfo MOFI;
302 MCContext MC(MAI.get(), MRI.get(), &MOFI);
303 MOFI.InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
306 auto MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
308 return error("no asm backend for target " + TripleName, Context);
310 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
312 return error("no instr info info for target " + TripleName, Context);
314 std::unique_ptr<MCSubtargetInfo> MSTI(
315 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
317 return error("no subtarget info for target " + TripleName, Context);
319 MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC);
321 return error("no code emitter for target " + TripleName, Context);
323 // Create the output file.
325 raw_fd_ostream OutFile(OutputFilename, EC, sys::fs::F_None);
327 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
329 std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
330 TheTriple, MC, *MAB, OutFile, MCE, *MSTI, false,
331 /*DWARFMustBeAtTheEnd*/ false));
333 return error("no object streamer for target " + TripleName, Context);
335 if (auto Err = write(*MS, InputFiles))
336 return error(Err.message(), "Writing DWP file");