llvm-dwp.cpp 24 KB

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