Bug Summary

File:tools/llvm-dwp/llvm-dwp.cpp
Warning:line 143, column 5
Value stored to 'Length' is never read

Annotated Source Code

1//===-- 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//===----------------------------------------------------------------------===//
14#include "DWPError.h"
15#include "DWPStringPool.h"
16#include "llvm/ADT/MapVector.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/DebugInfo/DWARF/DWARFContext.h"
19#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
20#include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
21#include "llvm/MC/MCAsmBackend.h"
22#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCCodeEmitter.h"
24#include "llvm/MC/MCContext.h"
25#include "llvm/MC/MCInstrInfo.h"
26#include "llvm/MC/MCObjectFileInfo.h"
27#include "llvm/MC/MCRegisterInfo.h"
28#include "llvm/MC/MCStreamer.h"
29#include "llvm/MC/MCTargetOptionsCommandFlags.def"
30#include "llvm/Object/Decompressor.h"
31#include "llvm/Object/ObjectFile.h"
32#include "llvm/Support/DataExtractor.h"
33#include "llvm/Support/Error.h"
34#include "llvm/Support/FileSystem.h"
35#include "llvm/Support/MathExtras.h"
36#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/Support/Path.h"
38#include "llvm/Support/TargetRegistry.h"
39#include "llvm/Support/TargetSelect.h"
40#include "llvm/Support/raw_ostream.h"
41
42using namespace llvm;
43using namespace llvm::object;
44using namespace cl;
45
46OptionCategory DwpCategory("Specific Options");
47static list<std::string> InputFiles(Positional, ZeroOrMore,
48 desc("<input files>"), cat(DwpCategory));
49
50static list<std::string> ExecFilenames(
51 "e", ZeroOrMore,
52 desc("Specify the executable/library files to get the list of *.dwo from"),
53 value_desc("filename"), cat(DwpCategory));
54
55static opt<std::string> OutputFilename(Required, "o",
56 desc("Specify the output file."),
57 value_desc("filename"),
58 cat(DwpCategory));
59
60static void writeStringsAndOffsets(MCStreamer &Out, DWPStringPool &Strings,
61 MCSection *StrOffsetSection,
62 StringRef CurStrSection,
63 StringRef CurStrOffsetSection) {
64 // Could possibly produce an error or warning if one of these was non-null but
65 // the other was null.
66 if (CurStrSection.empty() || CurStrOffsetSection.empty())
67 return;
68
69 DenseMap<uint32_t, uint32_t> OffsetRemapping;
70
71 DataExtractor Data(CurStrSection, true, 0);
72 uint32_t LocalOffset = 0;
73 uint32_t PrevOffset = 0;
74 while (const char *s = Data.getCStr(&LocalOffset)) {
75 OffsetRemapping[PrevOffset] =
76 Strings.getOffset(s, LocalOffset - PrevOffset);
77 PrevOffset = LocalOffset;
78 }
79
80 Data = DataExtractor(CurStrOffsetSection, true, 0);
81
82 Out.SwitchSection(StrOffsetSection);
83
84 uint32_t Offset = 0;
85 uint64_t Size = CurStrOffsetSection.size();
86 while (Offset < Size) {
87 auto OldOffset = Data.getU32(&Offset);
88 auto NewOffset = OffsetRemapping[OldOffset];
89 Out.EmitIntValue(NewOffset, 4);
90 }
91}
92
93static uint32_t getCUAbbrev(StringRef Abbrev, uint64_t AbbrCode) {
94 uint64_t CurCode;
95 uint32_t Offset = 0;
96 DataExtractor AbbrevData(Abbrev, true, 0);
97 while ((CurCode = AbbrevData.getULEB128(&Offset)) != AbbrCode) {
98 // Tag
99 AbbrevData.getULEB128(&Offset);
100 // DW_CHILDREN
101 AbbrevData.getU8(&Offset);
102 // Attributes
103 while (AbbrevData.getULEB128(&Offset) | AbbrevData.getULEB128(&Offset))
104 ;
105 }
106 return Offset;
107}
108
109struct CompileUnitIdentifiers {
110 uint64_t Signature = 0;
111 const char *Name = "";
112 const char *DWOName = "";
113};
114
115static Expected<const char *>
116getIndexedString(dwarf::Form Form, DataExtractor InfoData,
117 uint32_t &InfoOffset, StringRef StrOffsets, StringRef Str) {
118 if (Form == dwarf::DW_FORM_string)
119 return InfoData.getCStr(&InfoOffset);
120 if (Form != dwarf::DW_FORM_GNU_str_index)
121 return make_error<DWPError>(
122 "string field encoded without DW_FORM_string or DW_FORM_GNU_str_index");
123 auto StrIndex = InfoData.getULEB128(&InfoOffset);
124 DataExtractor StrOffsetsData(StrOffsets, true, 0);
125 uint32_t StrOffsetsOffset = 4 * StrIndex;
126 uint32_t StrOffset = StrOffsetsData.getU32(&StrOffsetsOffset);
127 DataExtractor StrData(Str, true, 0);
128 return StrData.getCStr(&StrOffset);
129}
130
131static Expected<CompileUnitIdentifiers> getCUIdentifiers(StringRef Abbrev,
132 StringRef Info,
133 StringRef StrOffsets,
134 StringRef Str) {
135 uint32_t Offset = 0;
136 DataExtractor InfoData(Info, true, 0);
137 dwarf::DwarfFormat Format = dwarf::DwarfFormat::DWARF32;
138 uint64_t Length = InfoData.getU32(&Offset);
139 // If the length is 0xffffffff, then this indictes that this is a DWARF 64
140 // stream and the length is actually encoded into a 64 bit value that follows.
141 if (Length == 0xffffffffU) {
142 Format = dwarf::DwarfFormat::DWARF64;
143 Length = InfoData.getU64(&Offset);
Value stored to 'Length' is never read
144 }
145 uint16_t Version = InfoData.getU16(&Offset);
146 InfoData.getU32(&Offset); // Abbrev offset (should be zero)
147 uint8_t AddrSize = InfoData.getU8(&Offset);
148
149 uint32_t AbbrCode = InfoData.getULEB128(&Offset);
150
151 DataExtractor AbbrevData(Abbrev, true, 0);
152 uint32_t AbbrevOffset = getCUAbbrev(Abbrev, AbbrCode);
153 auto Tag = static_cast<dwarf::Tag>(AbbrevData.getULEB128(&AbbrevOffset));
154 if (Tag != dwarf::DW_TAG_compile_unit)
155 return make_error<DWPError>("top level DIE is not a compile unit");
156 // DW_CHILDREN
157 AbbrevData.getU8(&AbbrevOffset);
158 uint32_t Name;
159 dwarf::Form Form;
160 CompileUnitIdentifiers ID;
161 while ((Name = AbbrevData.getULEB128(&AbbrevOffset)) |
162 (Form = static_cast<dwarf::Form>(AbbrevData.getULEB128(&AbbrevOffset))) &&
163 (Name != 0 || Form != 0)) {
164 switch (Name) {
165 case dwarf::DW_AT_name: {
166 Expected<const char *> EName =
167 getIndexedString(Form, InfoData, Offset, StrOffsets, Str);
168 if (!EName)
169 return EName.takeError();
170 ID.Name = *EName;
171 break;
172 }
173 case dwarf::DW_AT_GNU_dwo_name: {
174 Expected<const char *> EName =
175 getIndexedString(Form, InfoData, Offset, StrOffsets, Str);
176 if (!EName)
177 return EName.takeError();
178 ID.DWOName = *EName;
179 break;
180 }
181 case dwarf::DW_AT_GNU_dwo_id:
182 ID.Signature = InfoData.getU64(&Offset);
183 break;
184 default:
185 DWARFFormValue::skipValue(Form, InfoData, &Offset,
186 DWARFFormParams({Version, AddrSize, Format}));
187 }
188 }
189 return ID;
190}
191
192struct UnitIndexEntry {
193 DWARFUnitIndex::Entry::SectionContribution Contributions[8];
194 std::string Name;
195 std::string DWOName;
196 StringRef DWPName;
197};
198
199static StringRef getSubsection(StringRef Section,
200 const DWARFUnitIndex::Entry &Entry,
201 DWARFSectionKind Kind) {
202 const auto *Off = Entry.getOffset(Kind);
203 if (!Off)
204 return StringRef();
205 return Section.substr(Off->Offset, Off->Length);
206}
207
208static void addAllTypesFromDWP(
209 MCStreamer &Out, MapVector<uint64_t, UnitIndexEntry> &TypeIndexEntries,
210 const DWARFUnitIndex &TUIndex, MCSection *OutputTypes, StringRef Types,
211 const UnitIndexEntry &TUEntry, uint32_t &TypesOffset) {
212 Out.SwitchSection(OutputTypes);
213 for (const DWARFUnitIndex::Entry &E : TUIndex.getRows()) {
214 auto *I = E.getOffsets();
215 if (!I)
216 continue;
217 auto P = TypeIndexEntries.insert(std::make_pair(E.getSignature(), TUEntry));
218 if (!P.second)
219 continue;
220 auto &Entry = P.first->second;
221 // Zero out the debug_info contribution
222 Entry.Contributions[0] = {};
223 for (auto Kind : TUIndex.getColumnKinds()) {
224 auto &C = Entry.Contributions[Kind - DW_SECT_INFO];
225 C.Offset += I->Offset;
226 C.Length = I->Length;
227 ++I;
228 }
229 auto &C = Entry.Contributions[DW_SECT_TYPES - DW_SECT_INFO];
230 Out.EmitBytes(Types.substr(
231 C.Offset - TUEntry.Contributions[DW_SECT_TYPES - DW_SECT_INFO].Offset,
232 C.Length));
233 C.Offset = TypesOffset;
234 TypesOffset += C.Length;
235 }
236}
237
238static void addAllTypes(MCStreamer &Out,
239 MapVector<uint64_t, UnitIndexEntry> &TypeIndexEntries,
240 MCSection *OutputTypes,
241 const std::vector<StringRef> &TypesSections,
242 const UnitIndexEntry &CUEntry, uint32_t &TypesOffset) {
243 for (StringRef Types : TypesSections) {
244 Out.SwitchSection(OutputTypes);
245 uint32_t Offset = 0;
246 DataExtractor Data(Types, true, 0);
247 while (Data.isValidOffset(Offset)) {
248 UnitIndexEntry Entry = CUEntry;
249 // Zero out the debug_info contribution
250 Entry.Contributions[0] = {};
251 auto &C = Entry.Contributions[DW_SECT_TYPES - DW_SECT_INFO];
252 C.Offset = TypesOffset;
253 auto PrevOffset = Offset;
254 // Length of the unit, including the 4 byte length field.
255 C.Length = Data.getU32(&Offset) + 4;
256
257 Data.getU16(&Offset); // Version
258 Data.getU32(&Offset); // Abbrev offset
259 Data.getU8(&Offset); // Address size
260 auto Signature = Data.getU64(&Offset);
261 Offset = PrevOffset + C.Length;
262
263 auto P = TypeIndexEntries.insert(std::make_pair(Signature, Entry));
264 if (!P.second)
265 continue;
266
267 Out.EmitBytes(Types.substr(PrevOffset, C.Length));
268 TypesOffset += C.Length;
269 }
270 }
271}
272
273static void
274writeIndexTable(MCStreamer &Out, ArrayRef<unsigned> ContributionOffsets,
275 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries,
276 uint32_t DWARFUnitIndex::Entry::SectionContribution::*Field) {
277 for (const auto &E : IndexEntries)
278 for (size_t i = 0; i != array_lengthof(E.second.Contributions); ++i)
279 if (ContributionOffsets[i])
280 Out.EmitIntValue(E.second.Contributions[i].*Field, 4);
281}
282
283static void
284writeIndex(MCStreamer &Out, MCSection *Section,
285 ArrayRef<unsigned> ContributionOffsets,
286 const MapVector<uint64_t, UnitIndexEntry> &IndexEntries) {
287 if (IndexEntries.empty())
288 return;
289
290 unsigned Columns = 0;
291 for (auto &C : ContributionOffsets)
292 if (C)
293 ++Columns;
294
295 std::vector<unsigned> Buckets(NextPowerOf2(3 * IndexEntries.size() / 2));
296 uint64_t Mask = Buckets.size() - 1;
297 size_t i = 0;
298 for (const auto &P : IndexEntries) {
299 auto S = P.first;
300 auto H = S & Mask;
301 auto HP = ((S >> 32) & Mask) | 1;
302 while (Buckets[H]) {
303 assert(S != IndexEntries.begin()[Buckets[H] - 1].first &&(static_cast <bool> (S != IndexEntries.begin()[Buckets[
H] - 1].first && "Duplicate unit") ? void (0) : __assert_fail
("S != IndexEntries.begin()[Buckets[H] - 1].first && \"Duplicate unit\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/llvm-dwp/llvm-dwp.cpp"
, 304, __extension__ __PRETTY_FUNCTION__))
304 "Duplicate unit")(static_cast <bool> (S != IndexEntries.begin()[Buckets[
H] - 1].first && "Duplicate unit") ? void (0) : __assert_fail
("S != IndexEntries.begin()[Buckets[H] - 1].first && \"Duplicate unit\""
, "/build/llvm-toolchain-snapshot-6.0~svn320940/tools/llvm-dwp/llvm-dwp.cpp"
, 304, __extension__ __PRETTY_FUNCTION__))
;
305 H = (H + HP) & Mask;
306 }
307 Buckets[H] = i + 1;
308 ++i;
309 }
310
311 Out.SwitchSection(Section);
312 Out.EmitIntValue(2, 4); // Version
313 Out.EmitIntValue(Columns, 4); // Columns
314 Out.EmitIntValue(IndexEntries.size(), 4); // Num Units
315 Out.EmitIntValue(Buckets.size(), 4); // Num Buckets
316
317 // Write the signatures.
318 for (const auto &I : Buckets)
319 Out.EmitIntValue(I ? IndexEntries.begin()[I - 1].first : 0, 8);
320
321 // Write the indexes.
322 for (const auto &I : Buckets)
323 Out.EmitIntValue(I, 4);
324
325 // Write the column headers (which sections will appear in the table)
326 for (size_t i = 0; i != ContributionOffsets.size(); ++i)
327 if (ContributionOffsets[i])
328 Out.EmitIntValue(i + DW_SECT_INFO, 4);
329
330 // Write the offsets.
331 writeIndexTable(Out, ContributionOffsets, IndexEntries,
332 &DWARFUnitIndex::Entry::SectionContribution::Offset);
333
334 // Write the lengths.
335 writeIndexTable(Out, ContributionOffsets, IndexEntries,
336 &DWARFUnitIndex::Entry::SectionContribution::Length);
337}
338
339std::string buildDWODescription(StringRef Name, StringRef DWPName, StringRef DWOName) {
340 std::string Text = "\'";
341 Text += Name;
342 Text += '\'';
343 if (!DWPName.empty()) {
344 Text += " (from ";
345 if (!DWOName.empty()) {
346 Text += '\'';
347 Text += DWOName;
348 Text += "' in ";
349 }
350 Text += '\'';
351 Text += DWPName;
352 Text += "')";
353 }
354 return Text;
355}
356
357static Error createError(StringRef Name, Error E) {
358 return make_error<DWPError>(
359 ("failure while decompressing compressed section: '" + Name + "', " +
360 llvm::toString(std::move(E)))
361 .str());
362}
363
364static Error
365handleCompressedSection(std::deque<SmallString<32>> &UncompressedSections,
366 StringRef &Name, StringRef &Contents) {
367 if (!Decompressor::isGnuStyle(Name))
368 return Error::success();
369
370 Expected<Decompressor> Dec =
371 Decompressor::create(Name, Contents, false /*IsLE*/, false /*Is64Bit*/);
372 if (!Dec)
373 return createError(Name, Dec.takeError());
374
375 UncompressedSections.emplace_back();
376 if (Error E = Dec->resizeAndDecompress(UncompressedSections.back()))
377 return createError(Name, std::move(E));
378
379 Name = Name.substr(2); // Drop ".z"
380 Contents = UncompressedSections.back();
381 return Error::success();
382}
383
384static Error handleSection(
385 const StringMap<std::pair<MCSection *, DWARFSectionKind>> &KnownSections,
386 const MCSection *StrSection, const MCSection *StrOffsetSection,
387 const MCSection *TypesSection, const MCSection *CUIndexSection,
388 const MCSection *TUIndexSection, const SectionRef &Section, MCStreamer &Out,
389 std::deque<SmallString<32>> &UncompressedSections,
390 uint32_t (&ContributionOffsets)[8], UnitIndexEntry &CurEntry,
391 StringRef &CurStrSection, StringRef &CurStrOffsetSection,
392 std::vector<StringRef> &CurTypesSection, StringRef &InfoSection,
393 StringRef &AbbrevSection, StringRef &CurCUIndexSection,
394 StringRef &CurTUIndexSection) {
395 if (Section.isBSS())
396 return Error::success();
397
398 if (Section.isVirtual())
399 return Error::success();
400
401 StringRef Name;
402 if (std::error_code Err = Section.getName(Name))
403 return errorCodeToError(Err);
404
405 StringRef Contents;
406 if (auto Err = Section.getContents(Contents))
407 return errorCodeToError(Err);
408
409 if (auto Err = handleCompressedSection(UncompressedSections, Name, Contents))
410 return Err;
411
412 Name = Name.substr(Name.find_first_not_of("._"));
413
414 auto SectionPair = KnownSections.find(Name);
415 if (SectionPair == KnownSections.end())
416 return Error::success();
417
418 if (DWARFSectionKind Kind = SectionPair->second.second) {
419 auto Index = Kind - DW_SECT_INFO;
420 if (Kind != DW_SECT_TYPES) {
421 CurEntry.Contributions[Index].Offset = ContributionOffsets[Index];
422 ContributionOffsets[Index] +=
423 (CurEntry.Contributions[Index].Length = Contents.size());
424 }
425
426 switch (Kind) {
427 case DW_SECT_INFO:
428 InfoSection = Contents;
429 break;
430 case DW_SECT_ABBREV:
431 AbbrevSection = Contents;
432 break;
433 default:
434 break;
435 }
436 }
437
438 MCSection *OutSection = SectionPair->second.first;
439 if (OutSection == StrOffsetSection)
440 CurStrOffsetSection = Contents;
441 else if (OutSection == StrSection)
442 CurStrSection = Contents;
443 else if (OutSection == TypesSection)
444 CurTypesSection.push_back(Contents);
445 else if (OutSection == CUIndexSection)
446 CurCUIndexSection = Contents;
447 else if (OutSection == TUIndexSection)
448 CurTUIndexSection = Contents;
449 else {
450 Out.SwitchSection(OutSection);
451 Out.EmitBytes(Contents);
452 }
453 return Error::success();
454}
455
456static Error
457buildDuplicateError(const std::pair<uint64_t, UnitIndexEntry> &PrevE,
458 const CompileUnitIdentifiers &ID, StringRef DWPName) {
459 return make_error<DWPError>(
460 std::string("Duplicate DWO ID (") + utohexstr(PrevE.first) + ") in " +
461 buildDWODescription(PrevE.second.Name, PrevE.second.DWPName,
462 PrevE.second.DWOName) +
463 " and " + buildDWODescription(ID.Name, DWPName, ID.DWOName));
464}
465
466static Expected<SmallVector<std::string, 16>>
467getDWOFilenames(StringRef ExecFilename) {
468 auto ErrOrObj = object::ObjectFile::createObjectFile(ExecFilename);
469 if (!ErrOrObj)
470 return ErrOrObj.takeError();
471
472 const ObjectFile &Obj = *ErrOrObj.get().getBinary();
473 std::unique_ptr<DWARFContext> DWARFCtx = DWARFContext::create(Obj);
474
475 SmallVector<std::string, 16> DWOPaths;
476 for (const auto &CU : DWARFCtx->compile_units()) {
477 const DWARFDie &Die = CU->getUnitDIE();
478 std::string DWOName = dwarf::toString(
479 Die.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
480 if (DWOName.empty())
481 continue;
482 std::string DWOCompDir =
483 dwarf::toString(Die.find(dwarf::DW_AT_comp_dir), "");
484 if (!DWOCompDir.empty()) {
485 SmallString<16> DWOPath;
486 sys::path::append(DWOPath, DWOCompDir, DWOName);
487 DWOPaths.emplace_back(DWOPath.data(), DWOPath.size());
488 } else {
489 DWOPaths.push_back(std::move(DWOName));
490 }
491 }
492 return std::move(DWOPaths);
493}
494
495static Error write(MCStreamer &Out, ArrayRef<std::string> Inputs) {
496 const auto &MCOFI = *Out.getContext().getObjectFileInfo();
497 MCSection *const StrSection = MCOFI.getDwarfStrDWOSection();
498 MCSection *const StrOffsetSection = MCOFI.getDwarfStrOffDWOSection();
499 MCSection *const TypesSection = MCOFI.getDwarfTypesDWOSection();
500 MCSection *const CUIndexSection = MCOFI.getDwarfCUIndexSection();
501 MCSection *const TUIndexSection = MCOFI.getDwarfTUIndexSection();
502 const StringMap<std::pair<MCSection *, DWARFSectionKind>> KnownSections = {
503 {"debug_info.dwo", {MCOFI.getDwarfInfoDWOSection(), DW_SECT_INFO}},
504 {"debug_types.dwo", {MCOFI.getDwarfTypesDWOSection(), DW_SECT_TYPES}},
505 {"debug_str_offsets.dwo", {StrOffsetSection, DW_SECT_STR_OFFSETS}},
506 {"debug_str.dwo", {StrSection, static_cast<DWARFSectionKind>(0)}},
507 {"debug_loc.dwo", {MCOFI.getDwarfLocDWOSection(), DW_SECT_LOC}},
508 {"debug_line.dwo", {MCOFI.getDwarfLineDWOSection(), DW_SECT_LINE}},
509 {"debug_abbrev.dwo", {MCOFI.getDwarfAbbrevDWOSection(), DW_SECT_ABBREV}},
510 {"debug_cu_index", {CUIndexSection, static_cast<DWARFSectionKind>(0)}},
511 {"debug_tu_index", {TUIndexSection, static_cast<DWARFSectionKind>(0)}}};
512
513 MapVector<uint64_t, UnitIndexEntry> IndexEntries;
514 MapVector<uint64_t, UnitIndexEntry> TypeIndexEntries;
515
516 uint32_t ContributionOffsets[8] = {};
517
518 DWPStringPool Strings(Out, StrSection);
519
520 SmallVector<OwningBinary<object::ObjectFile>, 128> Objects;
521 Objects.reserve(Inputs.size());
522
523 std::deque<SmallString<32>> UncompressedSections;
524
525 for (const auto &Input : Inputs) {
526 auto ErrOrObj = object::ObjectFile::createObjectFile(Input);
527 if (!ErrOrObj)
528 return ErrOrObj.takeError();
529
530 auto &Obj = *ErrOrObj->getBinary();
531 Objects.push_back(std::move(*ErrOrObj));
532
533 UnitIndexEntry CurEntry = {};
534
535 StringRef CurStrSection;
536 StringRef CurStrOffsetSection;
537 std::vector<StringRef> CurTypesSection;
538 StringRef InfoSection;
539 StringRef AbbrevSection;
540 StringRef CurCUIndexSection;
541 StringRef CurTUIndexSection;
542
543 for (const auto &Section : Obj.sections())
544 if (auto Err = handleSection(
545 KnownSections, StrSection, StrOffsetSection, TypesSection,
546 CUIndexSection, TUIndexSection, Section, Out,
547 UncompressedSections, ContributionOffsets, CurEntry,
548 CurStrSection, CurStrOffsetSection, CurTypesSection, InfoSection,
549 AbbrevSection, CurCUIndexSection, CurTUIndexSection))
550 return Err;
551
552 if (InfoSection.empty())
553 continue;
554
555 writeStringsAndOffsets(Out, Strings, StrOffsetSection, CurStrSection,
556 CurStrOffsetSection);
557
558 if (CurCUIndexSection.empty()) {
559 Expected<CompileUnitIdentifiers> EID = getCUIdentifiers(
560 AbbrevSection, InfoSection, CurStrOffsetSection, CurStrSection);
561 if (!EID)
562 return EID.takeError();
563 const auto &ID = *EID;
564 auto P = IndexEntries.insert(std::make_pair(ID.Signature, CurEntry));
565 if (!P.second)
566 return buildDuplicateError(*P.first, ID, "");
567 P.first->second.Name = ID.Name;
568 P.first->second.DWOName = ID.DWOName;
569 addAllTypes(Out, TypeIndexEntries, TypesSection, CurTypesSection,
570 CurEntry, ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO]);
571 continue;
572 }
573
574 DWARFUnitIndex CUIndex(DW_SECT_INFO);
575 DataExtractor CUIndexData(CurCUIndexSection, Obj.isLittleEndian(), 0);
576 if (!CUIndex.parse(CUIndexData))
577 return make_error<DWPError>("Failed to parse cu_index");
578
579 for (const DWARFUnitIndex::Entry &E : CUIndex.getRows()) {
580 auto *I = E.getOffsets();
581 if (!I)
582 continue;
583 auto P = IndexEntries.insert(std::make_pair(E.getSignature(), CurEntry));
584 Expected<CompileUnitIdentifiers> EID = getCUIdentifiers(
585 getSubsection(AbbrevSection, E, DW_SECT_ABBREV),
586 getSubsection(InfoSection, E, DW_SECT_INFO),
587 getSubsection(CurStrOffsetSection, E, DW_SECT_STR_OFFSETS),
588 CurStrSection);
589 if (!EID)
590 return EID.takeError();
591 const auto &ID = *EID;
592 if (!P.second)
593 return buildDuplicateError(*P.first, ID, Input);
594 auto &NewEntry = P.first->second;
595 NewEntry.Name = ID.Name;
596 NewEntry.DWOName = ID.DWOName;
597 NewEntry.DWPName = Input;
598 for (auto Kind : CUIndex.getColumnKinds()) {
599 auto &C = NewEntry.Contributions[Kind - DW_SECT_INFO];
600 C.Offset += I->Offset;
601 C.Length = I->Length;
602 ++I;
603 }
604 }
605
606 if (!CurTypesSection.empty()) {
607 if (CurTypesSection.size() != 1)
608 return make_error<DWPError>("multiple type unit sections in .dwp file");
609 DWARFUnitIndex TUIndex(DW_SECT_TYPES);
610 DataExtractor TUIndexData(CurTUIndexSection, Obj.isLittleEndian(), 0);
611 if (!TUIndex.parse(TUIndexData))
612 return make_error<DWPError>("Failed to parse tu_index");
613 addAllTypesFromDWP(Out, TypeIndexEntries, TUIndex, TypesSection,
614 CurTypesSection.front(), CurEntry,
615 ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO]);
616 }
617 }
618
619 // Lie about there being no info contributions so the TU index only includes
620 // the type unit contribution
621 ContributionOffsets[0] = 0;
622 writeIndex(Out, MCOFI.getDwarfTUIndexSection(), ContributionOffsets,
623 TypeIndexEntries);
624
625 // Lie about the type contribution
626 ContributionOffsets[DW_SECT_TYPES - DW_SECT_INFO] = 0;
627 // Unlie about the info contribution
628 ContributionOffsets[0] = 1;
629
630 writeIndex(Out, MCOFI.getDwarfCUIndexSection(), ContributionOffsets,
631 IndexEntries);
632
633 return Error::success();
634}
635
636static int error(const Twine &Error, const Twine &Context) {
637 errs() << Twine("while processing ") + Context + ":\n";
638 errs() << Twine("error: ") + Error + "\n";
639 return 1;
640}
641
642int main(int argc, char **argv) {
643
644 ParseCommandLineOptions(argc, argv, "merge split dwarf (.dwo) files");
645
646 llvm::InitializeAllTargetInfos();
647 llvm::InitializeAllTargetMCs();
648 llvm::InitializeAllTargets();
649 llvm::InitializeAllAsmPrinters();
650
651 std::string ErrorStr;
652 StringRef Context = "dwarf streamer init";
653
654 Triple TheTriple("x86_64-linux-gnu");
655
656 // Get the target.
657 const Target *TheTarget =
658 TargetRegistry::lookupTarget("", TheTriple, ErrorStr);
659 if (!TheTarget)
660 return error(ErrorStr, Context);
661 std::string TripleName = TheTriple.getTriple();
662
663 // Create all the MC Objects.
664 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
665 if (!MRI)
666 return error(Twine("no register info for target ") + TripleName, Context);
667
668 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
669 if (!MAI)
670 return error("no asm info for target " + TripleName, Context);
671
672 MCObjectFileInfo MOFI;
673 MCContext MC(MAI.get(), MRI.get(), &MOFI);
674 MOFI.InitMCObjectFileInfo(TheTriple, /*PIC*/ false, MC);
675
676 MCTargetOptions Options;
677 auto MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "", Options);
678 if (!MAB)
679 return error("no asm backend for target " + TripleName, Context);
680
681 std::unique_ptr<MCInstrInfo> MII(TheTarget->createMCInstrInfo());
682 if (!MII)
683 return error("no instr info info for target " + TripleName, Context);
684
685 std::unique_ptr<MCSubtargetInfo> MSTI(
686 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
687 if (!MSTI)
688 return error("no subtarget info for target " + TripleName, Context);
689
690 MCCodeEmitter *MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, MC);
691 if (!MCE)
692 return error("no code emitter for target " + TripleName, Context);
693
694 // Create the output file.
695 std::error_code EC;
696 raw_fd_ostream OutFile(OutputFilename, EC, sys::fs::F_None);
697 if (EC)
698 return error(Twine(OutputFilename) + ": " + EC.message(), Context);
699
700 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
701 std::unique_ptr<MCStreamer> MS(TheTarget->createMCObjectStreamer(
702 TheTriple, MC, std::unique_ptr<MCAsmBackend>(MAB), OutFile,
703 std::unique_ptr<MCCodeEmitter>(MCE), *MSTI, MCOptions.MCRelaxAll,
704 MCOptions.MCIncrementalLinkerCompatible,
705 /*DWARFMustBeAtTheEnd*/ false));
706 if (!MS)
707 return error("no object streamer for target " + TripleName, Context);
708
709 std::vector<std::string> DWOFilenames = InputFiles;
710 for (const auto &ExecFilename : ExecFilenames) {
711 auto DWOs = getDWOFilenames(ExecFilename);
712 if (!DWOs) {
713 logAllUnhandledErrors(DWOs.takeError(), errs(), "error: ");
714 return 1;
715 }
716 DWOFilenames.insert(DWOFilenames.end(),
717 std::make_move_iterator(DWOs->begin()),
718 std::make_move_iterator(DWOs->end()));
719 }
720
721 if (auto Err = write(*MS, DWOFilenames)) {
722 logAllUnhandledErrors(std::move(Err), errs(), "error: ");
723 return 1;
724 }
725
726 MS->Finish();
727}