1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/ADT/StringSet.h"
3 #include "llvm/CodeGen/AsmPrinter.h"
4 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
5 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
6 #include "llvm/MC/MCAsmInfo.h"
7 #include "llvm/MC/MCContext.h"
8 #include "llvm/MC/MCInstrInfo.h"
9 #include "llvm/MC/MCObjectFileInfo.h"
10 #include "llvm/MC/MCRegisterInfo.h"
11 #include "llvm/MC/MCSectionELF.h"
12 #include "llvm/MC/MCStreamer.h"
13 #include "llvm/Object/ObjectFile.h"
14 #include "llvm/Support/DataExtractor.h"
15 #include "llvm/Support/FileSystem.h"
16 #include "llvm/Support/MathExtras.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "llvm/Support/Options.h"
19 #include "llvm/Support/TargetRegistry.h"
20 #include "llvm/Support/TargetSelect.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetMachine.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",
36 desc("Specify the output file."),
37 value_desc("filename"),
40 static int error(const Twine &Error, const Twine &Context) {
41 errs() << Twine("while processing ") + Context + ":\n";
42 errs() << Twine("error: ") + Error + "\n";
46 static std::error_code
47 writeStringsAndOffsets(MCStreamer &Out, StringMap<uint32_t> &Strings,
48 uint32_t &StringOffset, MCSection *StrSection,
49 MCSection *StrOffsetSection, StringRef CurStrSection,
50 StringRef CurStrOffsetSection) {
51 // Could possibly produce an error or warning if one of these was non-null but
52 // the other was null.
53 if (CurStrSection.empty() || CurStrOffsetSection.empty())
54 return std::error_code();
56 DenseMap<uint32_t, uint32_t> OffsetRemapping;
58 DataExtractor Data(CurStrSection, true, 0);
59 uint32_t LocalOffset = 0;
60 uint32_t PrevOffset = 0;
61 while (const char *s = Data.getCStr(&LocalOffset)) {
62 StringRef Str(s, LocalOffset - PrevOffset - 1);
63 auto Pair = Strings.insert(std::make_pair(Str, StringOffset));
65 Out.SwitchSection(StrSection);
67 StringRef(Pair.first->getKeyData(), Pair.first->getKeyLength() + 1));
68 StringOffset += Str.size() + 1;
70 OffsetRemapping[PrevOffset] = Pair.first->second;
71 PrevOffset = LocalOffset;
74 Data = DataExtractor(CurStrOffsetSection, true, 0);
76 Out.SwitchSection(StrOffsetSection);
79 uint64_t Size = CurStrOffsetSection.size();
80 while (Offset < Size) {
81 auto OldOffset = Data.getU32(&Offset);
82 auto NewOffset = OffsetRemapping[OldOffset];
83 Out.EmitIntValue(NewOffset, 4);
86 return std::error_code();
89 static uint32_t getCUAbbrev(StringRef Abbrev, uint64_t AbbrCode) {
92 DataExtractor AbbrevData(Abbrev, true, 0);
93 while ((CurCode = AbbrevData.getULEB128(&Offset)) != AbbrCode) {
95 AbbrevData.getULEB128(&Offset);
97 AbbrevData.getU8(&Offset);
99 while (AbbrevData.getULEB128(&Offset) | AbbrevData.getULEB128(&Offset))
105 static uint64_t getCUSignature(StringRef Abbrev, StringRef Info) {
107 DataExtractor InfoData(Info, true, 0);
108 InfoData.getU32(&Offset); // Length
109 uint16_t Version = InfoData.getU16(&Offset);
110 InfoData.getU32(&Offset); // Abbrev offset (should be zero)
111 uint8_t AddrSize = InfoData.getU8(&Offset);
113 uint32_t AbbrCode = InfoData.getULEB128(&Offset);
115 DataExtractor AbbrevData(Abbrev, true, 0);
116 uint32_t AbbrevOffset = getCUAbbrev(Abbrev, AbbrCode);
117 uint64_t Tag = AbbrevData.getULEB128(&AbbrevOffset);
119 // FIXME: Real error handling
120 assert(Tag == dwarf::DW_TAG_compile_unit);
122 AbbrevData.getU8(&AbbrevOffset);
125 while ((Name = AbbrevData.getULEB128(&AbbrevOffset)) |
126 (Form = AbbrevData.getULEB128(&AbbrevOffset)) &&
127 Name != dwarf::DW_AT_GNU_dwo_id) {
128 DWARFFormValue::skipValue(Form, InfoData, &Offset, Version, AddrSize);
130 // FIXME: Real error handling
131 assert(Name == dwarf::DW_AT_GNU_dwo_id);
132 return InfoData.getU64(&Offset);
135 struct UnitIndexEntry {
137 DWARFUnitIndex::Entry::SectionContribution Contributions[8];
140 static void addAllTypes(std::vector<UnitIndexEntry> &TypeIndexEntries,
141 uint32_t OutTypesOffset, StringRef Types,
142 const UnitIndexEntry &CUEntry) {
144 DataExtractor Data(Types, true, 0);
145 while (Data.isValidOffset(Offset)) {
146 TypeIndexEntries.push_back(CUEntry);
147 auto &Entry = TypeIndexEntries.back();
148 // Zero out the debug_info contribution
149 Entry.Contributions[0] = {};
150 auto &C = Entry.Contributions[DW_SECT_TYPES - DW_SECT_INFO];
151 C.Offset = OutTypesOffset + Offset;
152 auto PrevOffset = Offset;
153 // Length of the unit, including the 4 byte length field.
154 C.Length = Data.getU32(&Offset) + 4;
156 Data.getU16(&Offset); // Version
157 Data.getU32(&Offset); // Abbrev offset
158 Data.getU8(&Offset); // Address size
159 Entry.Signature = Data.getU64(&Offset);
160 Offset = PrevOffset + C.Length;
165 writeIndexTable(MCStreamer &Out, ArrayRef<unsigned> ContributionOffsets,
166 ArrayRef<UnitIndexEntry> IndexEntries,
167 uint32_t DWARFUnitIndex::Entry::SectionContribution::*Field) {
168 for (const auto &E : IndexEntries)
169 for (size_t i = 0; i != array_lengthof(E.Contributions); ++i)
170 if (ContributionOffsets[i])
171 Out.EmitIntValue(E.Contributions[i].*Field, 4);
174 static void writeIndex(MCStreamer &Out, MCSection *Section,
175 ArrayRef<unsigned> ContributionOffsets,
176 ArrayRef<UnitIndexEntry> IndexEntries) {
177 unsigned Columns = 0;
178 for (auto &C : ContributionOffsets)
182 std::vector<unsigned> Buckets(NextPowerOf2(3 * IndexEntries.size() / 2));
183 uint64_t Mask = Buckets.size() - 1;
184 for (size_t i = 0; i != IndexEntries.size(); ++i) {
185 auto S = IndexEntries[i].Signature;
188 H += ((S >> 32) & Mask) | 1;
192 Out.SwitchSection(Section);
193 Out.EmitIntValue(2, 4); // Version
194 Out.EmitIntValue(Columns, 4); // Columns
195 Out.EmitIntValue(IndexEntries.size(), 4); // Num Units
196 Out.EmitIntValue(Buckets.size(), 4); // Num Buckets
198 // Write the signatures.
199 for (const auto &I : Buckets)
200 Out.EmitIntValue(I ? IndexEntries[I - 1].Signature : 0, 8);
202 // Write the indexes.
203 for (const auto &I : Buckets)
204 Out.EmitIntValue(I, 4);
206 // Write the column headers (which sections will appear in the table)
207 for (size_t i = 0; i != ContributionOffsets.size(); ++i)
208 if (ContributionOffsets[i])
209 Out.EmitIntValue(i + DW_SECT_INFO, 4);
211 // Write the offsets.
212 writeIndexTable(Out, ContributionOffsets, IndexEntries,
213 &DWARFUnitIndex::Entry::SectionContribution::Offset);
215 // Write the lengths.
216 writeIndexTable(Out, ContributionOffsets, IndexEntries,
217 &DWARFUnitIndex::Entry::SectionContribution::Length);
219 static std::error_code write(MCStreamer &Out, ArrayRef<std::string> Inputs) {
220 const auto &MCOFI = *Out.getContext().getObjectFileInfo();
221 MCSection *const StrSection = MCOFI.getDwarfStrDWOSection();
222 MCSection *const StrOffsetSection = MCOFI.getDwarfStrOffDWOSection();
223 const StringMap<std::pair<MCSection *, DWARFSectionKind>> KnownSections = {
224 {"debug_info.dwo", {MCOFI.getDwarfInfoDWOSection(), DW_SECT_INFO}},
225 {"debug_types.dwo", {MCOFI.getDwarfTypesDWOSection(), DW_SECT_TYPES}},
226 {"debug_str_offsets.dwo", {StrOffsetSection, DW_SECT_STR_OFFSETS}},
227 {"debug_str.dwo", {StrSection, static_cast<DWARFSectionKind>(0)}},
228 {"debug_loc.dwo", {MCOFI.getDwarfLocDWOSection(), DW_SECT_LOC}},
229 {"debug_line.dwo", {MCOFI.getDwarfLineDWOSection(), DW_SECT_LINE}},
230 {"debug_abbrev.dwo", {MCOFI.getDwarfAbbrevDWOSection(), DW_SECT_ABBREV}}};
232 std::vector<UnitIndexEntry> IndexEntries;
233 std::vector<UnitIndexEntry> TypeIndexEntries;
235 StringMap<uint32_t> Strings;
236 uint32_t StringOffset = 0;
238 uint32_t ContributionOffsets[8] = {};
240 for (const auto &Input : Inputs) {
241 auto ErrOrObj = object::ObjectFile::createObjectFile(Input);
243 return ErrOrObj.getError();
245 IndexEntries.emplace_back();
246 UnitIndexEntry &CurEntry = IndexEntries.back();
248 StringRef CurStrSection;
249 StringRef CurStrOffsetSection;
250 StringRef InfoSection;
251 StringRef AbbrevSection;
252 StringRef TypesSection;
254 auto TypesOffset = ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO];
256 for (const auto &Section : ErrOrObj->getBinary()->sections()) {
258 if (std::error_code Err = Section.getName(Name))
262 KnownSections.find(Name.substr(Name.find_first_not_of("._")));
263 if (SectionPair == KnownSections.end())
267 if (auto Err = Section.getContents(Contents))
270 if (DWARFSectionKind Kind = SectionPair->second.second) {
271 auto Index = Kind - DW_SECT_INFO;
272 CurEntry.Contributions[Index].Offset = ContributionOffsets[Index];
273 ContributionOffsets[Index] +=
274 (CurEntry.Contributions[Index].Length = Contents.size());
278 InfoSection = Contents;
281 AbbrevSection = Contents;
284 TypesSection = Contents;
291 MCSection *OutSection = SectionPair->second.first;
292 if (OutSection == StrOffsetSection)
293 CurStrOffsetSection = Contents;
294 else if (OutSection == StrSection)
295 CurStrSection = Contents;
297 Out.SwitchSection(OutSection);
298 Out.EmitBytes(Contents);
302 assert(!AbbrevSection.empty());
303 assert(!InfoSection.empty());
304 CurEntry.Signature = getCUSignature(AbbrevSection, InfoSection);
305 addAllTypes(TypeIndexEntries, TypesOffset, TypesSection, CurEntry);
307 if (auto Err = writeStringsAndOffsets(Out, Strings, StringOffset,
308 StrSection, StrOffsetSection,
309 CurStrSection, CurStrOffsetSection))
313 if (!TypeIndexEntries.empty()) {
314 // Lie about there being no info contributions so the TU index only includes
315 // the type unit contribution
316 ContributionOffsets[0] = 0;
317 writeIndex(Out, MCOFI.getDwarfTUIndexSection(), ContributionOffsets,
321 // Lie about the type contribution
322 ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO] = 0;
323 // Unlie about the info contribution
324 ContributionOffsets[0] = 1;
326 writeIndex(Out, MCOFI.getDwarfCUIndexSection(), ContributionOffsets,
329 return std::error_code();
332 int main(int argc, char **argv) {
334 ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files");
336 llvm::InitializeAllTargetInfos();
337 llvm::InitializeAllTargetMCs();
338 llvm::InitializeAllTargets();
339 llvm::InitializeAllAsmPrinters();
341 std::string ErrorStr;
342 StringRef Context = "dwarf streamer init";
344 Triple TheTriple("x86_64-linux-gnu");
347 const Target *TheTarget =
348 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
350 return error(ErrorStr, Context);
351 std::string TripleName = TheTriple.getTriple();
353 // Create all the MC Objects.
354 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
356 return error(Twine("no register info for target ") + TripleName, Context);
358 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
360 return error("no asm info for target " + TripleName, Context);
362 MCObjectFileInfo MOFI;
363 MCContext MC(MAI.get(), MRI.get(), &MOFI);
364 MOFI.InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default, MC);
366 auto MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
368 return error("no asm backend for target " + TripleName, Context);
370 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
372 return error("no instr info info for target " + TripleName, Context);
374 std::unique_ptr<MCSubtargetInfo> MSTI(
375 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
377 return error("no subtarget info for target " + TripleName, Context);
379 MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC);
381 return error("no code emitter for target " + TripleName, Context);
383 // Create the output file.
385 raw_fd_ostream OutFile(OutputFilename, EC, sys::fs::F_None);
387 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
389 std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
390 TheTriple, MC, *MAB, OutFile, MCE, *MSTI, false,
391 /*DWARFMustBeAtTheEnd*/ false));
393 return error("no object streamer for target " + TripleName, Context);
395 if (auto Err = write(*MS, InputFiles))
396 return error(Err.message(), "Writing DWP file");