llvm-dwp.cpp 24 KB

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