Bug Summary

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