llvm-dwp.cpp 26 KB

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