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 struct UnitIndexEntry {
135 DWARFUnitIndex::Entry::SectionContribution Contributions[8];
138 static void addAllTypes(std::vector<UnitIndexEntry> &TypeIndexEntries,
139 uint32_t OutTypesOffset, StringRef Types,
140 const UnitIndexEntry &CUEntry) {
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;
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;
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);
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)
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;
186 H += ((S >> 32) & Mask) | 1;
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
196 // Write the signatures.
197 for (const auto &I : Buckets)
198 Out.EmitIntValue(I ? IndexEntries[I - 1].Signature : 0, 8);
200 // Write the indexes.
201 for (const auto &I : Buckets)
202 Out.EmitIntValue(I, 4);
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);
209 // Write the offsets.
210 writeIndexTable(Out, ContributionOffsets, IndexEntries,
211 &DWARFUnitIndex::Entry::SectionContribution::Offset);
213 // Write the lengths.
214 writeIndexTable(Out, ContributionOffsets, IndexEntries,
215 &DWARFUnitIndex::Entry::SectionContribution::Length);
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}}};
230 std::vector<UnitIndexEntry> IndexEntries;
231 std::vector<UnitIndexEntry> TypeIndexEntries;
233 StringMap<uint32_t> Strings;
234 uint32_t StringOffset = 0;
236 uint32_t ContributionOffsets[8] = {};
238 for (const auto &Input : Inputs) {
239 auto ErrOrObj = object::ObjectFile::createObjectFile(Input);
241 return ErrOrObj.getError();
243 IndexEntries.emplace_back();
244 UnitIndexEntry &CurEntry = IndexEntries.back();
246 StringRef CurStrSection;
247 StringRef CurStrOffsetSection;
248 StringRef InfoSection;
249 StringRef AbbrevSection;
250 StringRef TypesSection;
252 auto TypesOffset = ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO];
254 for (const auto &Section : ErrOrObj->getBinary()->sections()) {
256 if (std::error_code Err = Section.getName(Name))
260 KnownSections.find(Name.substr(Name.find_first_not_of("._")));
261 if (SectionPair == KnownSections.end())
265 if (auto Err = Section.getContents(Contents))
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());
276 InfoSection = Contents;
279 AbbrevSection = Contents;
282 TypesSection = Contents;
289 MCSection *OutSection = SectionPair->second.first;
290 if (OutSection == StrOffsetSection)
291 CurStrOffsetSection = Contents;
292 else if (OutSection == StrSection)
293 CurStrSection = Contents;
295 Out.SwitchSection(OutSection);
296 Out.EmitBytes(Contents);
300 assert(!AbbrevSection.empty());
301 assert(!InfoSection.empty());
302 CurEntry.Signature = getCUSignature(AbbrevSection, InfoSection);
303 addAllTypes(TypeIndexEntries, TypesOffset, TypesSection, CurEntry);
305 if (auto Err = writeStringsAndOffsets(Out, Strings, StringOffset,
306 StrSection, StrOffsetSection,
307 CurStrSection, CurStrOffsetSection))
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,
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;
322 writeIndex(Out, MCOFI.getDwarfCUIndexSection(), ContributionOffsets,
325 return std::error_code();
328 int main(int argc, char** argv) {
330 ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files");
332 llvm::InitializeAllTargetInfos();
333 llvm::InitializeAllTargetMCs();
334 llvm::InitializeAllTargets();
335 llvm::InitializeAllAsmPrinters();
337 std::string ErrorStr;
338 StringRef Context = "dwarf streamer init";
340 Triple TheTriple("x86_64-linux-gnu");
343 const Target *TheTarget =
344 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
346 return error(ErrorStr, Context);
347 std::string TripleName = TheTriple.getTriple();
349 // Create all the MC Objects.
350 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
352 return error(Twine("no register info for target ") + TripleName, Context);
354 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
356 return error("no asm info for target " + TripleName, Context);
358 MCObjectFileInfo MOFI;
359 MCContext MC(MAI.get(), MRI.get(), &MOFI);
360 MOFI.InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
363 auto MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
365 return error("no asm backend for target " + TripleName, Context);
367 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
369 return error("no instr info info for target " + TripleName, Context);
371 std::unique_ptr<MCSubtargetInfo> MSTI(
372 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
374 return error("no subtarget info for target " + TripleName, Context);
376 MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC);
378 return error("no code emitter for target " + TripleName, Context);
380 // Create the output file.
382 raw_fd_ostream OutFile(OutputFilename, EC, sys::fs::F_None);
384 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
386 std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
387 TheTriple, MC, *MAB, OutFile, MCE, *MSTI, false,
388 /*DWARFMustBeAtTheEnd*/ false));
390 return error("no object streamer for target " + TripleName, Context);
392 if (auto Err = write(*MS, InputFiles))
393 return error(Err.message(), "Writing DWP file");