llvm-dwp.cpp 24 KB

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