blob: 8a0744cf1e016b7866480c3157afd963469f9bb0 [file] [log] [blame]
David Blaikie7ade1db2016-03-01 22:29:00 +00001//===-- llvm-dwp.cpp - Split DWARF merging tool for llvm ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// A utility for merging DWARF 5 Split DWARF .dwo files into .dwp (DWARF
11// package files).
12//
13//===----------------------------------------------------------------------===//
David Blaikie018cdc82016-05-23 16:32:11 +000014#include "DWPError.h"
15#include "DWPStringPool.h"
David Blaikieff94d6e2016-02-19 21:09:26 +000016#include "llvm/ADT/MapVector.h"
David Blaikiebb823832015-12-01 00:48:39 +000017#include "llvm/ADT/STLExtras.h"
Alexander Shaposhnikovdce71c72017-09-02 08:19:01 +000018#include "llvm/DebugInfo/DWARF/DWARFContext.h"
David Blaikie32ad0752015-12-05 03:06:30 +000019#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
20#include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
Lang Hames445025a2017-10-11 01:57:21 +000021#include "llvm/MC/MCAsmBackend.h"
David Blaikiebb823832015-12-01 00:48:39 +000022#include "llvm/MC/MCAsmInfo.h"
Lang Hames806f68b2017-10-11 23:34:47 +000023#include "llvm/MC/MCCodeEmitter.h"
David Blaikiebb823832015-12-01 00:48:39 +000024#include "llvm/MC/MCContext.h"
25#include "llvm/MC/MCInstrInfo.h"
26#include "llvm/MC/MCObjectFileInfo.h"
Peter Collingbourne17a98142018-05-18 18:26:45 +000027#include "llvm/MC/MCObjectWriter.h"
David Blaikiebb823832015-12-01 00:48:39 +000028#include "llvm/MC/MCRegisterInfo.h"
David Blaikiebb823832015-12-01 00:48:39 +000029#include "llvm/MC/MCStreamer.h"
David Blaikie461bf522018-04-11 18:49:37 +000030#include "llvm/MC/MCTargetOptionsCommandFlags.inc"
George Rimar06943952017-01-13 15:58:55 +000031#include "llvm/Object/Decompressor.h"
David Blaikiebb823832015-12-01 00:48:39 +000032#include "llvm/Object/ObjectFile.h"
David Blaikie0fb89f72015-12-01 18:07:07 +000033#include "llvm/Support/DataExtractor.h"
David Blaikie018cdc82016-05-23 16:32:11 +000034#include "llvm/Support/Error.h"
David Blaikiebb823832015-12-01 00:48:39 +000035#include "llvm/Support/FileSystem.h"
Fangrui Songc5823bd2018-05-06 23:08:29 +000036#include "llvm/Support/InitLLVM.h"
David Blaikie32ad0752015-12-05 03:06:30 +000037#include "llvm/Support/MathExtras.h"
David Blaikiebb823832015-12-01 00:48:39 +000038#include "llvm/Support/MemoryBuffer.h"
Alexander Shaposhnikovdce71c72017-09-02 08:19:01 +000039#include "llvm/Support/Path.h"
David Blaikiebb823832015-12-01 00:48:39 +000040#include "llvm/Support/TargetRegistry.h"
David Blaikie32ad0752015-12-05 03:06:30 +000041#include "llvm/Support/TargetSelect.h"
David Blaikiebb823832015-12-01 00:48:39 +000042#include "llvm/Support/raw_ostream.h"
David Blaikiebb823832015-12-01 00:48:39 +000043
44using namespace llvm;
David Blaikie0fb89f72015-12-01 18:07:07 +000045using namespace llvm::object;
David Blaikiebb823832015-12-01 00:48:39 +000046
Fangrui Songc04d0592018-09-06 20:23:34 +000047cl::OptionCategory DwpCategory("Specific Options");
48static cl::list<std::string> InputFiles(cl::Positional, cl::ZeroOrMore,
49 cl::desc("<input files>"),
50 cl::cat(DwpCategory));
David Blaikiebb823832015-12-01 00:48:39 +000051
Fangrui Songc04d0592018-09-06 20:23:34 +000052static cl::list<std::string> ExecFilenames(
53 "e", cl::ZeroOrMore,
54 cl::desc("Specify the executable/library files to get the list of *.dwo from"),
55 cl::value_desc("filename"), cl::cat(DwpCategory));
Alexander Shaposhnikovdce71c72017-09-02 08:19:01 +000056
Fangrui Songc04d0592018-09-06 20:23:34 +000057static cl::opt<std::string> OutputFilename(cl::Required, "o",
58 cl::desc("Specify the output file."),
59 cl::value_desc("filename"),
60 cl::cat(DwpCategory));
David Blaikiebb823832015-12-01 00:48:39 +000061
David Blaikie018cdc82016-05-23 16:32:11 +000062static void writeStringsAndOffsets(MCStreamer &Out, DWPStringPool &Strings,
63 MCSection *StrOffsetSection,
64 StringRef CurStrSection,
65 StringRef CurStrOffsetSection) {
David Blaikie0fb89f72015-12-01 18:07:07 +000066 // Could possibly produce an error or warning if one of these was non-null but
67 // the other was null.
68 if (CurStrSection.empty() || CurStrOffsetSection.empty())
David Blaikief84af692016-05-17 23:44:13 +000069 return;
David Blaikie0fb89f72015-12-01 18:07:07 +000070
71 DenseMap<uint32_t, uint32_t> OffsetRemapping;
72
73 DataExtractor Data(CurStrSection, true, 0);
74 uint32_t LocalOffset = 0;
75 uint32_t PrevOffset = 0;
76 while (const char *s = Data.getCStr(&LocalOffset)) {
David Blaikie018cdc82016-05-23 16:32:11 +000077 OffsetRemapping[PrevOffset] =
78 Strings.getOffset(s, LocalOffset - PrevOffset);
David Blaikie0fb89f72015-12-01 18:07:07 +000079 PrevOffset = LocalOffset;
80 }
81
82 Data = DataExtractor(CurStrOffsetSection, true, 0);
83
84 Out.SwitchSection(StrOffsetSection);
85
86 uint32_t Offset = 0;
87 uint64_t Size = CurStrOffsetSection.size();
88 while (Offset < Size) {
89 auto OldOffset = Data.getU32(&Offset);
90 auto NewOffset = OffsetRemapping[OldOffset];
91 Out.EmitIntValue(NewOffset, 4);
92 }
David Blaikiebb823832015-12-01 00:48:39 +000093}
94
David Blaikie2a3cc322015-12-04 17:20:04 +000095static uint32_t getCUAbbrev(StringRef Abbrev, uint64_t AbbrCode) {
96 uint64_t CurCode;
97 uint32_t Offset = 0;
98 DataExtractor AbbrevData(Abbrev, true, 0);
99 while ((CurCode = AbbrevData.getULEB128(&Offset)) != AbbrCode) {
100 // Tag
101 AbbrevData.getULEB128(&Offset);
102 // DW_CHILDREN
103 AbbrevData.getU8(&Offset);
104 // Attributes
105 while (AbbrevData.getULEB128(&Offset) | AbbrevData.getULEB128(&Offset))
106 ;
107 }
108 return Offset;
109}
110
David Blaikiedfb40132016-03-24 22:17:08 +0000111struct CompileUnitIdentifiers {
112 uint64_t Signature = 0;
David Blaikie3bcdc182016-03-26 20:32:14 +0000113 const char *Name = "";
114 const char *DWOName = "";
David Blaikiedfb40132016-03-24 22:17:08 +0000115};
116
David Blaikie4945c532016-05-17 00:07:10 +0000117static Expected<const char *>
Alexander Shaposhnikovdce71c72017-09-02 08:19:01 +0000118getIndexedString(dwarf::Form Form, DataExtractor InfoData,
Greg Clayton07e9e1a2016-10-27 16:32:04 +0000119 uint32_t &InfoOffset, StringRef StrOffsets, StringRef Str) {
David Blaikiefe34a372016-04-05 20:16:38 +0000120 if (Form == dwarf::DW_FORM_string)
121 return InfoData.getCStr(&InfoOffset);
David Blaikie4945c532016-05-17 00:07:10 +0000122 if (Form != dwarf::DW_FORM_GNU_str_index)
123 return make_error<DWPError>(
124 "string field encoded without DW_FORM_string or DW_FORM_GNU_str_index");
David Blaikiefe34a372016-04-05 20:16:38 +0000125 auto StrIndex = InfoData.getULEB128(&InfoOffset);
David Blaikie3bcdc182016-03-26 20:32:14 +0000126 DataExtractor StrOffsetsData(StrOffsets, true, 0);
127 uint32_t StrOffsetsOffset = 4 * StrIndex;
128 uint32_t StrOffset = StrOffsetsData.getU32(&StrOffsetsOffset);
129 DataExtractor StrData(Str, true, 0);
130 return StrData.getCStr(&StrOffset);
131}
132
David Blaikiedd6e7862016-05-16 23:26:29 +0000133static Expected<CompileUnitIdentifiers> getCUIdentifiers(StringRef Abbrev,
134 StringRef Info,
135 StringRef StrOffsets,
136 StringRef Str) {
David Blaikie6802c082016-02-26 07:30:15 +0000137 uint32_t Offset = 0;
138 DataExtractor InfoData(Info, true, 0);
Greg Claytonf5acbc22016-11-11 16:21:37 +0000139 dwarf::DwarfFormat Format = dwarf::DwarfFormat::DWARF32;
140 uint64_t Length = InfoData.getU32(&Offset);
141 // If the length is 0xffffffff, then this indictes that this is a DWARF 64
142 // stream and the length is actually encoded into a 64 bit value that follows.
143 if (Length == 0xffffffffU) {
144 Format = dwarf::DwarfFormat::DWARF64;
145 Length = InfoData.getU64(&Offset);
146 }
David Blaikie6802c082016-02-26 07:30:15 +0000147 uint16_t Version = InfoData.getU16(&Offset);
148 InfoData.getU32(&Offset); // Abbrev offset (should be zero)
149 uint8_t AddrSize = InfoData.getU8(&Offset);
150
151 uint32_t AbbrCode = InfoData.getULEB128(&Offset);
152
153 DataExtractor AbbrevData(Abbrev, true, 0);
154 uint32_t AbbrevOffset = getCUAbbrev(Abbrev, AbbrCode);
Greg Clayton07e9e1a2016-10-27 16:32:04 +0000155 auto Tag = static_cast<dwarf::Tag>(AbbrevData.getULEB128(&AbbrevOffset));
David Blaikiedd6e7862016-05-16 23:26:29 +0000156 if (Tag != dwarf::DW_TAG_compile_unit)
157 return make_error<DWPError>("top level DIE is not a compile unit");
David Blaikie6802c082016-02-26 07:30:15 +0000158 // DW_CHILDREN
159 AbbrevData.getU8(&AbbrevOffset);
160 uint32_t Name;
Greg Clayton07e9e1a2016-10-27 16:32:04 +0000161 dwarf::Form Form;
David Blaikiedfb40132016-03-24 22:17:08 +0000162 CompileUnitIdentifiers ID;
David Blaikie6802c082016-02-26 07:30:15 +0000163 while ((Name = AbbrevData.getULEB128(&AbbrevOffset)) |
Greg Clayton07e9e1a2016-10-27 16:32:04 +0000164 (Form = static_cast<dwarf::Form>(AbbrevData.getULEB128(&AbbrevOffset))) &&
David Blaikiedfb40132016-03-24 22:17:08 +0000165 (Name != 0 || Form != 0)) {
166 switch (Name) {
167 case dwarf::DW_AT_name: {
David Blaikie4945c532016-05-17 00:07:10 +0000168 Expected<const char *> EName =
169 getIndexedString(Form, InfoData, Offset, StrOffsets, Str);
170 if (!EName)
171 return EName.takeError();
172 ID.Name = *EName;
David Blaikie3bcdc182016-03-26 20:32:14 +0000173 break;
174 }
175 case dwarf::DW_AT_GNU_dwo_name: {
David Blaikie4945c532016-05-17 00:07:10 +0000176 Expected<const char *> EName =
177 getIndexedString(Form, InfoData, Offset, StrOffsets, Str);
178 if (!EName)
179 return EName.takeError();
180 ID.DWOName = *EName;
David Blaikiedfb40132016-03-24 22:17:08 +0000181 break;
182 }
183 case dwarf::DW_AT_GNU_dwo_id:
184 ID.Signature = InfoData.getU64(&Offset);
185 break;
186 default:
Paul Robinsonfd770ea2017-06-26 18:43:01 +0000187 DWARFFormValue::skipValue(Form, InfoData, &Offset,
Pavel Labathfa49d7da2018-03-14 09:39:54 +0000188 dwarf::FormParams({Version, AddrSize, Format}));
David Blaikiedfb40132016-03-24 22:17:08 +0000189 }
David Blaikie6802c082016-02-26 07:30:15 +0000190 }
David Blaikiedfb40132016-03-24 22:17:08 +0000191 return ID;
David Blaikie2a3cc322015-12-04 17:20:04 +0000192}
193
David Blaikie543e02b2015-12-05 03:05:45 +0000194struct UnitIndexEntry {
David Blaikie543e02b2015-12-05 03:05:45 +0000195 DWARFUnitIndex::Entry::SectionContribution Contributions[8];
David Blaikie6802c082016-02-26 07:30:15 +0000196 std::string Name;
David Blaikie3bcdc182016-03-26 20:32:14 +0000197 std::string DWOName;
David Blaikie6802c082016-02-26 07:30:15 +0000198 StringRef DWPName;
David Blaikie543e02b2015-12-05 03:05:45 +0000199};
200
David Blaikie018cdc82016-05-23 16:32:11 +0000201static StringRef getSubsection(StringRef Section,
202 const DWARFUnitIndex::Entry &Entry,
203 DWARFSectionKind Kind) {
David Blaikie6802c082016-02-26 07:30:15 +0000204 const auto *Off = Entry.getOffset(Kind);
205 if (!Off)
206 return StringRef();
207 return Section.substr(Off->Offset, Off->Length);
208}
209
David Blaikieff94d6e2016-02-19 21:09:26 +0000210static void addAllTypesFromDWP(
211 MCStreamer &Out, MapVector<uint64_t, UnitIndexEntry> &TypeIndexEntries,
212 const DWARFUnitIndex &TUIndex, MCSection *OutputTypes, StringRef Types,
213 const UnitIndexEntry &TUEntry, uint32_t &TypesOffset) {
David Blaikie11dc3712016-02-17 07:00:24 +0000214 Out.SwitchSection(OutputTypes);
215 for (const DWARFUnitIndex::Entry &E : TUIndex.getRows()) {
216 auto *I = E.getOffsets();
217 if (!I)
218 continue;
David Blaikieff94d6e2016-02-19 21:09:26 +0000219 auto P = TypeIndexEntries.insert(std::make_pair(E.getSignature(), TUEntry));
220 if (!P.second)
David Blaikie11dc3712016-02-17 07:00:24 +0000221 continue;
David Blaikieff94d6e2016-02-19 21:09:26 +0000222 auto &Entry = P.first->second;
David Blaikie11dc3712016-02-17 07:00:24 +0000223 // Zero out the debug_info contribution
224 Entry.Contributions[0] = {};
225 for (auto Kind : TUIndex.getColumnKinds()) {
226 auto &C = Entry.Contributions[Kind - DW_SECT_INFO];
227 C.Offset += I->Offset;
228 C.Length = I->Length;
229 ++I;
230 }
231 auto &C = Entry.Contributions[DW_SECT_TYPES - DW_SECT_INFO];
232 Out.EmitBytes(Types.substr(
233 C.Offset - TUEntry.Contributions[DW_SECT_TYPES - DW_SECT_INFO].Offset,
234 C.Length));
235 C.Offset = TypesOffset;
236 TypesOffset += C.Length;
David Blaikie11dc3712016-02-17 07:00:24 +0000237 }
238}
239
David Blaikiece4a7232015-12-09 21:02:33 +0000240static void addAllTypes(MCStreamer &Out,
David Blaikieff94d6e2016-02-19 21:09:26 +0000241 MapVector<uint64_t, UnitIndexEntry> &TypeIndexEntries,
David Blaikie46c3acf2016-04-05 20:26:50 +0000242 MCSection *OutputTypes,
243 const std::vector<StringRef> &TypesSections,
David Blaikiece4a7232015-12-09 21:02:33 +0000244 const UnitIndexEntry &CUEntry, uint32_t &TypesOffset) {
David Blaikie46c3acf2016-04-05 20:26:50 +0000245 for (StringRef Types : TypesSections) {
246 Out.SwitchSection(OutputTypes);
247 uint32_t Offset = 0;
248 DataExtractor Data(Types, true, 0);
249 while (Data.isValidOffset(Offset)) {
250 UnitIndexEntry Entry = CUEntry;
251 // Zero out the debug_info contribution
252 Entry.Contributions[0] = {};
253 auto &C = Entry.Contributions[DW_SECT_TYPES - DW_SECT_INFO];
254 C.Offset = TypesOffset;
255 auto PrevOffset = Offset;
256 // Length of the unit, including the 4 byte length field.
257 C.Length = Data.getU32(&Offset) + 4;
David Blaikiece4a7232015-12-09 21:02:33 +0000258
David Blaikie46c3acf2016-04-05 20:26:50 +0000259 Data.getU16(&Offset); // Version
260 Data.getU32(&Offset); // Abbrev offset
261 Data.getU8(&Offset); // Address size
262 auto Signature = Data.getU64(&Offset);
263 Offset = PrevOffset + C.Length;
David Blaikie543e02b2015-12-05 03:05:45 +0000264
David Blaikie46c3acf2016-04-05 20:26:50 +0000265 auto P = TypeIndexEntries.insert(std::make_pair(Signature, Entry));
266 if (!P.second)
267 continue;
David Blaikiecd49eb32015-12-14 07:42:00 +0000268
David Blaikie46c3acf2016-04-05 20:26:50 +0000269 Out.EmitBytes(Types.substr(PrevOffset, C.Length));
270 TypesOffset += C.Length;
271 }
David Blaikie543e02b2015-12-05 03:05:45 +0000272 }
273}
274
275static void
276writeIndexTable(MCStreamer &Out, ArrayRef<unsigned> ContributionOffsets,
David Blaikieff94d6e2016-02-19 21:09:26 +0000277 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries,
David Blaikie543e02b2015-12-05 03:05:45 +0000278 uint32_t DWARFUnitIndex::Entry::SectionContribution::*Field) {
279 for (const auto &E : IndexEntries)
David Blaikieff94d6e2016-02-19 21:09:26 +0000280 for (size_t i = 0; i != array_lengthof(E.second.Contributions); ++i)
David Blaikie543e02b2015-12-05 03:05:45 +0000281 if (ContributionOffsets[i])
David Blaikieff94d6e2016-02-19 21:09:26 +0000282 Out.EmitIntValue(E.second.Contributions[i].*Field, 4);
David Blaikie543e02b2015-12-05 03:05:45 +0000283}
284
David Blaikieff94d6e2016-02-19 21:09:26 +0000285static void
286writeIndex(MCStreamer &Out, MCSection *Section,
287 ArrayRef<unsigned> ContributionOffsets,
288 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries) {
David Blaikie132af4d2016-02-26 07:04:58 +0000289 if (IndexEntries.empty())
290 return;
291
David Blaikie543e02b2015-12-05 03:05:45 +0000292 unsigned Columns = 0;
293 for (auto &C : ContributionOffsets)
294 if (C)
295 ++Columns;
296
297 std::vector<unsigned> Buckets(NextPowerOf2(3 * IndexEntries.size() / 2));
298 uint64_t Mask = Buckets.size() - 1;
David Blaikieff94d6e2016-02-19 21:09:26 +0000299 size_t i = 0;
300 for (const auto &P : IndexEntries) {
301 auto S = P.first;
David Blaikie543e02b2015-12-05 03:05:45 +0000302 auto H = S & Mask;
David Blaikie037ba972016-04-05 17:51:40 +0000303 auto HP = ((S >> 32) & Mask) | 1;
David Blaikiece4a7232015-12-09 21:02:33 +0000304 while (Buckets[H]) {
David Blaikieff94d6e2016-02-19 21:09:26 +0000305 assert(S != IndexEntries.begin()[Buckets[H] - 1].first &&
David Blaikiefb07a712016-02-19 01:51:44 +0000306 "Duplicate unit");
David Blaikie037ba972016-04-05 17:51:40 +0000307 H = (H + HP) & Mask;
David Blaikiece4a7232015-12-09 21:02:33 +0000308 }
David Blaikie543e02b2015-12-05 03:05:45 +0000309 Buckets[H] = i + 1;
David Blaikieff94d6e2016-02-19 21:09:26 +0000310 ++i;
David Blaikie543e02b2015-12-05 03:05:45 +0000311 }
312
313 Out.SwitchSection(Section);
314 Out.EmitIntValue(2, 4); // Version
315 Out.EmitIntValue(Columns, 4); // Columns
316 Out.EmitIntValue(IndexEntries.size(), 4); // Num Units
David Blaikie32ad0752015-12-05 03:06:30 +0000317 Out.EmitIntValue(Buckets.size(), 4); // Num Buckets
David Blaikie543e02b2015-12-05 03:05:45 +0000318
319 // Write the signatures.
320 for (const auto &I : Buckets)
David Blaikieff94d6e2016-02-19 21:09:26 +0000321 Out.EmitIntValue(I ? IndexEntries.begin()[I - 1].first : 0, 8);
David Blaikie543e02b2015-12-05 03:05:45 +0000322
323 // Write the indexes.
324 for (const auto &I : Buckets)
325 Out.EmitIntValue(I, 4);
326
327 // Write the column headers (which sections will appear in the table)
328 for (size_t i = 0; i != ContributionOffsets.size(); ++i)
329 if (ContributionOffsets[i])
330 Out.EmitIntValue(i + DW_SECT_INFO, 4);
331
332 // Write the offsets.
333 writeIndexTable(Out, ContributionOffsets, IndexEntries,
334 &DWARFUnitIndex::Entry::SectionContribution::Offset);
335
336 // Write the lengths.
337 writeIndexTable(Out, ContributionOffsets, IndexEntries,
338 &DWARFUnitIndex::Entry::SectionContribution::Length);
339}
David Blaikiefb07a712016-02-19 01:51:44 +0000340
David Blaikie119b9302016-05-16 20:42:27 +0000341std::string buildDWODescription(StringRef Name, StringRef DWPName, StringRef DWOName) {
342 std::string Text = "\'";
343 Text += Name;
344 Text += '\'';
David Blaikie3bcdc182016-03-26 20:32:14 +0000345 if (!DWPName.empty()) {
David Blaikie119b9302016-05-16 20:42:27 +0000346 Text += " (from ";
347 if (!DWOName.empty()) {
348 Text += '\'';
349 Text += DWOName;
350 Text += "' in ";
351 }
352 Text += '\'';
353 Text += DWPName;
354 Text += "')";
David Blaikie3bcdc182016-03-26 20:32:14 +0000355 }
David Blaikie119b9302016-05-16 20:42:27 +0000356 return Text;
357}
358
George Rimar06943952017-01-13 15:58:55 +0000359static Error createError(StringRef Name, Error E) {
360 return make_error<DWPError>(
361 ("failure while decompressing compressed section: '" + Name + "', " +
362 llvm::toString(std::move(E)))
363 .str());
364}
365
366static Error
367handleCompressedSection(std::deque<SmallString<32>> &UncompressedSections,
368 StringRef &Name, StringRef &Contents) {
369 if (!Decompressor::isGnuStyle(Name))
Mehdi Aminidf0b8bc2016-11-11 04:28:40 +0000370 return Error::success();
George Rimar06943952017-01-13 15:58:55 +0000371
372 Expected<Decompressor> Dec =
373 Decompressor::create(Name, Contents, false /*IsLE*/, false /*Is64Bit*/);
374 if (!Dec)
375 return createError(Name, Dec.takeError());
376
David Blaikie16017f92016-05-23 21:58:58 +0000377 UncompressedSections.emplace_back();
George Rimar33642102017-05-18 08:00:01 +0000378 if (Error E = Dec->resizeAndDecompress(UncompressedSections.back()))
George Rimar06943952017-01-13 15:58:55 +0000379 return createError(Name, std::move(E));
380
381 Name = Name.substr(2); // Drop ".z"
David Blaikie16017f92016-05-23 21:58:58 +0000382 Contents = UncompressedSections.back();
Mehdi Aminidf0b8bc2016-11-11 04:28:40 +0000383 return Error::success();
David Blaikie16017f92016-05-23 21:58:58 +0000384}
David Blaikie7bac6e82016-05-23 22:21:10 +0000385
386static Error handleSection(
387 const StringMap<std::pair<MCSection *, DWARFSectionKind>> &KnownSections,
388 const MCSection *StrSection, const MCSection *StrOffsetSection,
389 const MCSection *TypesSection, const MCSection *CUIndexSection,
390 const MCSection *TUIndexSection, const SectionRef &Section, MCStreamer &Out,
David Blaikiefe303ed2016-05-25 23:37:06 +0000391 std::deque<SmallString<32>> &UncompressedSections,
David Blaikie7bac6e82016-05-23 22:21:10 +0000392 uint32_t (&ContributionOffsets)[8], UnitIndexEntry &CurEntry,
393 StringRef &CurStrSection, StringRef &CurStrOffsetSection,
394 std::vector<StringRef> &CurTypesSection, StringRef &InfoSection,
395 StringRef &AbbrevSection, StringRef &CurCUIndexSection,
396 StringRef &CurTUIndexSection) {
397 if (Section.isBSS())
Mehdi Aminidf0b8bc2016-11-11 04:28:40 +0000398 return Error::success();
David Blaikie7bac6e82016-05-23 22:21:10 +0000399
400 if (Section.isVirtual())
Mehdi Aminidf0b8bc2016-11-11 04:28:40 +0000401 return Error::success();
David Blaikie7bac6e82016-05-23 22:21:10 +0000402
403 StringRef Name;
404 if (std::error_code Err = Section.getName(Name))
405 return errorCodeToError(Err);
406
David Blaikie7bac6e82016-05-23 22:21:10 +0000407 StringRef Contents;
408 if (auto Err = Section.getContents(Contents))
409 return errorCodeToError(Err);
410
411 if (auto Err = handleCompressedSection(UncompressedSections, Name, Contents))
412 return Err;
413
George Rimar06943952017-01-13 15:58:55 +0000414 Name = Name.substr(Name.find_first_not_of("._"));
415
David Blaikie7bac6e82016-05-23 22:21:10 +0000416 auto SectionPair = KnownSections.find(Name);
417 if (SectionPair == KnownSections.end())
Mehdi Aminidf0b8bc2016-11-11 04:28:40 +0000418 return Error::success();
David Blaikie7bac6e82016-05-23 22:21:10 +0000419
420 if (DWARFSectionKind Kind = SectionPair->second.second) {
421 auto Index = Kind - DW_SECT_INFO;
422 if (Kind != DW_SECT_TYPES) {
423 CurEntry.Contributions[Index].Offset = ContributionOffsets[Index];
424 ContributionOffsets[Index] +=
425 (CurEntry.Contributions[Index].Length = Contents.size());
426 }
427
428 switch (Kind) {
429 case DW_SECT_INFO:
430 InfoSection = Contents;
431 break;
432 case DW_SECT_ABBREV:
433 AbbrevSection = Contents;
434 break;
435 default:
436 break;
437 }
438 }
439
440 MCSection *OutSection = SectionPair->second.first;
441 if (OutSection == StrOffsetSection)
442 CurStrOffsetSection = Contents;
443 else if (OutSection == StrSection)
444 CurStrSection = Contents;
445 else if (OutSection == TypesSection)
446 CurTypesSection.push_back(Contents);
447 else if (OutSection == CUIndexSection)
448 CurCUIndexSection = Contents;
449 else if (OutSection == TUIndexSection)
450 CurTUIndexSection = Contents;
451 else {
452 Out.SwitchSection(OutSection);
453 Out.EmitBytes(Contents);
454 }
Mehdi Aminidf0b8bc2016-11-11 04:28:40 +0000455 return Error::success();
David Blaikie7bac6e82016-05-23 22:21:10 +0000456}
457
458static Error
459buildDuplicateError(const std::pair<uint64_t, UnitIndexEntry> &PrevE,
460 const CompileUnitIdentifiers &ID, StringRef DWPName) {
David Blaikie293233a2016-05-17 19:40:28 +0000461 return make_error<DWPError>(
462 std::string("Duplicate DWO ID (") + utohexstr(PrevE.first) + ") in " +
463 buildDWODescription(PrevE.second.Name, PrevE.second.DWPName,
464 PrevE.second.DWOName) +
465 " and " + buildDWODescription(ID.Name, DWPName, ID.DWOName));
David Blaikie3bcdc182016-03-26 20:32:14 +0000466}
David Blaikie7bac6e82016-05-23 22:21:10 +0000467
Alexander Shaposhnikovdce71c72017-09-02 08:19:01 +0000468static Expected<SmallVector<std::string, 16>>
469getDWOFilenames(StringRef ExecFilename) {
470 auto ErrOrObj = object::ObjectFile::createObjectFile(ExecFilename);
471 if (!ErrOrObj)
472 return ErrOrObj.takeError();
473
474 const ObjectFile &Obj = *ErrOrObj.get().getBinary();
475 std::unique_ptr<DWARFContext> DWARFCtx = DWARFContext::create(Obj);
476
477 SmallVector<std::string, 16> DWOPaths;
478 for (const auto &CU : DWARFCtx->compile_units()) {
479 const DWARFDie &Die = CU->getUnitDIE();
480 std::string DWOName = dwarf::toString(
481 Die.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
482 if (DWOName.empty())
483 continue;
484 std::string DWOCompDir =
485 dwarf::toString(Die.find(dwarf::DW_AT_comp_dir), "");
486 if (!DWOCompDir.empty()) {
487 SmallString<16> DWOPath;
488 sys::path::append(DWOPath, DWOCompDir, DWOName);
489 DWOPaths.emplace_back(DWOPath.data(), DWOPath.size());
490 } else {
491 DWOPaths.push_back(std::move(DWOName));
492 }
493 }
494 return std::move(DWOPaths);
495}
496
David Blaikie13dad4b2016-05-12 19:59:54 +0000497static Error write(MCStreamer &Out, ArrayRef<std::string> Inputs) {
David Blaikie0fb89f72015-12-01 18:07:07 +0000498 const auto &MCOFI = *Out.getContext().getObjectFileInfo();
499 MCSection *const StrSection = MCOFI.getDwarfStrDWOSection();
500 MCSection *const StrOffsetSection = MCOFI.getDwarfStrOffDWOSection();
David Blaikiece4a7232015-12-09 21:02:33 +0000501 MCSection *const TypesSection = MCOFI.getDwarfTypesDWOSection();
David Blaikie20603752016-02-06 01:15:26 +0000502 MCSection *const CUIndexSection = MCOFI.getDwarfCUIndexSection();
David Blaikie11dc3712016-02-17 07:00:24 +0000503 MCSection *const TUIndexSection = MCOFI.getDwarfTUIndexSection();
David Blaikie5001b2a2015-12-02 06:21:34 +0000504 const StringMap<std::pair<MCSection *, DWARFSectionKind>> KnownSections = {
505 {"debug_info.dwo", {MCOFI.getDwarfInfoDWOSection(), DW_SECT_INFO}},
506 {"debug_types.dwo", {MCOFI.getDwarfTypesDWOSection(), DW_SECT_TYPES}},
507 {"debug_str_offsets.dwo", {StrOffsetSection, DW_SECT_STR_OFFSETS}},
508 {"debug_str.dwo", {StrSection, static_cast<DWARFSectionKind>(0)}},
509 {"debug_loc.dwo", {MCOFI.getDwarfLocDWOSection(), DW_SECT_LOC}},
David Blaikie19d15112015-12-04 21:16:42 +0000510 {"debug_line.dwo", {MCOFI.getDwarfLineDWOSection(), DW_SECT_LINE}},
David Blaikie20603752016-02-06 01:15:26 +0000511 {"debug_abbrev.dwo", {MCOFI.getDwarfAbbrevDWOSection(), DW_SECT_ABBREV}},
David Blaikie11dc3712016-02-17 07:00:24 +0000512 {"debug_cu_index", {CUIndexSection, static_cast<DWARFSectionKind>(0)}},
513 {"debug_tu_index", {TUIndexSection, static_cast<DWARFSectionKind>(0)}}};
David Blaikie5001b2a2015-12-02 06:21:34 +0000514
David Blaikieff94d6e2016-02-19 21:09:26 +0000515 MapVector<uint64_t, UnitIndexEntry> IndexEntries;
516 MapVector<uint64_t, UnitIndexEntry> TypeIndexEntries;
David Blaikie0fb89f72015-12-01 18:07:07 +0000517
David Blaikie5001b2a2015-12-02 06:21:34 +0000518 uint32_t ContributionOffsets[8] = {};
519
David Blaikie018cdc82016-05-23 16:32:11 +0000520 DWPStringPool Strings(Out, StrSection);
521
522 SmallVector<OwningBinary<object::ObjectFile>, 128> Objects;
523 Objects.reserve(Inputs.size());
524
David Blaikiefe303ed2016-05-25 23:37:06 +0000525 std::deque<SmallString<32>> UncompressedSections;
David Blaikiefb4915b2016-05-23 17:35:51 +0000526
David Blaikiebb823832015-12-01 00:48:39 +0000527 for (const auto &Input : Inputs) {
528 auto ErrOrObj = object::ObjectFile::createObjectFile(Input);
529 if (!ErrOrObj)
David Blaikie13dad4b2016-05-12 19:59:54 +0000530 return ErrOrObj.takeError();
David Blaikie5001b2a2015-12-02 06:21:34 +0000531
David Blaikie018cdc82016-05-23 16:32:11 +0000532 auto &Obj = *ErrOrObj->getBinary();
533 Objects.push_back(std::move(*ErrOrObj));
534
David Blaikie20603752016-02-06 01:15:26 +0000535 UnitIndexEntry CurEntry = {};
David Blaikie5001b2a2015-12-02 06:21:34 +0000536
David Blaikie0fb89f72015-12-01 18:07:07 +0000537 StringRef CurStrSection;
538 StringRef CurStrOffsetSection;
David Blaikie46c3acf2016-04-05 20:26:50 +0000539 std::vector<StringRef> CurTypesSection;
David Blaikie2a3cc322015-12-04 17:20:04 +0000540 StringRef InfoSection;
541 StringRef AbbrevSection;
David Blaikie20603752016-02-06 01:15:26 +0000542 StringRef CurCUIndexSection;
David Blaikie11dc3712016-02-17 07:00:24 +0000543 StringRef CurTUIndexSection;
David Blaikie5001b2a2015-12-02 06:21:34 +0000544
David Blaikie7bac6e82016-05-23 22:21:10 +0000545 for (const auto &Section : Obj.sections())
546 if (auto Err = handleSection(
547 KnownSections, StrSection, StrOffsetSection, TypesSection,
548 CUIndexSection, TUIndexSection, Section, Out,
549 UncompressedSections, ContributionOffsets, CurEntry,
550 CurStrSection, CurStrOffsetSection, CurTypesSection, InfoSection,
551 AbbrevSection, CurCUIndexSection, CurTUIndexSection))
David Blaikie16017f92016-05-23 21:58:58 +0000552 return Err;
David Blaikiefb07a712016-02-19 01:51:44 +0000553
David Blaikie132af4d2016-02-26 07:04:58 +0000554 if (InfoSection.empty())
555 continue;
556
David Blaikie632d5682016-05-23 22:38:06 +0000557 writeStringsAndOffsets(Out, Strings, StrOffsetSection, CurStrSection,
558 CurStrOffsetSection);
David Blaikie20603752016-02-06 01:15:26 +0000559
David Blaikie632d5682016-05-23 22:38:06 +0000560 if (CurCUIndexSection.empty()) {
David Blaikiedd6e7862016-05-16 23:26:29 +0000561 Expected<CompileUnitIdentifiers> EID = getCUIdentifiers(
David Blaikiedfb40132016-03-24 22:17:08 +0000562 AbbrevSection, InfoSection, CurStrOffsetSection, CurStrSection);
David Blaikiedd6e7862016-05-16 23:26:29 +0000563 if (!EID)
564 return EID.takeError();
565 const auto &ID = *EID;
David Blaikiedfb40132016-03-24 22:17:08 +0000566 auto P = IndexEntries.insert(std::make_pair(ID.Signature, CurEntry));
David Blaikie119b9302016-05-16 20:42:27 +0000567 if (!P.second)
David Blaikie293233a2016-05-17 19:40:28 +0000568 return buildDuplicateError(*P.first, ID, "");
David Blaikiedfb40132016-03-24 22:17:08 +0000569 P.first->second.Name = ID.Name;
David Blaikie3bcdc182016-03-26 20:32:14 +0000570 P.first->second.DWOName = ID.DWOName;
David Blaikie20603752016-02-06 01:15:26 +0000571 addAllTypes(Out, TypeIndexEntries, TypesSection, CurTypesSection,
572 CurEntry, ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO]);
David Blaikie632d5682016-05-23 22:38:06 +0000573 continue;
David Blaikie20603752016-02-06 01:15:26 +0000574 }
David Blaikie2a3cc322015-12-04 17:20:04 +0000575
David Blaikie632d5682016-05-23 22:38:06 +0000576 DWARFUnitIndex CUIndex(DW_SECT_INFO);
577 DataExtractor CUIndexData(CurCUIndexSection, Obj.isLittleEndian(), 0);
578 if (!CUIndex.parse(CUIndexData))
579 return make_error<DWPError>("Failed to parse cu_index");
580
581 for (const DWARFUnitIndex::Entry &E : CUIndex.getRows()) {
582 auto *I = E.getOffsets();
583 if (!I)
584 continue;
585 auto P = IndexEntries.insert(std::make_pair(E.getSignature(), CurEntry));
586 Expected<CompileUnitIdentifiers> EID = getCUIdentifiers(
587 getSubsection(AbbrevSection, E, DW_SECT_ABBREV),
588 getSubsection(InfoSection, E, DW_SECT_INFO),
589 getSubsection(CurStrOffsetSection, E, DW_SECT_STR_OFFSETS),
590 CurStrSection);
591 if (!EID)
592 return EID.takeError();
593 const auto &ID = *EID;
594 if (!P.second)
595 return buildDuplicateError(*P.first, ID, Input);
596 auto &NewEntry = P.first->second;
597 NewEntry.Name = ID.Name;
598 NewEntry.DWOName = ID.DWOName;
599 NewEntry.DWPName = Input;
600 for (auto Kind : CUIndex.getColumnKinds()) {
601 auto &C = NewEntry.Contributions[Kind - DW_SECT_INFO];
602 C.Offset += I->Offset;
603 C.Length = I->Length;
604 ++I;
605 }
606 }
607
608 if (!CurTypesSection.empty()) {
609 if (CurTypesSection.size() != 1)
610 return make_error<DWPError>("multiple type unit sections in .dwp file");
611 DWARFUnitIndex TUIndex(DW_SECT_TYPES);
612 DataExtractor TUIndexData(CurTUIndexSection, Obj.isLittleEndian(), 0);
613 if (!TUIndex.parse(TUIndexData))
614 return make_error<DWPError>("Failed to parse tu_index");
615 addAllTypesFromDWP(Out, TypeIndexEntries, TUIndex, TypesSection,
616 CurTypesSection.front(), CurEntry,
617 ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO]);
618 }
David Blaikiebb823832015-12-01 00:48:39 +0000619 }
David Blaikie5001b2a2015-12-02 06:21:34 +0000620
David Blaikie132af4d2016-02-26 07:04:58 +0000621 // Lie about there being no info contributions so the TU index only includes
622 // the type unit contribution
623 ContributionOffsets[0] = 0;
624 writeIndex(Out, MCOFI.getDwarfTUIndexSection(), ContributionOffsets,
625 TypeIndexEntries);
David Blaikiedc564082015-12-02 22:01:56 +0000626
David Blaikie543e02b2015-12-05 03:05:45 +0000627 // Lie about the type contribution
628 ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO] = 0;
629 // Unlie about the info contribution
630 ContributionOffsets[0] = 1;
David Blaikiea2b2c5a2015-12-04 21:30:23 +0000631
David Blaikie543e02b2015-12-05 03:05:45 +0000632 writeIndex(Out, MCOFI.getDwarfCUIndexSection(), ContributionOffsets,
633 IndexEntries);
David Blaikiec9b39e62016-03-01 21:24:04 +0000634
Mehdi Aminidf0b8bc2016-11-11 04:28:40 +0000635 return Error::success();
David Blaikiebb823832015-12-01 00:48:39 +0000636}
637
David Blaikie34ab13f2016-05-17 23:37:44 +0000638static int error(const Twine &Error, const Twine &Context) {
639 errs() << Twine("while processing ") + Context + ":\n";
640 errs() << Twine("error: ") + Error + "\n";
641 return 1;
642}
643
David Blaikie32ad0752015-12-05 03:06:30 +0000644int main(int argc, char **argv) {
Fangrui Songc5823bd2018-05-06 23:08:29 +0000645 InitLLVM X(argc, argv);
David Blaikiebb823832015-12-01 00:48:39 +0000646
Fangrui Songc04d0592018-09-06 20:23:34 +0000647 cl::ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files\n");
David Blaikiebb823832015-12-01 00:48:39 +0000648
649 llvm::InitializeAllTargetInfos();
650 llvm::InitializeAllTargetMCs();
651 llvm::InitializeAllTargets();
652 llvm::InitializeAllAsmPrinters();
653
654 std::string ErrorStr;
655 StringRef Context = "dwarf streamer init";
656
657 Triple TheTriple("x86_64-linux-gnu");
658
659 // Get the target.
660 const Target *TheTarget =
661 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
662 if (!TheTarget)
663 return error(ErrorStr, Context);
664 std::string TripleName = TheTriple.getTriple();
665
666 // Create all the MC Objects.
667 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
668 if (!MRI)
669 return error(Twine("no register info for target ") + TripleName, Context);
670
671 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
672 if (!MAI)
673 return error("no asm info for target " + TripleName, Context);
674
675 MCObjectFileInfo MOFI;
676 MCContext MC(MAI.get(), MRI.get(), &MOFI);
Rafael Espindola2600a672017-08-02 20:32:26 +0000677 MOFI.InitMCObjectFileInfo(TheTriple, /*PIC*/ false, MC);
David Blaikiebb823832015-12-01 00:48:39 +0000678
Alex Bradburyd32868d2018-01-03 08:53:05 +0000679 std::unique_ptr<MCSubtargetInfo> MSTI(
680 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
681 if (!MSTI)
682 return error("no subtarget info for target " + TripleName, Context);
683
Joel Jones8a399752016-07-25 17:18:28 +0000684 MCTargetOptions Options;
Alex Bradburyd32868d2018-01-03 08:53:05 +0000685 auto MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, Options);
David Blaikiebb823832015-12-01 00:48:39 +0000686 if (!MAB)
687 return error("no asm backend for target " + TripleName, Context);
688
689 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
690 if (!MII)
691 return error("no instr info info for target " + TripleName, Context);
692
David Blaikiebb823832015-12-01 00:48:39 +0000693 MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC);
694 if (!MCE)
695 return error("no code emitter for target " + TripleName, Context);
696
697 // Create the output file.
698 std::error_code EC;
699 raw_fd_ostream OutFile(OutputFilename, EC, sys::fs::F_None);
Fangrui Songf2dd6bb2018-09-06 20:26:54 +0000700 Optional<buffer_ostream> BOS;
701 raw_pwrite_stream *OS;
David Blaikiebb823832015-12-01 00:48:39 +0000702 if (EC)
703 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
Fangrui Songf2dd6bb2018-09-06 20:26:54 +0000704 if (OutFile.supportsSeeking()) {
705 OS = &OutFile;
706 } else {
707 BOS.emplace(OutFile);
708 OS = BOS.getPointer();
709 }
David Blaikiebb823832015-12-01 00:48:39 +0000710
David Majnemer56afa6e2015-12-21 22:09:27 +0000711 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
David Blaikiebb823832015-12-01 00:48:39 +0000712 std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
Peter Collingbourne17a98142018-05-18 18:26:45 +0000713 TheTriple, MC, std::unique_ptr<MCAsmBackend>(MAB),
Fangrui Songf2dd6bb2018-09-06 20:26:54 +0000714 MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(MCE),
Peter Collingbourne17a98142018-05-18 18:26:45 +0000715 *MSTI, MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
David Blaikiebb823832015-12-01 00:48:39 +0000716 /*DWARFMustBeAtTheEnd*/ false));
717 if (!MS)
718 return error("no object streamer for target " + TripleName, Context);
719
Alexander Shaposhnikovdce71c72017-09-02 08:19:01 +0000720 std::vector<std::string> DWOFilenames = InputFiles;
721 for (const auto &ExecFilename : ExecFilenames) {
722 auto DWOs = getDWOFilenames(ExecFilename);
723 if (!DWOs) {
724 logAllUnhandledErrors(DWOs.takeError(), errs(), "error: ");
725 return 1;
726 }
727 DWOFilenames.insert(DWOFilenames.end(),
728 std::make_move_iterator(DWOs->begin()),
729 std::make_move_iterator(DWOs->end()));
730 }
731
732 if (auto Err = write(*MS, DWOFilenames)) {
David Blaikie13dad4b2016-05-12 19:59:54 +0000733 logAllUnhandledErrors(std::move(Err), errs(), "error: ");
734 return 1;
735 }
David Blaikiec9b39e62016-03-01 21:24:04 +0000736
737 MS->Finish();
David Blaikie62918042015-12-01 00:48:34 +0000738}