blob: 86409b113350d7ce8d5b192958ee10718806da79 [file] [log] [blame]
David Blaikief72dbc12016-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 Blaikiefd800922016-05-23 16:32:11 +000014#include "DWPError.h"
15#include "DWPStringPool.h"
David Blaikie852c02b2016-02-19 21:09:26 +000016#include "llvm/ADT/MapVector.h"
David Blaikie242b9482015-12-01 00:48:39 +000017#include "llvm/ADT/STLExtras.h"
Alexander Shaposhnikovf1f9c342017-09-02 08:19:01 +000018#include "llvm/DebugInfo/DWARF/DWARFContext.h"
David Blaikie2ed678c2015-12-05 03:06:30 +000019#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
20#include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
Lang Hames02d33052017-10-11 01:57:21 +000021#include "llvm/MC/MCAsmBackend.h"
David Blaikie242b9482015-12-01 00:48:39 +000022#include "llvm/MC/MCAsmInfo.h"
Lang Hames2241ffa2017-10-11 23:34:47 +000023#include "llvm/MC/MCCodeEmitter.h"
David Blaikie242b9482015-12-01 00:48:39 +000024#include "llvm/MC/MCContext.h"
25#include "llvm/MC/MCInstrInfo.h"
26#include "llvm/MC/MCObjectFileInfo.h"
27#include "llvm/MC/MCRegisterInfo.h"
David Blaikie242b9482015-12-01 00:48:39 +000028#include "llvm/MC/MCStreamer.h"
David Blaikie4333f972018-04-11 18:49:37 +000029#include "llvm/MC/MCTargetOptionsCommandFlags.inc"
George Rimar8f5976e2017-01-13 15:58:55 +000030#include "llvm/Object/Decompressor.h"
David Blaikie242b9482015-12-01 00:48:39 +000031#include "llvm/Object/ObjectFile.h"
David Blaikie98ad82a2015-12-01 18:07:07 +000032#include "llvm/Support/DataExtractor.h"
David Blaikiefd800922016-05-23 16:32:11 +000033#include "llvm/Support/Error.h"
David Blaikie242b9482015-12-01 00:48:39 +000034#include "llvm/Support/FileSystem.h"
Fangrui Song07f0a682018-05-06 23:08:29 +000035#include "llvm/Support/InitLLVM.h"
David Blaikie2ed678c2015-12-05 03:06:30 +000036#include "llvm/Support/MathExtras.h"
David Blaikie242b9482015-12-01 00:48:39 +000037#include "llvm/Support/MemoryBuffer.h"
Alexander Shaposhnikovf1f9c342017-09-02 08:19:01 +000038#include "llvm/Support/Path.h"
David Blaikie242b9482015-12-01 00:48:39 +000039#include "llvm/Support/TargetRegistry.h"
David Blaikie2ed678c2015-12-05 03:06:30 +000040#include "llvm/Support/TargetSelect.h"
David Blaikie242b9482015-12-01 00:48:39 +000041#include "llvm/Support/raw_ostream.h"
David Blaikie242b9482015-12-01 00:48:39 +000042
43using namespace llvm;
David Blaikie98ad82a2015-12-01 18:07:07 +000044using namespace llvm::object;
David Blaikie242b9482015-12-01 00:48:39 +000045using namespace cl;
46
47OptionCategory DwpCategory("Specific Options");
Alexander Shaposhnikovf1f9c342017-09-02 08:19:01 +000048static list<std::string> InputFiles(Positional, ZeroOrMore,
David Blaikie242b9482015-12-01 00:48:39 +000049 desc("<input files>"), cat(DwpCategory));
50
Alexander Shaposhnikovf1f9c342017-09-02 08:19:01 +000051static list<std::string> ExecFilenames(
52 "e", ZeroOrMore,
53 desc("Specify the executable/library files to get the list of *.dwo from"),
54 value_desc("filename"), cat(DwpCategory));
55
David Blaikie2ed678c2015-12-05 03:06:30 +000056static opt<std::string> OutputFilename(Required, "o",
57 desc("Specify the output file."),
58 value_desc("filename"),
59 cat(DwpCategory));
David Blaikie242b9482015-12-01 00:48:39 +000060
David Blaikiefd800922016-05-23 16:32:11 +000061static void writeStringsAndOffsets(MCStreamer &Out, DWPStringPool &Strings,
62 MCSection *StrOffsetSection,
63 StringRef CurStrSection,
64 StringRef CurStrOffsetSection) {
David Blaikie98ad82a2015-12-01 18:07:07 +000065 // Could possibly produce an error or warning if one of these was non-null but
66 // the other was null.
67 if (CurStrSection.empty() || CurStrOffsetSection.empty())
David Blaikiebc619cd2016-05-17 23:44:13 +000068 return;
David Blaikie98ad82a2015-12-01 18:07:07 +000069
70 DenseMap<uint32_t, uint32_t> OffsetRemapping;
71
72 DataExtractor Data(CurStrSection, true, 0);
73 uint32_t LocalOffset = 0;
74 uint32_t PrevOffset = 0;
75 while (const char *s = Data.getCStr(&LocalOffset)) {
David Blaikiefd800922016-05-23 16:32:11 +000076 OffsetRemapping[PrevOffset] =
77 Strings.getOffset(s, LocalOffset - PrevOffset);
David Blaikie98ad82a2015-12-01 18:07:07 +000078 PrevOffset = LocalOffset;
79 }
80
81 Data = DataExtractor(CurStrOffsetSection, true, 0);
82
83 Out.SwitchSection(StrOffsetSection);
84
85 uint32_t Offset = 0;
86 uint64_t Size = CurStrOffsetSection.size();
87 while (Offset < Size) {
88 auto OldOffset = Data.getU32(&Offset);
89 auto NewOffset = OffsetRemapping[OldOffset];
90 Out.EmitIntValue(NewOffset, 4);
91 }
David Blaikie242b9482015-12-01 00:48:39 +000092}
93
David Blaikiead07b5d2015-12-04 17:20:04 +000094static uint32_t getCUAbbrev(StringRef Abbrev, uint64_t AbbrCode) {
95 uint64_t CurCode;
96 uint32_t Offset = 0;
97 DataExtractor AbbrevData(Abbrev, true, 0);
98 while ((CurCode = AbbrevData.getULEB128(&Offset)) != AbbrCode) {
99 // Tag
100 AbbrevData.getULEB128(&Offset);
101 // DW_CHILDREN
102 AbbrevData.getU8(&Offset);
103 // Attributes
104 while (AbbrevData.getULEB128(&Offset) | AbbrevData.getULEB128(&Offset))
105 ;
106 }
107 return Offset;
108}
109
David Blaikiece7c6cf2016-03-24 22:17:08 +0000110struct CompileUnitIdentifiers {
111 uint64_t Signature = 0;
David Blaikie4dd03f02016-03-26 20:32:14 +0000112 const char *Name = "";
113 const char *DWOName = "";
David Blaikiece7c6cf2016-03-24 22:17:08 +0000114};
115
David Blaikie4940f872016-05-17 00:07:10 +0000116static Expected<const char *>
Alexander Shaposhnikovf1f9c342017-09-02 08:19:01 +0000117getIndexedString(dwarf::Form Form, DataExtractor InfoData,
Greg Clayton6c273762016-10-27 16:32:04 +0000118 uint32_t &InfoOffset, StringRef StrOffsets, StringRef Str) {
David Blaikie60fbd3b2016-04-05 20:16:38 +0000119 if (Form == dwarf::DW_FORM_string)
120 return InfoData.getCStr(&InfoOffset);
David Blaikie4940f872016-05-17 00:07:10 +0000121 if (Form != dwarf::DW_FORM_GNU_str_index)
122 return make_error<DWPError>(
123 "string field encoded without DW_FORM_string or DW_FORM_GNU_str_index");
David Blaikie60fbd3b2016-04-05 20:16:38 +0000124 auto StrIndex = InfoData.getULEB128(&InfoOffset);
David Blaikie4dd03f02016-03-26 20:32:14 +0000125 DataExtractor StrOffsetsData(StrOffsets, true, 0);
126 uint32_t StrOffsetsOffset = 4 * StrIndex;
127 uint32_t StrOffset = StrOffsetsData.getU32(&StrOffsetsOffset);
128 DataExtractor StrData(Str, true, 0);
129 return StrData.getCStr(&StrOffset);
130}
131
David Blaikie7bb62ef2016-05-16 23:26:29 +0000132static Expected<CompileUnitIdentifiers> getCUIdentifiers(StringRef Abbrev,
133 StringRef Info,
134 StringRef StrOffsets,
135 StringRef Str) {
David Blaikief1958da2016-02-26 07:30:15 +0000136 uint32_t Offset = 0;
137 DataExtractor InfoData(Info, true, 0);
Greg Clayton82f12b12016-11-11 16:21:37 +0000138 dwarf::DwarfFormat Format = dwarf::DwarfFormat::DWARF32;
139 uint64_t Length = InfoData.getU32(&Offset);
140 // If the length is 0xffffffff, then this indictes that this is a DWARF 64
141 // stream and the length is actually encoded into a 64 bit value that follows.
142 if (Length == 0xffffffffU) {
143 Format = dwarf::DwarfFormat::DWARF64;
144 Length = InfoData.getU64(&Offset);
145 }
David Blaikief1958da2016-02-26 07:30:15 +0000146 uint16_t Version = InfoData.getU16(&Offset);
147 InfoData.getU32(&Offset); // Abbrev offset (should be zero)
148 uint8_t AddrSize = InfoData.getU8(&Offset);
149
150 uint32_t AbbrCode = InfoData.getULEB128(&Offset);
151
152 DataExtractor AbbrevData(Abbrev, true, 0);
153 uint32_t AbbrevOffset = getCUAbbrev(Abbrev, AbbrCode);
Greg Clayton6c273762016-10-27 16:32:04 +0000154 auto Tag = static_cast<dwarf::Tag>(AbbrevData.getULEB128(&AbbrevOffset));
David Blaikie7bb62ef2016-05-16 23:26:29 +0000155 if (Tag != dwarf::DW_TAG_compile_unit)
156 return make_error<DWPError>("top level DIE is not a compile unit");
David Blaikief1958da2016-02-26 07:30:15 +0000157 // DW_CHILDREN
158 AbbrevData.getU8(&AbbrevOffset);
159 uint32_t Name;
Greg Clayton6c273762016-10-27 16:32:04 +0000160 dwarf::Form Form;
David Blaikiece7c6cf2016-03-24 22:17:08 +0000161 CompileUnitIdentifiers ID;
David Blaikief1958da2016-02-26 07:30:15 +0000162 while ((Name = AbbrevData.getULEB128(&AbbrevOffset)) |
Greg Clayton6c273762016-10-27 16:32:04 +0000163 (Form = static_cast<dwarf::Form>(AbbrevData.getULEB128(&AbbrevOffset))) &&
David Blaikiece7c6cf2016-03-24 22:17:08 +0000164 (Name != 0 || Form != 0)) {
165 switch (Name) {
166 case dwarf::DW_AT_name: {
David Blaikie4940f872016-05-17 00:07:10 +0000167 Expected<const char *> EName =
168 getIndexedString(Form, InfoData, Offset, StrOffsets, Str);
169 if (!EName)
170 return EName.takeError();
171 ID.Name = *EName;
David Blaikie4dd03f02016-03-26 20:32:14 +0000172 break;
173 }
174 case dwarf::DW_AT_GNU_dwo_name: {
David Blaikie4940f872016-05-17 00:07:10 +0000175 Expected<const char *> EName =
176 getIndexedString(Form, InfoData, Offset, StrOffsets, Str);
177 if (!EName)
178 return EName.takeError();
179 ID.DWOName = *EName;
David Blaikiece7c6cf2016-03-24 22:17:08 +0000180 break;
181 }
182 case dwarf::DW_AT_GNU_dwo_id:
183 ID.Signature = InfoData.getU64(&Offset);
184 break;
185 default:
Paul Robinson75c068c2017-06-26 18:43:01 +0000186 DWARFFormValue::skipValue(Form, InfoData, &Offset,
Pavel Labath322711f2018-03-14 09:39:54 +0000187 dwarf::FormParams({Version, AddrSize, Format}));
David Blaikiece7c6cf2016-03-24 22:17:08 +0000188 }
David Blaikief1958da2016-02-26 07:30:15 +0000189 }
David Blaikiece7c6cf2016-03-24 22:17:08 +0000190 return ID;
David Blaikiead07b5d2015-12-04 17:20:04 +0000191}
192
David Blaikie24c8ac92015-12-05 03:05:45 +0000193struct UnitIndexEntry {
David Blaikie24c8ac92015-12-05 03:05:45 +0000194 DWARFUnitIndex::Entry::SectionContribution Contributions[8];
David Blaikief1958da2016-02-26 07:30:15 +0000195 std::string Name;
David Blaikie4dd03f02016-03-26 20:32:14 +0000196 std::string DWOName;
David Blaikief1958da2016-02-26 07:30:15 +0000197 StringRef DWPName;
David Blaikie24c8ac92015-12-05 03:05:45 +0000198};
199
David Blaikiefd800922016-05-23 16:32:11 +0000200static StringRef getSubsection(StringRef Section,
201 const DWARFUnitIndex::Entry &Entry,
202 DWARFSectionKind Kind) {
David Blaikief1958da2016-02-26 07:30:15 +0000203 const auto *Off = Entry.getOffset(Kind);
204 if (!Off)
205 return StringRef();
206 return Section.substr(Off->Offset, Off->Length);
207}
208
David Blaikie852c02b2016-02-19 21:09:26 +0000209static void addAllTypesFromDWP(
210 MCStreamer &Out, MapVector<uint64_t, UnitIndexEntry> &TypeIndexEntries,
211 const DWARFUnitIndex &TUIndex, MCSection *OutputTypes, StringRef Types,
212 const UnitIndexEntry &TUEntry, uint32_t &TypesOffset) {
David Blaikie8bce5a02016-02-17 07:00:24 +0000213 Out.SwitchSection(OutputTypes);
214 for (const DWARFUnitIndex::Entry &E : TUIndex.getRows()) {
215 auto *I = E.getOffsets();
216 if (!I)
217 continue;
David Blaikie852c02b2016-02-19 21:09:26 +0000218 auto P = TypeIndexEntries.insert(std::make_pair(E.getSignature(), TUEntry));
219 if (!P.second)
David Blaikie8bce5a02016-02-17 07:00:24 +0000220 continue;
David Blaikie852c02b2016-02-19 21:09:26 +0000221 auto &Entry = P.first->second;
David Blaikie8bce5a02016-02-17 07:00:24 +0000222 // Zero out the debug_info contribution
223 Entry.Contributions[0] = {};
224 for (auto Kind : TUIndex.getColumnKinds()) {
225 auto &C = Entry.Contributions[Kind - DW_SECT_INFO];
226 C.Offset += I->Offset;
227 C.Length = I->Length;
228 ++I;
229 }
230 auto &C = Entry.Contributions[DW_SECT_TYPES - DW_SECT_INFO];
231 Out.EmitBytes(Types.substr(
232 C.Offset - TUEntry.Contributions[DW_SECT_TYPES - DW_SECT_INFO].Offset,
233 C.Length));
234 C.Offset = TypesOffset;
235 TypesOffset += C.Length;
David Blaikie8bce5a02016-02-17 07:00:24 +0000236 }
237}
238
David Blaikiec3826da2015-12-09 21:02:33 +0000239static void addAllTypes(MCStreamer &Out,
David Blaikie852c02b2016-02-19 21:09:26 +0000240 MapVector<uint64_t, UnitIndexEntry> &TypeIndexEntries,
David Blaikie62be5ae2016-04-05 20:26:50 +0000241 MCSection *OutputTypes,
242 const std::vector<StringRef> &TypesSections,
David Blaikiec3826da2015-12-09 21:02:33 +0000243 const UnitIndexEntry &CUEntry, uint32_t &TypesOffset) {
David Blaikie62be5ae2016-04-05 20:26:50 +0000244 for (StringRef Types : TypesSections) {
245 Out.SwitchSection(OutputTypes);
246 uint32_t Offset = 0;
247 DataExtractor Data(Types, true, 0);
248 while (Data.isValidOffset(Offset)) {
249 UnitIndexEntry Entry = CUEntry;
250 // Zero out the debug_info contribution
251 Entry.Contributions[0] = {};
252 auto &C = Entry.Contributions[DW_SECT_TYPES - DW_SECT_INFO];
253 C.Offset = TypesOffset;
254 auto PrevOffset = Offset;
255 // Length of the unit, including the 4 byte length field.
256 C.Length = Data.getU32(&Offset) + 4;
David Blaikiec3826da2015-12-09 21:02:33 +0000257
David Blaikie62be5ae2016-04-05 20:26:50 +0000258 Data.getU16(&Offset); // Version
259 Data.getU32(&Offset); // Abbrev offset
260 Data.getU8(&Offset); // Address size
261 auto Signature = Data.getU64(&Offset);
262 Offset = PrevOffset + C.Length;
David Blaikie24c8ac92015-12-05 03:05:45 +0000263
David Blaikie62be5ae2016-04-05 20:26:50 +0000264 auto P = TypeIndexEntries.insert(std::make_pair(Signature, Entry));
265 if (!P.second)
266 continue;
David Blaikief5cb6272015-12-14 07:42:00 +0000267
David Blaikie62be5ae2016-04-05 20:26:50 +0000268 Out.EmitBytes(Types.substr(PrevOffset, C.Length));
269 TypesOffset += C.Length;
270 }
David Blaikie24c8ac92015-12-05 03:05:45 +0000271 }
272}
273
274static void
275writeIndexTable(MCStreamer &Out, ArrayRef<unsigned> ContributionOffsets,
David Blaikie852c02b2016-02-19 21:09:26 +0000276 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries,
David Blaikie24c8ac92015-12-05 03:05:45 +0000277 uint32_t DWARFUnitIndex::Entry::SectionContribution::*Field) {
278 for (const auto &E : IndexEntries)
David Blaikie852c02b2016-02-19 21:09:26 +0000279 for (size_t i = 0; i != array_lengthof(E.second.Contributions); ++i)
David Blaikie24c8ac92015-12-05 03:05:45 +0000280 if (ContributionOffsets[i])
David Blaikie852c02b2016-02-19 21:09:26 +0000281 Out.EmitIntValue(E.second.Contributions[i].*Field, 4);
David Blaikie24c8ac92015-12-05 03:05:45 +0000282}
283
David Blaikie852c02b2016-02-19 21:09:26 +0000284static void
285writeIndex(MCStreamer &Out, MCSection *Section,
286 ArrayRef<unsigned> ContributionOffsets,
287 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries) {
David Blaikie5d6d4dc2016-02-26 07:04:58 +0000288 if (IndexEntries.empty())
289 return;
290
David Blaikie24c8ac92015-12-05 03:05:45 +0000291 unsigned Columns = 0;
292 for (auto &C : ContributionOffsets)
293 if (C)
294 ++Columns;
295
296 std::vector<unsigned> Buckets(NextPowerOf2(3 * IndexEntries.size() / 2));
297 uint64_t Mask = Buckets.size() - 1;
David Blaikie852c02b2016-02-19 21:09:26 +0000298 size_t i = 0;
299 for (const auto &P : IndexEntries) {
300 auto S = P.first;
David Blaikie24c8ac92015-12-05 03:05:45 +0000301 auto H = S & Mask;
David Blaikie9b492562016-04-05 17:51:40 +0000302 auto HP = ((S >> 32) & Mask) | 1;
David Blaikiec3826da2015-12-09 21:02:33 +0000303 while (Buckets[H]) {
David Blaikie852c02b2016-02-19 21:09:26 +0000304 assert(S != IndexEntries.begin()[Buckets[H] - 1].first &&
David Blaikie74f5b282016-02-19 01:51:44 +0000305 "Duplicate unit");
David Blaikie9b492562016-04-05 17:51:40 +0000306 H = (H + HP) & Mask;
David Blaikiec3826da2015-12-09 21:02:33 +0000307 }
David Blaikie24c8ac92015-12-05 03:05:45 +0000308 Buckets[H] = i + 1;
David Blaikie852c02b2016-02-19 21:09:26 +0000309 ++i;
David Blaikie24c8ac92015-12-05 03:05:45 +0000310 }
311
312 Out.SwitchSection(Section);
313 Out.EmitIntValue(2, 4); // Version
314 Out.EmitIntValue(Columns, 4); // Columns
315 Out.EmitIntValue(IndexEntries.size(), 4); // Num Units
David Blaikie2ed678c2015-12-05 03:06:30 +0000316 Out.EmitIntValue(Buckets.size(), 4); // Num Buckets
David Blaikie24c8ac92015-12-05 03:05:45 +0000317
318 // Write the signatures.
319 for (const auto &I : Buckets)
David Blaikie852c02b2016-02-19 21:09:26 +0000320 Out.EmitIntValue(I ? IndexEntries.begin()[I - 1].first : 0, 8);
David Blaikie24c8ac92015-12-05 03:05:45 +0000321
322 // Write the indexes.
323 for (const auto &I : Buckets)
324 Out.EmitIntValue(I, 4);
325
326 // Write the column headers (which sections will appear in the table)
327 for (size_t i = 0; i != ContributionOffsets.size(); ++i)
328 if (ContributionOffsets[i])
329 Out.EmitIntValue(i + DW_SECT_INFO, 4);
330
331 // Write the offsets.
332 writeIndexTable(Out, ContributionOffsets, IndexEntries,
333 &DWARFUnitIndex::Entry::SectionContribution::Offset);
334
335 // Write the lengths.
336 writeIndexTable(Out, ContributionOffsets, IndexEntries,
337 &DWARFUnitIndex::Entry::SectionContribution::Length);
338}
David Blaikie74f5b282016-02-19 01:51:44 +0000339
David Blaikied1f7ab32016-05-16 20:42:27 +0000340std::string buildDWODescription(StringRef Name, StringRef DWPName, StringRef DWOName) {
341 std::string Text = "\'";
342 Text += Name;
343 Text += '\'';
David Blaikie4dd03f02016-03-26 20:32:14 +0000344 if (!DWPName.empty()) {
David Blaikied1f7ab32016-05-16 20:42:27 +0000345 Text += " (from ";
346 if (!DWOName.empty()) {
347 Text += '\'';
348 Text += DWOName;
349 Text += "' in ";
350 }
351 Text += '\'';
352 Text += DWPName;
353 Text += "')";
David Blaikie4dd03f02016-03-26 20:32:14 +0000354 }
David Blaikied1f7ab32016-05-16 20:42:27 +0000355 return Text;
356}
357
George Rimar8f5976e2017-01-13 15:58:55 +0000358static Error createError(StringRef Name, Error E) {
359 return make_error<DWPError>(
360 ("failure while decompressing compressed section: '" + Name + "', " +
361 llvm::toString(std::move(E)))
362 .str());
363}
364
365static Error
366handleCompressedSection(std::deque<SmallString<32>> &UncompressedSections,
367 StringRef &Name, StringRef &Contents) {
368 if (!Decompressor::isGnuStyle(Name))
Mehdi Amini41af4302016-11-11 04:28:40 +0000369 return Error::success();
George Rimar8f5976e2017-01-13 15:58:55 +0000370
371 Expected<Decompressor> Dec =
372 Decompressor::create(Name, Contents, false /*IsLE*/, false /*Is64Bit*/);
373 if (!Dec)
374 return createError(Name, Dec.takeError());
375
David Blaikie05e0d2b2016-05-23 21:58:58 +0000376 UncompressedSections.emplace_back();
George Rimarf98b9ac2017-05-18 08:00:01 +0000377 if (Error E = Dec->resizeAndDecompress(UncompressedSections.back()))
George Rimar8f5976e2017-01-13 15:58:55 +0000378 return createError(Name, std::move(E));
379
380 Name = Name.substr(2); // Drop ".z"
David Blaikie05e0d2b2016-05-23 21:58:58 +0000381 Contents = UncompressedSections.back();
Mehdi Amini41af4302016-11-11 04:28:40 +0000382 return Error::success();
David Blaikie05e0d2b2016-05-23 21:58:58 +0000383}
David Blaikied9517cb2016-05-23 22:21:10 +0000384
385static Error handleSection(
386 const StringMap<std::pair<MCSection *, DWARFSectionKind>> &KnownSections,
387 const MCSection *StrSection, const MCSection *StrOffsetSection,
388 const MCSection *TypesSection, const MCSection *CUIndexSection,
389 const MCSection *TUIndexSection, const SectionRef &Section, MCStreamer &Out,
David Blaikie1fc3e6b2016-05-25 23:37:06 +0000390 std::deque<SmallString<32>> &UncompressedSections,
David Blaikied9517cb2016-05-23 22:21:10 +0000391 uint32_t (&ContributionOffsets)[8], UnitIndexEntry &CurEntry,
392 StringRef &CurStrSection, StringRef &CurStrOffsetSection,
393 std::vector<StringRef> &CurTypesSection, StringRef &InfoSection,
394 StringRef &AbbrevSection, StringRef &CurCUIndexSection,
395 StringRef &CurTUIndexSection) {
396 if (Section.isBSS())
Mehdi Amini41af4302016-11-11 04:28:40 +0000397 return Error::success();
David Blaikied9517cb2016-05-23 22:21:10 +0000398
399 if (Section.isVirtual())
Mehdi Amini41af4302016-11-11 04:28:40 +0000400 return Error::success();
David Blaikied9517cb2016-05-23 22:21:10 +0000401
402 StringRef Name;
403 if (std::error_code Err = Section.getName(Name))
404 return errorCodeToError(Err);
405
David Blaikied9517cb2016-05-23 22:21:10 +0000406 StringRef Contents;
407 if (auto Err = Section.getContents(Contents))
408 return errorCodeToError(Err);
409
410 if (auto Err = handleCompressedSection(UncompressedSections, Name, Contents))
411 return Err;
412
George Rimar8f5976e2017-01-13 15:58:55 +0000413 Name = Name.substr(Name.find_first_not_of("._"));
414
David Blaikied9517cb2016-05-23 22:21:10 +0000415 auto SectionPair = KnownSections.find(Name);
416 if (SectionPair == KnownSections.end())
Mehdi Amini41af4302016-11-11 04:28:40 +0000417 return Error::success();
David Blaikied9517cb2016-05-23 22:21:10 +0000418
419 if (DWARFSectionKind Kind = SectionPair->second.second) {
420 auto Index = Kind - DW_SECT_INFO;
421 if (Kind != DW_SECT_TYPES) {
422 CurEntry.Contributions[Index].Offset = ContributionOffsets[Index];
423 ContributionOffsets[Index] +=
424 (CurEntry.Contributions[Index].Length = Contents.size());
425 }
426
427 switch (Kind) {
428 case DW_SECT_INFO:
429 InfoSection = Contents;
430 break;
431 case DW_SECT_ABBREV:
432 AbbrevSection = Contents;
433 break;
434 default:
435 break;
436 }
437 }
438
439 MCSection *OutSection = SectionPair->second.first;
440 if (OutSection == StrOffsetSection)
441 CurStrOffsetSection = Contents;
442 else if (OutSection == StrSection)
443 CurStrSection = Contents;
444 else if (OutSection == TypesSection)
445 CurTypesSection.push_back(Contents);
446 else if (OutSection == CUIndexSection)
447 CurCUIndexSection = Contents;
448 else if (OutSection == TUIndexSection)
449 CurTUIndexSection = Contents;
450 else {
451 Out.SwitchSection(OutSection);
452 Out.EmitBytes(Contents);
453 }
Mehdi Amini41af4302016-11-11 04:28:40 +0000454 return Error::success();
David Blaikied9517cb2016-05-23 22:21:10 +0000455}
456
457static Error
458buildDuplicateError(const std::pair<uint64_t, UnitIndexEntry> &PrevE,
459 const CompileUnitIdentifiers &ID, StringRef DWPName) {
David Blaikie11825c72016-05-17 19:40:28 +0000460 return make_error<DWPError>(
461 std::string("Duplicate DWO ID (") + utohexstr(PrevE.first) + ") in " +
462 buildDWODescription(PrevE.second.Name, PrevE.second.DWPName,
463 PrevE.second.DWOName) +
464 " and " + buildDWODescription(ID.Name, DWPName, ID.DWOName));
David Blaikie4dd03f02016-03-26 20:32:14 +0000465}
David Blaikied9517cb2016-05-23 22:21:10 +0000466
Alexander Shaposhnikovf1f9c342017-09-02 08:19:01 +0000467static Expected<SmallVector<std::string, 16>>
468getDWOFilenames(StringRef ExecFilename) {
469 auto ErrOrObj = object::ObjectFile::createObjectFile(ExecFilename);
470 if (!ErrOrObj)
471 return ErrOrObj.takeError();
472
473 const ObjectFile &Obj = *ErrOrObj.get().getBinary();
474 std::unique_ptr<DWARFContext> DWARFCtx = DWARFContext::create(Obj);
475
476 SmallVector<std::string, 16> DWOPaths;
477 for (const auto &CU : DWARFCtx->compile_units()) {
478 const DWARFDie &Die = CU->getUnitDIE();
479 std::string DWOName = dwarf::toString(
480 Die.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
481 if (DWOName.empty())
482 continue;
483 std::string DWOCompDir =
484 dwarf::toString(Die.find(dwarf::DW_AT_comp_dir), "");
485 if (!DWOCompDir.empty()) {
486 SmallString<16> DWOPath;
487 sys::path::append(DWOPath, DWOCompDir, DWOName);
488 DWOPaths.emplace_back(DWOPath.data(), DWOPath.size());
489 } else {
490 DWOPaths.push_back(std::move(DWOName));
491 }
492 }
493 return std::move(DWOPaths);
494}
495
David Blaikiebc8397c2016-05-12 19:59:54 +0000496static Error write(MCStreamer &Out, ArrayRef<std::string> Inputs) {
David Blaikie98ad82a2015-12-01 18:07:07 +0000497 const auto &MCOFI = *Out.getContext().getObjectFileInfo();
498 MCSection *const StrSection = MCOFI.getDwarfStrDWOSection();
499 MCSection *const StrOffsetSection = MCOFI.getDwarfStrOffDWOSection();
David Blaikiec3826da2015-12-09 21:02:33 +0000500 MCSection *const TypesSection = MCOFI.getDwarfTypesDWOSection();
David Blaikie23919372016-02-06 01:15:26 +0000501 MCSection *const CUIndexSection = MCOFI.getDwarfCUIndexSection();
David Blaikie8bce5a02016-02-17 07:00:24 +0000502 MCSection *const TUIndexSection = MCOFI.getDwarfTUIndexSection();
David Blaikieb073cb92015-12-02 06:21:34 +0000503 const StringMap<std::pair<MCSection *, DWARFSectionKind>> KnownSections = {
504 {"debug_info.dwo", {MCOFI.getDwarfInfoDWOSection(), DW_SECT_INFO}},
505 {"debug_types.dwo", {MCOFI.getDwarfTypesDWOSection(), DW_SECT_TYPES}},
506 {"debug_str_offsets.dwo", {StrOffsetSection, DW_SECT_STR_OFFSETS}},
507 {"debug_str.dwo", {StrSection, static_cast<DWARFSectionKind>(0)}},
508 {"debug_loc.dwo", {MCOFI.getDwarfLocDWOSection(), DW_SECT_LOC}},
David Blaikieb7020252015-12-04 21:16:42 +0000509 {"debug_line.dwo", {MCOFI.getDwarfLineDWOSection(), DW_SECT_LINE}},
David Blaikie23919372016-02-06 01:15:26 +0000510 {"debug_abbrev.dwo", {MCOFI.getDwarfAbbrevDWOSection(), DW_SECT_ABBREV}},
David Blaikie8bce5a02016-02-17 07:00:24 +0000511 {"debug_cu_index", {CUIndexSection, static_cast<DWARFSectionKind>(0)}},
512 {"debug_tu_index", {TUIndexSection, static_cast<DWARFSectionKind>(0)}}};
David Blaikieb073cb92015-12-02 06:21:34 +0000513
David Blaikie852c02b2016-02-19 21:09:26 +0000514 MapVector<uint64_t, UnitIndexEntry> IndexEntries;
515 MapVector<uint64_t, UnitIndexEntry> TypeIndexEntries;
David Blaikie98ad82a2015-12-01 18:07:07 +0000516
David Blaikieb073cb92015-12-02 06:21:34 +0000517 uint32_t ContributionOffsets[8] = {};
518
David Blaikiefd800922016-05-23 16:32:11 +0000519 DWPStringPool Strings(Out, StrSection);
520
521 SmallVector<OwningBinary<object::ObjectFile>, 128> Objects;
522 Objects.reserve(Inputs.size());
523
David Blaikie1fc3e6b2016-05-25 23:37:06 +0000524 std::deque<SmallString<32>> UncompressedSections;
David Blaikie2e9bd892016-05-23 17:35:51 +0000525
David Blaikie242b9482015-12-01 00:48:39 +0000526 for (const auto &Input : Inputs) {
527 auto ErrOrObj = object::ObjectFile::createObjectFile(Input);
528 if (!ErrOrObj)
David Blaikiebc8397c2016-05-12 19:59:54 +0000529 return ErrOrObj.takeError();
David Blaikieb073cb92015-12-02 06:21:34 +0000530
David Blaikiefd800922016-05-23 16:32:11 +0000531 auto &Obj = *ErrOrObj->getBinary();
532 Objects.push_back(std::move(*ErrOrObj));
533
David Blaikie23919372016-02-06 01:15:26 +0000534 UnitIndexEntry CurEntry = {};
David Blaikieb073cb92015-12-02 06:21:34 +0000535
David Blaikie98ad82a2015-12-01 18:07:07 +0000536 StringRef CurStrSection;
537 StringRef CurStrOffsetSection;
David Blaikie62be5ae2016-04-05 20:26:50 +0000538 std::vector<StringRef> CurTypesSection;
David Blaikiead07b5d2015-12-04 17:20:04 +0000539 StringRef InfoSection;
540 StringRef AbbrevSection;
David Blaikie23919372016-02-06 01:15:26 +0000541 StringRef CurCUIndexSection;
David Blaikie8bce5a02016-02-17 07:00:24 +0000542 StringRef CurTUIndexSection;
David Blaikieb073cb92015-12-02 06:21:34 +0000543
David Blaikied9517cb2016-05-23 22:21:10 +0000544 for (const auto &Section : Obj.sections())
545 if (auto Err = handleSection(
546 KnownSections, StrSection, StrOffsetSection, TypesSection,
547 CUIndexSection, TUIndexSection, Section, Out,
548 UncompressedSections, ContributionOffsets, CurEntry,
549 CurStrSection, CurStrOffsetSection, CurTypesSection, InfoSection,
550 AbbrevSection, CurCUIndexSection, CurTUIndexSection))
David Blaikie05e0d2b2016-05-23 21:58:58 +0000551 return Err;
David Blaikie74f5b282016-02-19 01:51:44 +0000552
David Blaikie5d6d4dc2016-02-26 07:04:58 +0000553 if (InfoSection.empty())
554 continue;
555
David Blaikie478c1a22016-05-23 22:38:06 +0000556 writeStringsAndOffsets(Out, Strings, StrOffsetSection, CurStrSection,
557 CurStrOffsetSection);
David Blaikie23919372016-02-06 01:15:26 +0000558
David Blaikie478c1a22016-05-23 22:38:06 +0000559 if (CurCUIndexSection.empty()) {
David Blaikie7bb62ef2016-05-16 23:26:29 +0000560 Expected<CompileUnitIdentifiers> EID = getCUIdentifiers(
David Blaikiece7c6cf2016-03-24 22:17:08 +0000561 AbbrevSection, InfoSection, CurStrOffsetSection, CurStrSection);
David Blaikie7bb62ef2016-05-16 23:26:29 +0000562 if (!EID)
563 return EID.takeError();
564 const auto &ID = *EID;
David Blaikiece7c6cf2016-03-24 22:17:08 +0000565 auto P = IndexEntries.insert(std::make_pair(ID.Signature, CurEntry));
David Blaikied1f7ab32016-05-16 20:42:27 +0000566 if (!P.second)
David Blaikie11825c72016-05-17 19:40:28 +0000567 return buildDuplicateError(*P.first, ID, "");
David Blaikiece7c6cf2016-03-24 22:17:08 +0000568 P.first->second.Name = ID.Name;
David Blaikie4dd03f02016-03-26 20:32:14 +0000569 P.first->second.DWOName = ID.DWOName;
David Blaikie23919372016-02-06 01:15:26 +0000570 addAllTypes(Out, TypeIndexEntries, TypesSection, CurTypesSection,
571 CurEntry, ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO]);
David Blaikie478c1a22016-05-23 22:38:06 +0000572 continue;
David Blaikie23919372016-02-06 01:15:26 +0000573 }
David Blaikiead07b5d2015-12-04 17:20:04 +0000574
David Blaikie478c1a22016-05-23 22:38:06 +0000575 DWARFUnitIndex CUIndex(DW_SECT_INFO);
576 DataExtractor CUIndexData(CurCUIndexSection, Obj.isLittleEndian(), 0);
577 if (!CUIndex.parse(CUIndexData))
578 return make_error<DWPError>("Failed to parse cu_index");
579
580 for (const DWARFUnitIndex::Entry &E : CUIndex.getRows()) {
581 auto *I = E.getOffsets();
582 if (!I)
583 continue;
584 auto P = IndexEntries.insert(std::make_pair(E.getSignature(), CurEntry));
585 Expected<CompileUnitIdentifiers> EID = getCUIdentifiers(
586 getSubsection(AbbrevSection, E, DW_SECT_ABBREV),
587 getSubsection(InfoSection, E, DW_SECT_INFO),
588 getSubsection(CurStrOffsetSection, E, DW_SECT_STR_OFFSETS),
589 CurStrSection);
590 if (!EID)
591 return EID.takeError();
592 const auto &ID = *EID;
593 if (!P.second)
594 return buildDuplicateError(*P.first, ID, Input);
595 auto &NewEntry = P.first->second;
596 NewEntry.Name = ID.Name;
597 NewEntry.DWOName = ID.DWOName;
598 NewEntry.DWPName = Input;
599 for (auto Kind : CUIndex.getColumnKinds()) {
600 auto &C = NewEntry.Contributions[Kind - DW_SECT_INFO];
601 C.Offset += I->Offset;
602 C.Length = I->Length;
603 ++I;
604 }
605 }
606
607 if (!CurTypesSection.empty()) {
608 if (CurTypesSection.size() != 1)
609 return make_error<DWPError>("multiple type unit sections in .dwp file");
610 DWARFUnitIndex TUIndex(DW_SECT_TYPES);
611 DataExtractor TUIndexData(CurTUIndexSection, Obj.isLittleEndian(), 0);
612 if (!TUIndex.parse(TUIndexData))
613 return make_error<DWPError>("Failed to parse tu_index");
614 addAllTypesFromDWP(Out, TypeIndexEntries, TUIndex, TypesSection,
615 CurTypesSection.front(), CurEntry,
616 ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO]);
617 }
David Blaikie242b9482015-12-01 00:48:39 +0000618 }
David Blaikieb073cb92015-12-02 06:21:34 +0000619
David Blaikie5d6d4dc2016-02-26 07:04:58 +0000620 // Lie about there being no info contributions so the TU index only includes
621 // the type unit contribution
622 ContributionOffsets[0] = 0;
623 writeIndex(Out, MCOFI.getDwarfTUIndexSection(), ContributionOffsets,
624 TypeIndexEntries);
David Blaikieb3757c02015-12-02 22:01:56 +0000625
David Blaikie24c8ac92015-12-05 03:05:45 +0000626 // Lie about the type contribution
627 ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO] = 0;
628 // Unlie about the info contribution
629 ContributionOffsets[0] = 1;
David Blaikie7c4ffe02015-12-04 21:30:23 +0000630
David Blaikie24c8ac92015-12-05 03:05:45 +0000631 writeIndex(Out, MCOFI.getDwarfCUIndexSection(), ContributionOffsets,
632 IndexEntries);
David Blaikieddb27362016-03-01 21:24:04 +0000633
Mehdi Amini41af4302016-11-11 04:28:40 +0000634 return Error::success();
David Blaikie242b9482015-12-01 00:48:39 +0000635}
636
David Blaikie17ab78e2016-05-17 23:37:44 +0000637static int error(const Twine &Error, const Twine &Context) {
638 errs() << Twine("while processing ") + Context + ":\n";
639 errs() << Twine("error: ") + Error + "\n";
640 return 1;
641}
642
David Blaikie2ed678c2015-12-05 03:06:30 +0000643int main(int argc, char **argv) {
Fangrui Song07f0a682018-05-06 23:08:29 +0000644 InitLLVM X(argc, argv);
David Blaikie242b9482015-12-01 00:48:39 +0000645
646 ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files");
647
648 llvm::InitializeAllTargetInfos();
649 llvm::InitializeAllTargetMCs();
650 llvm::InitializeAllTargets();
651 llvm::InitializeAllAsmPrinters();
652
653 std::string ErrorStr;
654 StringRef Context = "dwarf streamer init";
655
656 Triple TheTriple("x86_64-linux-gnu");
657
658 // Get the target.
659 const Target *TheTarget =
660 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
661 if (!TheTarget)
662 return error(ErrorStr, Context);
663 std::string TripleName = TheTriple.getTriple();
664
665 // Create all the MC Objects.
666 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
667 if (!MRI)
668 return error(Twine("no register info for target ") + TripleName, Context);
669
670 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
671 if (!MAI)
672 return error("no asm info for target " + TripleName, Context);
673
674 MCObjectFileInfo MOFI;
675 MCContext MC(MAI.get(), MRI.get(), &MOFI);
Rafael Espindola9f929952017-08-02 20:32:26 +0000676 MOFI.InitMCObjectFileInfo(TheTriple, /*PIC*/ false, MC);
David Blaikie242b9482015-12-01 00:48:39 +0000677
Alex Bradburyb22f7512018-01-03 08:53:05 +0000678 std::unique_ptr<MCSubtargetInfo> MSTI(
679 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
680 if (!MSTI)
681 return error("no subtarget info for target " + TripleName, Context);
682
Joel Jones373d7d32016-07-25 17:18:28 +0000683 MCTargetOptions Options;
Alex Bradburyb22f7512018-01-03 08:53:05 +0000684 auto MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, Options);
David Blaikie242b9482015-12-01 00:48:39 +0000685 if (!MAB)
686 return error("no asm backend for target " + TripleName, Context);
687
688 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
689 if (!MII)
690 return error("no instr info info for target " + TripleName, Context);
691
David Blaikie242b9482015-12-01 00:48:39 +0000692 MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC);
693 if (!MCE)
694 return error("no code emitter for target " + TripleName, Context);
695
696 // Create the output file.
697 std::error_code EC;
698 raw_fd_ostream OutFile(OutputFilename, EC, sys::fs::F_None);
699 if (EC)
700 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
701
David Majnemer03e2cc32015-12-21 22:09:27 +0000702 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
David Blaikie242b9482015-12-01 00:48:39 +0000703 std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
Lang Hames2241ffa2017-10-11 23:34:47 +0000704 TheTriple, MC, std::unique_ptr<MCAsmBackend>(MAB), OutFile,
705 std::unique_ptr<MCCodeEmitter>(MCE), *MSTI, MCOptions.MCRelaxAll,
706 MCOptions.MCIncrementalLinkerCompatible,
David Blaikie242b9482015-12-01 00:48:39 +0000707 /*DWARFMustBeAtTheEnd*/ false));
708 if (!MS)
709 return error("no object streamer for target " + TripleName, Context);
710
Alexander Shaposhnikovf1f9c342017-09-02 08:19:01 +0000711 std::vector<std::string> DWOFilenames = InputFiles;
712 for (const auto &ExecFilename : ExecFilenames) {
713 auto DWOs = getDWOFilenames(ExecFilename);
714 if (!DWOs) {
715 logAllUnhandledErrors(DWOs.takeError(), errs(), "error: ");
716 return 1;
717 }
718 DWOFilenames.insert(DWOFilenames.end(),
719 std::make_move_iterator(DWOs->begin()),
720 std::make_move_iterator(DWOs->end()));
721 }
722
723 if (auto Err = write(*MS, DWOFilenames)) {
David Blaikiebc8397c2016-05-12 19:59:54 +0000724 logAllUnhandledErrors(std::move(Err), errs(), "error: ");
725 return 1;
726 }
David Blaikieddb27362016-03-01 21:24:04 +0000727
728 MS->Finish();
David Blaikiedf055252015-12-01 00:48:34 +0000729}