llvm-dwp.cpp 26 KB

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