DWARFStreamer.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. //===- DwarfStreamer.cpp --------------------------------------------------===//
  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. #include "llvm/DWARFLinker/DWARFStreamer.h"
  9. #include "llvm/ADT/Triple.h"
  10. #include "llvm/CodeGen/NonRelocatableStringpool.h"
  11. #include "llvm/DWARFLinker/DWARFLinkerCompileUnit.h"
  12. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  13. #include "llvm/MC/MCAsmBackend.h"
  14. #include "llvm/MC/MCCodeEmitter.h"
  15. #include "llvm/MC/MCDwarf.h"
  16. #include "llvm/MC/MCObjectWriter.h"
  17. #include "llvm/MC/MCSection.h"
  18. #include "llvm/MC/MCStreamer.h"
  19. #include "llvm/MC/MCSubtargetInfo.h"
  20. #include "llvm/MC/MCSymbol.h"
  21. #include "llvm/MC/MCTargetOptions.h"
  22. #include "llvm/MC/MCTargetOptionsCommandFlags.h"
  23. #include "llvm/MC/TargetRegistry.h"
  24. #include "llvm/Support/LEB128.h"
  25. #include "llvm/Target/TargetOptions.h"
  26. namespace llvm {
  27. bool DwarfStreamer::init(Triple TheTriple,
  28. StringRef Swift5ReflectionSegmentName) {
  29. std::string ErrorStr;
  30. std::string TripleName;
  31. StringRef Context = "dwarf streamer init";
  32. // Get the target.
  33. const Target *TheTarget =
  34. TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
  35. if (!TheTarget)
  36. return error(ErrorStr, Context), false;
  37. TripleName = TheTriple.getTriple();
  38. // Create all the MC Objects.
  39. MRI.reset(TheTarget->createMCRegInfo(TripleName));
  40. if (!MRI)
  41. return error(Twine("no register info for target ") + TripleName, Context),
  42. false;
  43. MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
  44. MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
  45. if (!MAI)
  46. return error("no asm info for target " + TripleName, Context), false;
  47. MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
  48. if (!MSTI)
  49. return error("no subtarget info for target " + TripleName, Context), false;
  50. MC.reset(new MCContext(TheTriple, MAI.get(), MRI.get(), MSTI.get(), nullptr,
  51. nullptr, true, Swift5ReflectionSegmentName));
  52. MOFI.reset(TheTarget->createMCObjectFileInfo(*MC, /*PIC=*/false, false));
  53. MC->setObjectFileInfo(MOFI.get());
  54. MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, MCOptions);
  55. if (!MAB)
  56. return error("no asm backend for target " + TripleName, Context), false;
  57. MII.reset(TheTarget->createMCInstrInfo());
  58. if (!MII)
  59. return error("no instr info info for target " + TripleName, Context), false;
  60. MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
  61. if (!MCE)
  62. return error("no code emitter for target " + TripleName, Context), false;
  63. switch (OutFileType) {
  64. case OutputFileType::Assembly: {
  65. MIP = TheTarget->createMCInstPrinter(TheTriple, MAI->getAssemblerDialect(),
  66. *MAI, *MII, *MRI);
  67. MS = TheTarget->createAsmStreamer(
  68. *MC, std::make_unique<formatted_raw_ostream>(OutFile), true, true, MIP,
  69. std::unique_ptr<MCCodeEmitter>(MCE), std::unique_ptr<MCAsmBackend>(MAB),
  70. true);
  71. break;
  72. }
  73. case OutputFileType::Object: {
  74. MS = TheTarget->createMCObjectStreamer(
  75. TheTriple, *MC, std::unique_ptr<MCAsmBackend>(MAB),
  76. MAB->createObjectWriter(OutFile), std::unique_ptr<MCCodeEmitter>(MCE),
  77. *MSTI, MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
  78. /*DWARFMustBeAtTheEnd*/ false);
  79. break;
  80. }
  81. }
  82. if (!MS)
  83. return error("no object streamer for target " + TripleName, Context), false;
  84. // Finally create the AsmPrinter we'll use to emit the DIEs.
  85. TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
  86. None));
  87. if (!TM)
  88. return error("no target machine for target " + TripleName, Context), false;
  89. Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
  90. if (!Asm)
  91. return error("no asm printer for target " + TripleName, Context), false;
  92. RangesSectionSize = 0;
  93. LocSectionSize = 0;
  94. LineSectionSize = 0;
  95. FrameSectionSize = 0;
  96. DebugInfoSectionSize = 0;
  97. return true;
  98. }
  99. void DwarfStreamer::finish() { MS->Finish(); }
  100. void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
  101. MS->SwitchSection(MOFI->getDwarfInfoSection());
  102. MC->setDwarfVersion(DwarfVersion);
  103. }
  104. /// Emit the compilation unit header for \p Unit in the debug_info section.
  105. ///
  106. /// A Dwarf 4 section header is encoded as:
  107. /// uint32_t Unit length (omitting this field)
  108. /// uint16_t Version
  109. /// uint32_t Abbreviation table offset
  110. /// uint8_t Address size
  111. /// Leading to a total of 11 bytes.
  112. ///
  113. /// A Dwarf 5 section header is encoded as:
  114. /// uint32_t Unit length (omitting this field)
  115. /// uint16_t Version
  116. /// uint8_t Unit type
  117. /// uint8_t Address size
  118. /// uint32_t Abbreviation table offset
  119. /// Leading to a total of 12 bytes.
  120. void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit,
  121. unsigned DwarfVersion) {
  122. switchToDebugInfoSection(DwarfVersion);
  123. /// The start of the unit within its section.
  124. Unit.setLabelBegin(Asm->createTempSymbol("cu_begin"));
  125. Asm->OutStreamer->emitLabel(Unit.getLabelBegin());
  126. // Emit size of content not including length itself. The size has already
  127. // been computed in CompileUnit::computeOffsets(). Subtract 4 to that size to
  128. // account for the length field.
  129. Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
  130. Asm->emitInt16(DwarfVersion);
  131. if (DwarfVersion >= 5) {
  132. Asm->emitInt8(dwarf::DW_UT_compile);
  133. Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize());
  134. // We share one abbreviations table across all units so it's always at the
  135. // start of the section.
  136. Asm->emitInt32(0);
  137. DebugInfoSectionSize += 12;
  138. } else {
  139. // We share one abbreviations table across all units so it's always at the
  140. // start of the section.
  141. Asm->emitInt32(0);
  142. Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize());
  143. DebugInfoSectionSize += 11;
  144. }
  145. // Remember this CU.
  146. EmittedUnits.push_back({Unit.getUniqueID(), Unit.getLabelBegin()});
  147. }
  148. /// Emit the \p Abbrevs array as the shared abbreviation table
  149. /// for the linked Dwarf file.
  150. void DwarfStreamer::emitAbbrevs(
  151. const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs,
  152. unsigned DwarfVersion) {
  153. MS->SwitchSection(MOFI->getDwarfAbbrevSection());
  154. MC->setDwarfVersion(DwarfVersion);
  155. Asm->emitDwarfAbbrevs(Abbrevs);
  156. }
  157. /// Recursively emit the DIE tree rooted at \p Die.
  158. void DwarfStreamer::emitDIE(DIE &Die) {
  159. MS->SwitchSection(MOFI->getDwarfInfoSection());
  160. Asm->emitDwarfDIE(Die);
  161. DebugInfoSectionSize += Die.getSize();
  162. }
  163. /// Emit contents of section SecName From Obj.
  164. void DwarfStreamer::emitSectionContents(StringRef SecData, StringRef SecName) {
  165. MCSection *Section =
  166. StringSwitch<MCSection *>(SecName)
  167. .Case("debug_line", MC->getObjectFileInfo()->getDwarfLineSection())
  168. .Case("debug_loc", MC->getObjectFileInfo()->getDwarfLocSection())
  169. .Case("debug_ranges",
  170. MC->getObjectFileInfo()->getDwarfRangesSection())
  171. .Case("debug_frame", MC->getObjectFileInfo()->getDwarfFrameSection())
  172. .Case("debug_aranges",
  173. MC->getObjectFileInfo()->getDwarfARangesSection())
  174. .Default(nullptr);
  175. if (Section) {
  176. MS->SwitchSection(Section);
  177. MS->emitBytes(SecData);
  178. }
  179. }
  180. /// Emit DIE containing warnings.
  181. void DwarfStreamer::emitPaperTrailWarningsDie(DIE &Die) {
  182. switchToDebugInfoSection(/* Version */ 2);
  183. auto &Asm = getAsmPrinter();
  184. Asm.emitInt32(11 + Die.getSize() - 4);
  185. Asm.emitInt16(2);
  186. Asm.emitInt32(0);
  187. Asm.emitInt8(MC->getTargetTriple().isArch64Bit() ? 8 : 4);
  188. DebugInfoSectionSize += 11;
  189. emitDIE(Die);
  190. }
  191. /// Emit the debug_str section stored in \p Pool.
  192. void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
  193. Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
  194. std::vector<DwarfStringPoolEntryRef> Entries = Pool.getEntriesForEmission();
  195. for (auto Entry : Entries) {
  196. // Emit the string itself.
  197. Asm->OutStreamer->emitBytes(Entry.getString());
  198. // Emit a null terminator.
  199. Asm->emitInt8(0);
  200. }
  201. #if 0
  202. if (DwarfVersion >= 5) {
  203. // Emit an empty string offset section.
  204. Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrOffSection());
  205. Asm->emitDwarfUnitLength(4, "Length of String Offsets Set");
  206. Asm->emitInt16(DwarfVersion);
  207. Asm->emitInt16(0);
  208. }
  209. #endif
  210. }
  211. void DwarfStreamer::emitDebugNames(
  212. AccelTable<DWARF5AccelTableStaticData> &Table) {
  213. if (EmittedUnits.empty())
  214. return;
  215. // Build up data structures needed to emit this section.
  216. std::vector<MCSymbol *> CompUnits;
  217. DenseMap<unsigned, size_t> UniqueIdToCuMap;
  218. unsigned Id = 0;
  219. for (auto &CU : EmittedUnits) {
  220. CompUnits.push_back(CU.LabelBegin);
  221. // We might be omitting CUs, so we need to remap them.
  222. UniqueIdToCuMap[CU.ID] = Id++;
  223. }
  224. Asm->OutStreamer->SwitchSection(MOFI->getDwarfDebugNamesSection());
  225. emitDWARF5AccelTable(
  226. Asm.get(), Table, CompUnits,
  227. [&UniqueIdToCuMap](const DWARF5AccelTableStaticData &Entry) {
  228. return UniqueIdToCuMap[Entry.getCUIndex()];
  229. });
  230. }
  231. void DwarfStreamer::emitAppleNamespaces(
  232. AccelTable<AppleAccelTableStaticOffsetData> &Table) {
  233. Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelNamespaceSection());
  234. auto *SectionBegin = Asm->createTempSymbol("namespac_begin");
  235. Asm->OutStreamer->emitLabel(SectionBegin);
  236. emitAppleAccelTable(Asm.get(), Table, "namespac", SectionBegin);
  237. }
  238. void DwarfStreamer::emitAppleNames(
  239. AccelTable<AppleAccelTableStaticOffsetData> &Table) {
  240. Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelNamesSection());
  241. auto *SectionBegin = Asm->createTempSymbol("names_begin");
  242. Asm->OutStreamer->emitLabel(SectionBegin);
  243. emitAppleAccelTable(Asm.get(), Table, "names", SectionBegin);
  244. }
  245. void DwarfStreamer::emitAppleObjc(
  246. AccelTable<AppleAccelTableStaticOffsetData> &Table) {
  247. Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelObjCSection());
  248. auto *SectionBegin = Asm->createTempSymbol("objc_begin");
  249. Asm->OutStreamer->emitLabel(SectionBegin);
  250. emitAppleAccelTable(Asm.get(), Table, "objc", SectionBegin);
  251. }
  252. void DwarfStreamer::emitAppleTypes(
  253. AccelTable<AppleAccelTableStaticTypeData> &Table) {
  254. Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelTypesSection());
  255. auto *SectionBegin = Asm->createTempSymbol("types_begin");
  256. Asm->OutStreamer->emitLabel(SectionBegin);
  257. emitAppleAccelTable(Asm.get(), Table, "types", SectionBegin);
  258. }
  259. /// Emit the swift_ast section stored in \p Buffers.
  260. void DwarfStreamer::emitSwiftAST(StringRef Buffer) {
  261. MCSection *SwiftASTSection = MOFI->getDwarfSwiftASTSection();
  262. SwiftASTSection->setAlignment(Align(32));
  263. MS->SwitchSection(SwiftASTSection);
  264. MS->emitBytes(Buffer);
  265. }
  266. void DwarfStreamer::emitSwiftReflectionSection(
  267. llvm::binaryformat::Swift5ReflectionSectionKind ReflSectionKind,
  268. StringRef Buffer, uint32_t Alignment, uint32_t Size) {
  269. MCSection *ReflectionSection =
  270. MOFI->getSwift5ReflectionSection(ReflSectionKind);
  271. if (ReflectionSection == nullptr)
  272. return;
  273. ReflectionSection->setAlignment(Align(Alignment));
  274. MS->SwitchSection(ReflectionSection);
  275. MS->emitBytes(Buffer);
  276. }
  277. /// Emit the debug_range section contents for \p FuncRange by
  278. /// translating the original \p Entries. The debug_range section
  279. /// format is totally trivial, consisting just of pairs of address
  280. /// sized addresses describing the ranges.
  281. void DwarfStreamer::emitRangesEntries(
  282. int64_t UnitPcOffset, uint64_t OrigLowPc,
  283. const FunctionIntervals::const_iterator &FuncRange,
  284. const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
  285. unsigned AddressSize) {
  286. MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
  287. // Offset each range by the right amount.
  288. int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
  289. for (const auto &Range : Entries) {
  290. if (Range.isBaseAddressSelectionEntry(AddressSize)) {
  291. warn("unsupported base address selection operation",
  292. "emitting debug_ranges");
  293. break;
  294. }
  295. // Do not emit empty ranges.
  296. if (Range.StartAddress == Range.EndAddress)
  297. continue;
  298. // All range entries should lie in the function range.
  299. if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
  300. Range.EndAddress + OrigLowPc <= FuncRange.stop()))
  301. warn("inconsistent range data.", "emitting debug_ranges");
  302. MS->emitIntValue(Range.StartAddress + PcOffset, AddressSize);
  303. MS->emitIntValue(Range.EndAddress + PcOffset, AddressSize);
  304. RangesSectionSize += 2 * AddressSize;
  305. }
  306. // Add the terminator entry.
  307. MS->emitIntValue(0, AddressSize);
  308. MS->emitIntValue(0, AddressSize);
  309. RangesSectionSize += 2 * AddressSize;
  310. }
  311. /// Emit the debug_aranges contribution of a unit and
  312. /// if \p DoDebugRanges is true the debug_range contents for a
  313. /// compile_unit level DW_AT_ranges attribute (Which are basically the
  314. /// same thing with a different base address).
  315. /// Just aggregate all the ranges gathered inside that unit.
  316. void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
  317. bool DoDebugRanges) {
  318. unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
  319. // Gather the ranges in a vector, so that we can simplify them. The
  320. // IntervalMap will have coalesced the non-linked ranges, but here
  321. // we want to coalesce the linked addresses.
  322. std::vector<std::pair<uint64_t, uint64_t>> Ranges;
  323. const auto &FunctionRanges = Unit.getFunctionRanges();
  324. for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
  325. Range != End; ++Range)
  326. Ranges.push_back(std::make_pair(Range.start() + Range.value(),
  327. Range.stop() + Range.value()));
  328. // The object addresses where sorted, but again, the linked
  329. // addresses might end up in a different order.
  330. llvm::sort(Ranges);
  331. if (!Ranges.empty()) {
  332. MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
  333. MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
  334. MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
  335. unsigned HeaderSize =
  336. sizeof(int32_t) + // Size of contents (w/o this field
  337. sizeof(int16_t) + // DWARF ARange version number
  338. sizeof(int32_t) + // Offset of CU in the .debug_info section
  339. sizeof(int8_t) + // Pointer Size (in bytes)
  340. sizeof(int8_t); // Segment Size (in bytes)
  341. unsigned TupleSize = AddressSize * 2;
  342. unsigned Padding = offsetToAlignment(HeaderSize, Align(TupleSize));
  343. Asm->emitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
  344. Asm->OutStreamer->emitLabel(BeginLabel);
  345. Asm->emitInt16(dwarf::DW_ARANGES_VERSION); // Version number
  346. Asm->emitInt32(Unit.getStartOffset()); // Corresponding unit's offset
  347. Asm->emitInt8(AddressSize); // Address size
  348. Asm->emitInt8(0); // Segment size
  349. Asm->OutStreamer->emitFill(Padding, 0x0);
  350. for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
  351. ++Range) {
  352. uint64_t RangeStart = Range->first;
  353. MS->emitIntValue(RangeStart, AddressSize);
  354. while ((Range + 1) != End && Range->second == (Range + 1)->first)
  355. ++Range;
  356. MS->emitIntValue(Range->second - RangeStart, AddressSize);
  357. }
  358. // Emit terminator
  359. Asm->OutStreamer->emitIntValue(0, AddressSize);
  360. Asm->OutStreamer->emitIntValue(0, AddressSize);
  361. Asm->OutStreamer->emitLabel(EndLabel);
  362. }
  363. if (!DoDebugRanges)
  364. return;
  365. MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
  366. // Offset each range by the right amount.
  367. int64_t PcOffset = -Unit.getLowPc();
  368. // Emit coalesced ranges.
  369. for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
  370. MS->emitIntValue(Range->first + PcOffset, AddressSize);
  371. while (Range + 1 != End && Range->second == (Range + 1)->first)
  372. ++Range;
  373. MS->emitIntValue(Range->second + PcOffset, AddressSize);
  374. RangesSectionSize += 2 * AddressSize;
  375. }
  376. // Add the terminator entry.
  377. MS->emitIntValue(0, AddressSize);
  378. MS->emitIntValue(0, AddressSize);
  379. RangesSectionSize += 2 * AddressSize;
  380. }
  381. /// Emit location lists for \p Unit and update attributes to point to the new
  382. /// entries.
  383. void DwarfStreamer::emitLocationsForUnit(
  384. const CompileUnit &Unit, DWARFContext &Dwarf,
  385. std::function<void(StringRef, SmallVectorImpl<uint8_t> &)> ProcessExpr) {
  386. const auto &Attributes = Unit.getLocationAttributes();
  387. if (Attributes.empty())
  388. return;
  389. MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
  390. unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
  391. uint64_t BaseAddressMarker = (AddressSize == 8)
  392. ? std::numeric_limits<uint64_t>::max()
  393. : std::numeric_limits<uint32_t>::max();
  394. const DWARFSection &InputSec = Dwarf.getDWARFObj().getLocSection();
  395. DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
  396. DWARFUnit &OrigUnit = Unit.getOrigUnit();
  397. auto OrigUnitDie = OrigUnit.getUnitDIE(false);
  398. int64_t UnitPcOffset = 0;
  399. if (auto OrigLowPc = dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc)))
  400. UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc();
  401. SmallVector<uint8_t, 32> Buffer;
  402. for (const auto &Attr : Attributes) {
  403. uint64_t Offset = Attr.first.get();
  404. Attr.first.set(LocSectionSize);
  405. // This is the quantity to add to the old location address to get
  406. // the correct address for the new one.
  407. int64_t LocPcOffset = Attr.second + UnitPcOffset;
  408. while (Data.isValidOffset(Offset)) {
  409. uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
  410. uint64_t High = Data.getUnsigned(&Offset, AddressSize);
  411. LocSectionSize += 2 * AddressSize;
  412. // End of list entry.
  413. if (Low == 0 && High == 0) {
  414. Asm->OutStreamer->emitIntValue(0, AddressSize);
  415. Asm->OutStreamer->emitIntValue(0, AddressSize);
  416. break;
  417. }
  418. // Base address selection entry.
  419. if (Low == BaseAddressMarker) {
  420. Asm->OutStreamer->emitIntValue(BaseAddressMarker, AddressSize);
  421. Asm->OutStreamer->emitIntValue(High + Attr.second, AddressSize);
  422. LocPcOffset = 0;
  423. continue;
  424. }
  425. // Location list entry.
  426. Asm->OutStreamer->emitIntValue(Low + LocPcOffset, AddressSize);
  427. Asm->OutStreamer->emitIntValue(High + LocPcOffset, AddressSize);
  428. uint64_t Length = Data.getU16(&Offset);
  429. Asm->OutStreamer->emitIntValue(Length, 2);
  430. // Copy the bytes into to the buffer, process them, emit them.
  431. Buffer.reserve(Length);
  432. Buffer.resize(0);
  433. StringRef Input = InputSec.Data.substr(Offset, Length);
  434. ProcessExpr(Input, Buffer);
  435. Asm->OutStreamer->emitBytes(
  436. StringRef((const char *)Buffer.data(), Length));
  437. Offset += Length;
  438. LocSectionSize += Length + 2;
  439. }
  440. }
  441. }
  442. void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
  443. StringRef PrologueBytes,
  444. unsigned MinInstLength,
  445. std::vector<DWARFDebugLine::Row> &Rows,
  446. unsigned PointerSize) {
  447. // Switch to the section where the table will be emitted into.
  448. MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
  449. MCSymbol *LineStartSym = MC->createTempSymbol();
  450. MCSymbol *LineEndSym = MC->createTempSymbol();
  451. // The first 4 bytes is the total length of the information for this
  452. // compilation unit (not including these 4 bytes for the length).
  453. Asm->emitLabelDifference(LineEndSym, LineStartSym, 4);
  454. Asm->OutStreamer->emitLabel(LineStartSym);
  455. // Copy Prologue.
  456. MS->emitBytes(PrologueBytes);
  457. LineSectionSize += PrologueBytes.size() + 4;
  458. SmallString<128> EncodingBuffer;
  459. raw_svector_ostream EncodingOS(EncodingBuffer);
  460. if (Rows.empty()) {
  461. // We only have the dummy entry, dsymutil emits an entry with a 0
  462. // address in that case.
  463. MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
  464. EncodingOS);
  465. MS->emitBytes(EncodingOS.str());
  466. LineSectionSize += EncodingBuffer.size();
  467. MS->emitLabel(LineEndSym);
  468. return;
  469. }
  470. // Line table state machine fields
  471. unsigned FileNum = 1;
  472. unsigned LastLine = 1;
  473. unsigned Column = 0;
  474. unsigned IsStatement = 1;
  475. unsigned Isa = 0;
  476. uint64_t Address = -1ULL;
  477. unsigned RowsSinceLastSequence = 0;
  478. for (DWARFDebugLine::Row &Row : Rows) {
  479. int64_t AddressDelta;
  480. if (Address == -1ULL) {
  481. MS->emitIntValue(dwarf::DW_LNS_extended_op, 1);
  482. MS->emitULEB128IntValue(PointerSize + 1);
  483. MS->emitIntValue(dwarf::DW_LNE_set_address, 1);
  484. MS->emitIntValue(Row.Address.Address, PointerSize);
  485. LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
  486. AddressDelta = 0;
  487. } else {
  488. AddressDelta = (Row.Address.Address - Address) / MinInstLength;
  489. }
  490. // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable.
  491. // We should find a way to share this code, but the current compatibility
  492. // requirement with classic dsymutil makes it hard. Revisit that once this
  493. // requirement is dropped.
  494. if (FileNum != Row.File) {
  495. FileNum = Row.File;
  496. MS->emitIntValue(dwarf::DW_LNS_set_file, 1);
  497. MS->emitULEB128IntValue(FileNum);
  498. LineSectionSize += 1 + getULEB128Size(FileNum);
  499. }
  500. if (Column != Row.Column) {
  501. Column = Row.Column;
  502. MS->emitIntValue(dwarf::DW_LNS_set_column, 1);
  503. MS->emitULEB128IntValue(Column);
  504. LineSectionSize += 1 + getULEB128Size(Column);
  505. }
  506. // FIXME: We should handle the discriminator here, but dsymutil doesn't
  507. // consider it, thus ignore it for now.
  508. if (Isa != Row.Isa) {
  509. Isa = Row.Isa;
  510. MS->emitIntValue(dwarf::DW_LNS_set_isa, 1);
  511. MS->emitULEB128IntValue(Isa);
  512. LineSectionSize += 1 + getULEB128Size(Isa);
  513. }
  514. if (IsStatement != Row.IsStmt) {
  515. IsStatement = Row.IsStmt;
  516. MS->emitIntValue(dwarf::DW_LNS_negate_stmt, 1);
  517. LineSectionSize += 1;
  518. }
  519. if (Row.BasicBlock) {
  520. MS->emitIntValue(dwarf::DW_LNS_set_basic_block, 1);
  521. LineSectionSize += 1;
  522. }
  523. if (Row.PrologueEnd) {
  524. MS->emitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
  525. LineSectionSize += 1;
  526. }
  527. if (Row.EpilogueBegin) {
  528. MS->emitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
  529. LineSectionSize += 1;
  530. }
  531. int64_t LineDelta = int64_t(Row.Line) - LastLine;
  532. if (!Row.EndSequence) {
  533. MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
  534. MS->emitBytes(EncodingOS.str());
  535. LineSectionSize += EncodingBuffer.size();
  536. EncodingBuffer.resize(0);
  537. Address = Row.Address.Address;
  538. LastLine = Row.Line;
  539. RowsSinceLastSequence++;
  540. } else {
  541. if (LineDelta) {
  542. MS->emitIntValue(dwarf::DW_LNS_advance_line, 1);
  543. MS->emitSLEB128IntValue(LineDelta);
  544. LineSectionSize += 1 + getSLEB128Size(LineDelta);
  545. }
  546. if (AddressDelta) {
  547. MS->emitIntValue(dwarf::DW_LNS_advance_pc, 1);
  548. MS->emitULEB128IntValue(AddressDelta);
  549. LineSectionSize += 1 + getULEB128Size(AddressDelta);
  550. }
  551. MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(),
  552. 0, EncodingOS);
  553. MS->emitBytes(EncodingOS.str());
  554. LineSectionSize += EncodingBuffer.size();
  555. EncodingBuffer.resize(0);
  556. Address = -1ULL;
  557. LastLine = FileNum = IsStatement = 1;
  558. RowsSinceLastSequence = Column = Isa = 0;
  559. }
  560. }
  561. if (RowsSinceLastSequence) {
  562. MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
  563. EncodingOS);
  564. MS->emitBytes(EncodingOS.str());
  565. LineSectionSize += EncodingBuffer.size();
  566. EncodingBuffer.resize(0);
  567. }
  568. MS->emitLabel(LineEndSym);
  569. }
  570. /// Copy the debug_line over to the updated binary while unobfuscating the file
  571. /// names and directories.
  572. void DwarfStreamer::translateLineTable(DataExtractor Data, uint64_t Offset) {
  573. MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
  574. StringRef Contents = Data.getData();
  575. // We have to deconstruct the line table header, because it contains to
  576. // length fields that will need to be updated when we change the length of
  577. // the files and directories in there.
  578. unsigned UnitLength = Data.getU32(&Offset);
  579. uint64_t UnitEnd = Offset + UnitLength;
  580. MCSymbol *BeginLabel = MC->createTempSymbol();
  581. MCSymbol *EndLabel = MC->createTempSymbol();
  582. unsigned Version = Data.getU16(&Offset);
  583. if (Version > 5) {
  584. warn("Unsupported line table version: dropping contents and not "
  585. "unobfsucating line table.");
  586. return;
  587. }
  588. Asm->emitLabelDifference(EndLabel, BeginLabel, 4);
  589. Asm->OutStreamer->emitLabel(BeginLabel);
  590. Asm->emitInt16(Version);
  591. LineSectionSize += 6;
  592. MCSymbol *HeaderBeginLabel = MC->createTempSymbol();
  593. MCSymbol *HeaderEndLabel = MC->createTempSymbol();
  594. Asm->emitLabelDifference(HeaderEndLabel, HeaderBeginLabel, 4);
  595. Asm->OutStreamer->emitLabel(HeaderBeginLabel);
  596. Offset += 4;
  597. LineSectionSize += 4;
  598. uint64_t AfterHeaderLengthOffset = Offset;
  599. // Skip to the directories.
  600. Offset += (Version >= 4) ? 5 : 4;
  601. unsigned OpcodeBase = Data.getU8(&Offset);
  602. Offset += OpcodeBase - 1;
  603. Asm->OutStreamer->emitBytes(Contents.slice(AfterHeaderLengthOffset, Offset));
  604. LineSectionSize += Offset - AfterHeaderLengthOffset;
  605. // Offset points to the first directory.
  606. while (const char *Dir = Data.getCStr(&Offset)) {
  607. if (Dir[0] == 0)
  608. break;
  609. StringRef Translated = Translator(Dir);
  610. Asm->OutStreamer->emitBytes(Translated);
  611. Asm->emitInt8(0);
  612. LineSectionSize += Translated.size() + 1;
  613. }
  614. Asm->emitInt8(0);
  615. LineSectionSize += 1;
  616. while (const char *File = Data.getCStr(&Offset)) {
  617. if (File[0] == 0)
  618. break;
  619. StringRef Translated = Translator(File);
  620. Asm->OutStreamer->emitBytes(Translated);
  621. Asm->emitInt8(0);
  622. LineSectionSize += Translated.size() + 1;
  623. uint64_t OffsetBeforeLEBs = Offset;
  624. Asm->emitULEB128(Data.getULEB128(&Offset));
  625. Asm->emitULEB128(Data.getULEB128(&Offset));
  626. Asm->emitULEB128(Data.getULEB128(&Offset));
  627. LineSectionSize += Offset - OffsetBeforeLEBs;
  628. }
  629. Asm->emitInt8(0);
  630. LineSectionSize += 1;
  631. Asm->OutStreamer->emitLabel(HeaderEndLabel);
  632. // Copy the actual line table program over.
  633. Asm->OutStreamer->emitBytes(Contents.slice(Offset, UnitEnd));
  634. LineSectionSize += UnitEnd - Offset;
  635. Asm->OutStreamer->emitLabel(EndLabel);
  636. Offset = UnitEnd;
  637. }
  638. /// Emit the pubnames or pubtypes section contribution for \p
  639. /// Unit into \p Sec. The data is provided in \p Names.
  640. void DwarfStreamer::emitPubSectionForUnit(
  641. MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
  642. const std::vector<CompileUnit::AccelInfo> &Names) {
  643. if (Names.empty())
  644. return;
  645. // Start the dwarf pubnames section.
  646. Asm->OutStreamer->SwitchSection(Sec);
  647. MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
  648. MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
  649. bool HeaderEmitted = false;
  650. // Emit the pubnames for this compilation unit.
  651. for (const auto &Name : Names) {
  652. if (Name.SkipPubSection)
  653. continue;
  654. if (!HeaderEmitted) {
  655. // Emit the header.
  656. Asm->emitLabelDifference(EndLabel, BeginLabel, 4); // Length
  657. Asm->OutStreamer->emitLabel(BeginLabel);
  658. Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
  659. Asm->emitInt32(Unit.getStartOffset()); // Unit offset
  660. Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
  661. HeaderEmitted = true;
  662. }
  663. Asm->emitInt32(Name.Die->getOffset());
  664. // Emit the string itself.
  665. Asm->OutStreamer->emitBytes(Name.Name.getString());
  666. // Emit a null terminator.
  667. Asm->emitInt8(0);
  668. }
  669. if (!HeaderEmitted)
  670. return;
  671. Asm->emitInt32(0); // End marker.
  672. Asm->OutStreamer->emitLabel(EndLabel);
  673. }
  674. /// Emit .debug_pubnames for \p Unit.
  675. void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
  676. emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
  677. "names", Unit, Unit.getPubnames());
  678. }
  679. /// Emit .debug_pubtypes for \p Unit.
  680. void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
  681. emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
  682. "types", Unit, Unit.getPubtypes());
  683. }
  684. /// Emit a CIE into the debug_frame section.
  685. void DwarfStreamer::emitCIE(StringRef CIEBytes) {
  686. MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
  687. MS->emitBytes(CIEBytes);
  688. FrameSectionSize += CIEBytes.size();
  689. }
  690. /// Emit a FDE into the debug_frame section. \p FDEBytes
  691. /// contains the FDE data without the length, CIE offset and address
  692. /// which will be replaced with the parameter values.
  693. void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
  694. uint32_t Address, StringRef FDEBytes) {
  695. MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
  696. MS->emitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
  697. MS->emitIntValue(CIEOffset, 4);
  698. MS->emitIntValue(Address, AddrSize);
  699. MS->emitBytes(FDEBytes);
  700. FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
  701. }
  702. } // namespace llvm