DWARFStreamer.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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/DebugInfo/DWARF/DWARFDebugMacro.h"
  14. #include "llvm/MC/MCAsmBackend.h"
  15. #include "llvm/MC/MCCodeEmitter.h"
  16. #include "llvm/MC/MCDwarf.h"
  17. #include "llvm/MC/MCObjectWriter.h"
  18. #include "llvm/MC/MCSection.h"
  19. #include "llvm/MC/MCStreamer.h"
  20. #include "llvm/MC/MCSubtargetInfo.h"
  21. #include "llvm/MC/MCTargetOptions.h"
  22. #include "llvm/MC/MCTargetOptionsCommandFlags.h"
  23. #include "llvm/MC/TargetRegistry.h"
  24. #include "llvm/Support/FormatVariadic.h"
  25. #include "llvm/Support/LEB128.h"
  26. #include "llvm/Target/TargetOptions.h"
  27. namespace llvm {
  28. bool DwarfStreamer::init(Triple TheTriple,
  29. StringRef Swift5ReflectionSegmentName) {
  30. std::string ErrorStr;
  31. std::string TripleName;
  32. StringRef Context = "dwarf streamer init";
  33. // Get the target.
  34. const Target *TheTarget =
  35. TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
  36. if (!TheTarget)
  37. return error(ErrorStr, Context), false;
  38. TripleName = TheTriple.getTriple();
  39. // Create all the MC Objects.
  40. MRI.reset(TheTarget->createMCRegInfo(TripleName));
  41. if (!MRI)
  42. return error(Twine("no register info for target ") + TripleName, Context),
  43. false;
  44. MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
  45. MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
  46. if (!MAI)
  47. return error("no asm info for target " + TripleName, Context), false;
  48. MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
  49. if (!MSTI)
  50. return error("no subtarget info for target " + TripleName, Context), false;
  51. MC.reset(new MCContext(TheTriple, MAI.get(), MRI.get(), MSTI.get(), nullptr,
  52. nullptr, true, Swift5ReflectionSegmentName));
  53. MOFI.reset(TheTarget->createMCObjectFileInfo(*MC, /*PIC=*/false, false));
  54. MC->setObjectFileInfo(MOFI.get());
  55. MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, MCOptions);
  56. if (!MAB)
  57. return error("no asm backend for target " + TripleName, Context), false;
  58. MII.reset(TheTarget->createMCInstrInfo());
  59. if (!MII)
  60. return error("no instr info info for target " + TripleName, Context), false;
  61. MCE = TheTarget->createMCCodeEmitter(*MII, *MC);
  62. if (!MCE)
  63. return error("no code emitter for target " + TripleName, Context), false;
  64. switch (OutFileType) {
  65. case OutputFileType::Assembly: {
  66. MIP = TheTarget->createMCInstPrinter(TheTriple, MAI->getAssemblerDialect(),
  67. *MAI, *MII, *MRI);
  68. MS = TheTarget->createAsmStreamer(
  69. *MC, std::make_unique<formatted_raw_ostream>(OutFile), true, true, MIP,
  70. std::unique_ptr<MCCodeEmitter>(MCE), std::unique_ptr<MCAsmBackend>(MAB),
  71. true);
  72. break;
  73. }
  74. case OutputFileType::Object: {
  75. MS = TheTarget->createMCObjectStreamer(
  76. TheTriple, *MC, std::unique_ptr<MCAsmBackend>(MAB),
  77. MAB->createObjectWriter(OutFile), std::unique_ptr<MCCodeEmitter>(MCE),
  78. *MSTI, MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
  79. /*DWARFMustBeAtTheEnd*/ false);
  80. break;
  81. }
  82. }
  83. if (!MS)
  84. return error("no object streamer for target " + TripleName, Context), false;
  85. // Finally create the AsmPrinter we'll use to emit the DIEs.
  86. TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
  87. std::nullopt));
  88. if (!TM)
  89. return error("no target machine for target " + TripleName, Context), false;
  90. Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
  91. if (!Asm)
  92. return error("no asm printer for target " + TripleName, Context), false;
  93. Asm->setDwarfUsesRelocationsAcrossSections(false);
  94. RangesSectionSize = 0;
  95. LocSectionSize = 0;
  96. LineSectionSize = 0;
  97. FrameSectionSize = 0;
  98. DebugInfoSectionSize = 0;
  99. MacInfoSectionSize = 0;
  100. MacroSectionSize = 0;
  101. return true;
  102. }
  103. void DwarfStreamer::finish() { MS->finish(); }
  104. void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
  105. MS->switchSection(MOFI->getDwarfInfoSection());
  106. MC->setDwarfVersion(DwarfVersion);
  107. }
  108. /// Emit the compilation unit header for \p Unit in the debug_info section.
  109. ///
  110. /// A Dwarf 4 section header is encoded as:
  111. /// uint32_t Unit length (omitting this field)
  112. /// uint16_t Version
  113. /// uint32_t Abbreviation table offset
  114. /// uint8_t Address size
  115. /// Leading to a total of 11 bytes.
  116. ///
  117. /// A Dwarf 5 section header is encoded as:
  118. /// uint32_t Unit length (omitting this field)
  119. /// uint16_t Version
  120. /// uint8_t Unit type
  121. /// uint8_t Address size
  122. /// uint32_t Abbreviation table offset
  123. /// Leading to a total of 12 bytes.
  124. void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit,
  125. unsigned DwarfVersion) {
  126. switchToDebugInfoSection(DwarfVersion);
  127. /// The start of the unit within its section.
  128. Unit.setLabelBegin(Asm->createTempSymbol("cu_begin"));
  129. Asm->OutStreamer->emitLabel(Unit.getLabelBegin());
  130. // Emit size of content not including length itself. The size has already
  131. // been computed in CompileUnit::computeOffsets(). Subtract 4 to that size to
  132. // account for the length field.
  133. Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
  134. Asm->emitInt16(DwarfVersion);
  135. if (DwarfVersion >= 5) {
  136. Asm->emitInt8(dwarf::DW_UT_compile);
  137. Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize());
  138. // We share one abbreviations table across all units so it's always at the
  139. // start of the section.
  140. Asm->emitInt32(0);
  141. DebugInfoSectionSize += 12;
  142. } else {
  143. // We share one abbreviations table across all units so it's always at the
  144. // start of the section.
  145. Asm->emitInt32(0);
  146. Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize());
  147. DebugInfoSectionSize += 11;
  148. }
  149. // Remember this CU.
  150. EmittedUnits.push_back({Unit.getUniqueID(), Unit.getLabelBegin()});
  151. }
  152. /// Emit the \p Abbrevs array as the shared abbreviation table
  153. /// for the linked Dwarf file.
  154. void DwarfStreamer::emitAbbrevs(
  155. const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs,
  156. unsigned DwarfVersion) {
  157. MS->switchSection(MOFI->getDwarfAbbrevSection());
  158. MC->setDwarfVersion(DwarfVersion);
  159. Asm->emitDwarfAbbrevs(Abbrevs);
  160. }
  161. /// Recursively emit the DIE tree rooted at \p Die.
  162. void DwarfStreamer::emitDIE(DIE &Die) {
  163. MS->switchSection(MOFI->getDwarfInfoSection());
  164. Asm->emitDwarfDIE(Die);
  165. DebugInfoSectionSize += Die.getSize();
  166. }
  167. /// Emit contents of section SecName From Obj.
  168. void DwarfStreamer::emitSectionContents(StringRef SecData, StringRef SecName) {
  169. MCSection *Section =
  170. StringSwitch<MCSection *>(SecName)
  171. .Case("debug_line", MC->getObjectFileInfo()->getDwarfLineSection())
  172. .Case("debug_loc", MC->getObjectFileInfo()->getDwarfLocSection())
  173. .Case("debug_ranges",
  174. MC->getObjectFileInfo()->getDwarfRangesSection())
  175. .Case("debug_frame", MC->getObjectFileInfo()->getDwarfFrameSection())
  176. .Case("debug_aranges",
  177. MC->getObjectFileInfo()->getDwarfARangesSection())
  178. .Default(nullptr);
  179. if (Section) {
  180. MS->switchSection(Section);
  181. MS->emitBytes(SecData);
  182. }
  183. }
  184. /// Emit DIE containing warnings.
  185. void DwarfStreamer::emitPaperTrailWarningsDie(DIE &Die) {
  186. switchToDebugInfoSection(/* Version */ 2);
  187. auto &Asm = getAsmPrinter();
  188. Asm.emitInt32(11 + Die.getSize() - 4);
  189. Asm.emitInt16(2);
  190. Asm.emitInt32(0);
  191. Asm.emitInt8(MC->getTargetTriple().isArch64Bit() ? 8 : 4);
  192. DebugInfoSectionSize += 11;
  193. emitDIE(Die);
  194. }
  195. /// Emit the debug_str section stored in \p Pool.
  196. void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
  197. Asm->OutStreamer->switchSection(MOFI->getDwarfStrSection());
  198. std::vector<DwarfStringPoolEntryRef> Entries = Pool.getEntriesForEmission();
  199. for (auto Entry : Entries) {
  200. // Emit the string itself.
  201. Asm->OutStreamer->emitBytes(Entry.getString());
  202. // Emit a null terminator.
  203. Asm->emitInt8(0);
  204. }
  205. #if 0
  206. if (DwarfVersion >= 5) {
  207. // Emit an empty string offset section.
  208. Asm->OutStreamer->switchSection(MOFI->getDwarfStrOffSection());
  209. Asm->emitDwarfUnitLength(4, "Length of String Offsets Set");
  210. Asm->emitInt16(DwarfVersion);
  211. Asm->emitInt16(0);
  212. }
  213. #endif
  214. }
  215. void DwarfStreamer::emitDebugNames(
  216. AccelTable<DWARF5AccelTableStaticData> &Table) {
  217. if (EmittedUnits.empty())
  218. return;
  219. // Build up data structures needed to emit this section.
  220. std::vector<MCSymbol *> CompUnits;
  221. DenseMap<unsigned, size_t> UniqueIdToCuMap;
  222. unsigned Id = 0;
  223. for (auto &CU : EmittedUnits) {
  224. CompUnits.push_back(CU.LabelBegin);
  225. // We might be omitting CUs, so we need to remap them.
  226. UniqueIdToCuMap[CU.ID] = Id++;
  227. }
  228. Asm->OutStreamer->switchSection(MOFI->getDwarfDebugNamesSection());
  229. emitDWARF5AccelTable(
  230. Asm.get(), Table, CompUnits,
  231. [&UniqueIdToCuMap](const DWARF5AccelTableStaticData &Entry) {
  232. return UniqueIdToCuMap[Entry.getCUIndex()];
  233. });
  234. }
  235. void DwarfStreamer::emitAppleNamespaces(
  236. AccelTable<AppleAccelTableStaticOffsetData> &Table) {
  237. Asm->OutStreamer->switchSection(MOFI->getDwarfAccelNamespaceSection());
  238. auto *SectionBegin = Asm->createTempSymbol("namespac_begin");
  239. Asm->OutStreamer->emitLabel(SectionBegin);
  240. emitAppleAccelTable(Asm.get(), Table, "namespac", SectionBegin);
  241. }
  242. void DwarfStreamer::emitAppleNames(
  243. AccelTable<AppleAccelTableStaticOffsetData> &Table) {
  244. Asm->OutStreamer->switchSection(MOFI->getDwarfAccelNamesSection());
  245. auto *SectionBegin = Asm->createTempSymbol("names_begin");
  246. Asm->OutStreamer->emitLabel(SectionBegin);
  247. emitAppleAccelTable(Asm.get(), Table, "names", SectionBegin);
  248. }
  249. void DwarfStreamer::emitAppleObjc(
  250. AccelTable<AppleAccelTableStaticOffsetData> &Table) {
  251. Asm->OutStreamer->switchSection(MOFI->getDwarfAccelObjCSection());
  252. auto *SectionBegin = Asm->createTempSymbol("objc_begin");
  253. Asm->OutStreamer->emitLabel(SectionBegin);
  254. emitAppleAccelTable(Asm.get(), Table, "objc", SectionBegin);
  255. }
  256. void DwarfStreamer::emitAppleTypes(
  257. AccelTable<AppleAccelTableStaticTypeData> &Table) {
  258. Asm->OutStreamer->switchSection(MOFI->getDwarfAccelTypesSection());
  259. auto *SectionBegin = Asm->createTempSymbol("types_begin");
  260. Asm->OutStreamer->emitLabel(SectionBegin);
  261. emitAppleAccelTable(Asm.get(), Table, "types", SectionBegin);
  262. }
  263. /// Emit the swift_ast section stored in \p Buffers.
  264. void DwarfStreamer::emitSwiftAST(StringRef Buffer) {
  265. MCSection *SwiftASTSection = MOFI->getDwarfSwiftASTSection();
  266. SwiftASTSection->setAlignment(Align(32));
  267. MS->switchSection(SwiftASTSection);
  268. MS->emitBytes(Buffer);
  269. }
  270. void DwarfStreamer::emitSwiftReflectionSection(
  271. llvm::binaryformat::Swift5ReflectionSectionKind ReflSectionKind,
  272. StringRef Buffer, uint32_t Alignment, uint32_t Size) {
  273. MCSection *ReflectionSection =
  274. MOFI->getSwift5ReflectionSection(ReflSectionKind);
  275. if (ReflectionSection == nullptr)
  276. return;
  277. ReflectionSection->setAlignment(Align(Alignment));
  278. MS->switchSection(ReflectionSection);
  279. MS->emitBytes(Buffer);
  280. }
  281. void DwarfStreamer::emitDwarfDebugArangesTable(
  282. const CompileUnit &Unit, const AddressRanges &LinkedRanges) {
  283. unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
  284. // Make .debug_aranges to be current section.
  285. MS->switchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
  286. // Emit Header.
  287. MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
  288. MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
  289. unsigned HeaderSize =
  290. sizeof(int32_t) + // Size of contents (w/o this field
  291. sizeof(int16_t) + // DWARF ARange version number
  292. sizeof(int32_t) + // Offset of CU in the .debug_info section
  293. sizeof(int8_t) + // Pointer Size (in bytes)
  294. sizeof(int8_t); // Segment Size (in bytes)
  295. unsigned TupleSize = AddressSize * 2;
  296. unsigned Padding = offsetToAlignment(HeaderSize, Align(TupleSize));
  297. Asm->emitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
  298. Asm->OutStreamer->emitLabel(BeginLabel);
  299. Asm->emitInt16(dwarf::DW_ARANGES_VERSION); // Version number
  300. Asm->emitInt32(Unit.getStartOffset()); // Corresponding unit's offset
  301. Asm->emitInt8(AddressSize); // Address size
  302. Asm->emitInt8(0); // Segment size
  303. Asm->OutStreamer->emitFill(Padding, 0x0);
  304. // Emit linked ranges.
  305. for (const AddressRange &Range : LinkedRanges) {
  306. MS->emitIntValue(Range.start(), AddressSize);
  307. MS->emitIntValue(Range.end() - Range.start(), AddressSize);
  308. }
  309. // Emit terminator.
  310. Asm->OutStreamer->emitIntValue(0, AddressSize);
  311. Asm->OutStreamer->emitIntValue(0, AddressSize);
  312. Asm->OutStreamer->emitLabel(EndLabel);
  313. }
  314. void DwarfStreamer::emitDwarfDebugRangesTableFragment(
  315. const CompileUnit &Unit, const AddressRanges &LinkedRanges) {
  316. unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
  317. // Make .debug_ranges to be current section.
  318. MS->switchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
  319. // Emit ranges.
  320. uint64_t BaseAddress = 0;
  321. if (std::optional<uint64_t> LowPC = Unit.getLowPc())
  322. BaseAddress = *LowPC;
  323. for (const AddressRange &Range : LinkedRanges) {
  324. MS->emitIntValue(Range.start() - BaseAddress, AddressSize);
  325. MS->emitIntValue(Range.end() - BaseAddress, AddressSize);
  326. RangesSectionSize += AddressSize;
  327. RangesSectionSize += AddressSize;
  328. }
  329. // Add the terminator entry.
  330. MS->emitIntValue(0, AddressSize);
  331. MS->emitIntValue(0, AddressSize);
  332. RangesSectionSize += AddressSize;
  333. RangesSectionSize += AddressSize;
  334. }
  335. /// Emit the debug_aranges contribution of a unit and
  336. /// if \p DoDebugRanges is true the debug_range contents for a
  337. /// compile_unit level DW_AT_ranges attribute (Which are basically the
  338. /// same thing with a different base address).
  339. /// Just aggregate all the ranges gathered inside that unit.
  340. void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
  341. bool DoDebugRanges) {
  342. const RangesTy &FunctionRanges = Unit.getFunctionRanges();
  343. // Linked addresses might end up in a different order.
  344. // Build linked address ranges.
  345. AddressRanges LinkedRanges;
  346. for (size_t Idx = 0; Idx < FunctionRanges.size(); Idx++)
  347. LinkedRanges.insert(
  348. {FunctionRanges[Idx].first.start() + FunctionRanges[Idx].second,
  349. FunctionRanges[Idx].first.end() + FunctionRanges[Idx].second});
  350. if (!FunctionRanges.empty())
  351. emitDwarfDebugArangesTable(Unit, LinkedRanges);
  352. if (DoDebugRanges)
  353. emitDwarfDebugRangesTableFragment(Unit, LinkedRanges);
  354. }
  355. /// Emit location lists for \p Unit and update attributes to point to the new
  356. /// entries.
  357. void DwarfStreamer::emitLocationsForUnit(
  358. const CompileUnit &Unit, DWARFContext &Dwarf,
  359. std::function<void(StringRef, SmallVectorImpl<uint8_t> &)> ProcessExpr) {
  360. const auto &Attributes = Unit.getLocationAttributes();
  361. if (Attributes.empty())
  362. return;
  363. MS->switchSection(MC->getObjectFileInfo()->getDwarfLocSection());
  364. unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
  365. uint64_t BaseAddressMarker = (AddressSize == 8)
  366. ? std::numeric_limits<uint64_t>::max()
  367. : std::numeric_limits<uint32_t>::max();
  368. const DWARFSection &InputSec = Dwarf.getDWARFObj().getLocSection();
  369. DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
  370. DWARFUnit &OrigUnit = Unit.getOrigUnit();
  371. auto OrigUnitDie = OrigUnit.getUnitDIE(false);
  372. int64_t UnitPcOffset = 0;
  373. if (auto OrigLowPc =
  374. dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc))) {
  375. assert(Unit.getLowPc());
  376. UnitPcOffset = int64_t(*OrigLowPc) - *Unit.getLowPc();
  377. }
  378. SmallVector<uint8_t, 32> Buffer;
  379. for (const auto &Attr : Attributes) {
  380. uint64_t Offset = Attr.first.get();
  381. Attr.first.set(LocSectionSize);
  382. // This is the quantity to add to the old location address to get
  383. // the correct address for the new one.
  384. int64_t LocPcOffset = Attr.second + UnitPcOffset;
  385. while (Data.isValidOffset(Offset)) {
  386. uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
  387. uint64_t High = Data.getUnsigned(&Offset, AddressSize);
  388. LocSectionSize += 2 * AddressSize;
  389. // End of list entry.
  390. if (Low == 0 && High == 0) {
  391. Asm->OutStreamer->emitIntValue(0, AddressSize);
  392. Asm->OutStreamer->emitIntValue(0, AddressSize);
  393. break;
  394. }
  395. // Base address selection entry.
  396. if (Low == BaseAddressMarker) {
  397. Asm->OutStreamer->emitIntValue(BaseAddressMarker, AddressSize);
  398. Asm->OutStreamer->emitIntValue(High + Attr.second, AddressSize);
  399. LocPcOffset = 0;
  400. continue;
  401. }
  402. // Location list entry.
  403. Asm->OutStreamer->emitIntValue(Low + LocPcOffset, AddressSize);
  404. Asm->OutStreamer->emitIntValue(High + LocPcOffset, AddressSize);
  405. uint64_t Length = Data.getU16(&Offset);
  406. Asm->OutStreamer->emitIntValue(Length, 2);
  407. // Copy the bytes into to the buffer, process them, emit them.
  408. Buffer.reserve(Length);
  409. Buffer.resize(0);
  410. StringRef Input = InputSec.Data.substr(Offset, Length);
  411. ProcessExpr(Input, Buffer);
  412. Asm->OutStreamer->emitBytes(
  413. StringRef((const char *)Buffer.data(), Length));
  414. Offset += Length;
  415. LocSectionSize += Length + 2;
  416. }
  417. }
  418. }
  419. void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
  420. StringRef PrologueBytes,
  421. unsigned MinInstLength,
  422. std::vector<DWARFDebugLine::Row> &Rows,
  423. unsigned PointerSize) {
  424. // Switch to the section where the table will be emitted into.
  425. MS->switchSection(MC->getObjectFileInfo()->getDwarfLineSection());
  426. MCSymbol *LineStartSym = MC->createTempSymbol();
  427. MCSymbol *LineEndSym = MC->createTempSymbol();
  428. // The first 4 bytes is the total length of the information for this
  429. // compilation unit (not including these 4 bytes for the length).
  430. Asm->emitLabelDifference(LineEndSym, LineStartSym, 4);
  431. Asm->OutStreamer->emitLabel(LineStartSym);
  432. // Copy Prologue.
  433. MS->emitBytes(PrologueBytes);
  434. LineSectionSize += PrologueBytes.size() + 4;
  435. SmallString<128> EncodingBuffer;
  436. raw_svector_ostream EncodingOS(EncodingBuffer);
  437. if (Rows.empty()) {
  438. // We only have the dummy entry, dsymutil emits an entry with a 0
  439. // address in that case.
  440. MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
  441. EncodingOS);
  442. MS->emitBytes(EncodingOS.str());
  443. LineSectionSize += EncodingBuffer.size();
  444. MS->emitLabel(LineEndSym);
  445. return;
  446. }
  447. // Line table state machine fields
  448. unsigned FileNum = 1;
  449. unsigned LastLine = 1;
  450. unsigned Column = 0;
  451. unsigned IsStatement = 1;
  452. unsigned Isa = 0;
  453. uint64_t Address = -1ULL;
  454. unsigned RowsSinceLastSequence = 0;
  455. for (DWARFDebugLine::Row &Row : Rows) {
  456. int64_t AddressDelta;
  457. if (Address == -1ULL) {
  458. MS->emitIntValue(dwarf::DW_LNS_extended_op, 1);
  459. MS->emitULEB128IntValue(PointerSize + 1);
  460. MS->emitIntValue(dwarf::DW_LNE_set_address, 1);
  461. MS->emitIntValue(Row.Address.Address, PointerSize);
  462. LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
  463. AddressDelta = 0;
  464. } else {
  465. AddressDelta = (Row.Address.Address - Address) / MinInstLength;
  466. }
  467. // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable.
  468. // We should find a way to share this code, but the current compatibility
  469. // requirement with classic dsymutil makes it hard. Revisit that once this
  470. // requirement is dropped.
  471. if (FileNum != Row.File) {
  472. FileNum = Row.File;
  473. MS->emitIntValue(dwarf::DW_LNS_set_file, 1);
  474. MS->emitULEB128IntValue(FileNum);
  475. LineSectionSize += 1 + getULEB128Size(FileNum);
  476. }
  477. if (Column != Row.Column) {
  478. Column = Row.Column;
  479. MS->emitIntValue(dwarf::DW_LNS_set_column, 1);
  480. MS->emitULEB128IntValue(Column);
  481. LineSectionSize += 1 + getULEB128Size(Column);
  482. }
  483. // FIXME: We should handle the discriminator here, but dsymutil doesn't
  484. // consider it, thus ignore it for now.
  485. if (Isa != Row.Isa) {
  486. Isa = Row.Isa;
  487. MS->emitIntValue(dwarf::DW_LNS_set_isa, 1);
  488. MS->emitULEB128IntValue(Isa);
  489. LineSectionSize += 1 + getULEB128Size(Isa);
  490. }
  491. if (IsStatement != Row.IsStmt) {
  492. IsStatement = Row.IsStmt;
  493. MS->emitIntValue(dwarf::DW_LNS_negate_stmt, 1);
  494. LineSectionSize += 1;
  495. }
  496. if (Row.BasicBlock) {
  497. MS->emitIntValue(dwarf::DW_LNS_set_basic_block, 1);
  498. LineSectionSize += 1;
  499. }
  500. if (Row.PrologueEnd) {
  501. MS->emitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
  502. LineSectionSize += 1;
  503. }
  504. if (Row.EpilogueBegin) {
  505. MS->emitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
  506. LineSectionSize += 1;
  507. }
  508. int64_t LineDelta = int64_t(Row.Line) - LastLine;
  509. if (!Row.EndSequence) {
  510. MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
  511. MS->emitBytes(EncodingOS.str());
  512. LineSectionSize += EncodingBuffer.size();
  513. EncodingBuffer.resize(0);
  514. Address = Row.Address.Address;
  515. LastLine = Row.Line;
  516. RowsSinceLastSequence++;
  517. } else {
  518. if (LineDelta) {
  519. MS->emitIntValue(dwarf::DW_LNS_advance_line, 1);
  520. MS->emitSLEB128IntValue(LineDelta);
  521. LineSectionSize += 1 + getSLEB128Size(LineDelta);
  522. }
  523. if (AddressDelta) {
  524. MS->emitIntValue(dwarf::DW_LNS_advance_pc, 1);
  525. MS->emitULEB128IntValue(AddressDelta);
  526. LineSectionSize += 1 + getULEB128Size(AddressDelta);
  527. }
  528. MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(),
  529. 0, EncodingOS);
  530. MS->emitBytes(EncodingOS.str());
  531. LineSectionSize += EncodingBuffer.size();
  532. EncodingBuffer.resize(0);
  533. Address = -1ULL;
  534. LastLine = FileNum = IsStatement = 1;
  535. RowsSinceLastSequence = Column = Isa = 0;
  536. }
  537. }
  538. if (RowsSinceLastSequence) {
  539. MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
  540. EncodingOS);
  541. MS->emitBytes(EncodingOS.str());
  542. LineSectionSize += EncodingBuffer.size();
  543. EncodingBuffer.resize(0);
  544. }
  545. MS->emitLabel(LineEndSym);
  546. }
  547. /// Copy the debug_line over to the updated binary while unobfuscating the file
  548. /// names and directories.
  549. void DwarfStreamer::translateLineTable(DataExtractor Data, uint64_t Offset) {
  550. MS->switchSection(MC->getObjectFileInfo()->getDwarfLineSection());
  551. StringRef Contents = Data.getData();
  552. // We have to deconstruct the line table header, because it contains to
  553. // length fields that will need to be updated when we change the length of
  554. // the files and directories in there.
  555. unsigned UnitLength = Data.getU32(&Offset);
  556. uint64_t UnitEnd = Offset + UnitLength;
  557. MCSymbol *BeginLabel = MC->createTempSymbol();
  558. MCSymbol *EndLabel = MC->createTempSymbol();
  559. unsigned Version = Data.getU16(&Offset);
  560. if (Version > 5) {
  561. warn("Unsupported line table version: dropping contents and not "
  562. "unobfsucating line table.");
  563. return;
  564. }
  565. Asm->emitLabelDifference(EndLabel, BeginLabel, 4);
  566. Asm->OutStreamer->emitLabel(BeginLabel);
  567. Asm->emitInt16(Version);
  568. LineSectionSize += 6;
  569. MCSymbol *HeaderBeginLabel = MC->createTempSymbol();
  570. MCSymbol *HeaderEndLabel = MC->createTempSymbol();
  571. Asm->emitLabelDifference(HeaderEndLabel, HeaderBeginLabel, 4);
  572. Asm->OutStreamer->emitLabel(HeaderBeginLabel);
  573. Offset += 4;
  574. LineSectionSize += 4;
  575. uint64_t AfterHeaderLengthOffset = Offset;
  576. // Skip to the directories.
  577. Offset += (Version >= 4) ? 5 : 4;
  578. unsigned OpcodeBase = Data.getU8(&Offset);
  579. Offset += OpcodeBase - 1;
  580. Asm->OutStreamer->emitBytes(Contents.slice(AfterHeaderLengthOffset, Offset));
  581. LineSectionSize += Offset - AfterHeaderLengthOffset;
  582. // Offset points to the first directory.
  583. while (const char *Dir = Data.getCStr(&Offset)) {
  584. if (Dir[0] == 0)
  585. break;
  586. StringRef Translated = Translator(Dir);
  587. Asm->OutStreamer->emitBytes(Translated);
  588. Asm->emitInt8(0);
  589. LineSectionSize += Translated.size() + 1;
  590. }
  591. Asm->emitInt8(0);
  592. LineSectionSize += 1;
  593. while (const char *File = Data.getCStr(&Offset)) {
  594. if (File[0] == 0)
  595. break;
  596. StringRef Translated = Translator(File);
  597. Asm->OutStreamer->emitBytes(Translated);
  598. Asm->emitInt8(0);
  599. LineSectionSize += Translated.size() + 1;
  600. uint64_t OffsetBeforeLEBs = Offset;
  601. Asm->emitULEB128(Data.getULEB128(&Offset));
  602. Asm->emitULEB128(Data.getULEB128(&Offset));
  603. Asm->emitULEB128(Data.getULEB128(&Offset));
  604. LineSectionSize += Offset - OffsetBeforeLEBs;
  605. }
  606. Asm->emitInt8(0);
  607. LineSectionSize += 1;
  608. Asm->OutStreamer->emitLabel(HeaderEndLabel);
  609. // Copy the actual line table program over.
  610. Asm->OutStreamer->emitBytes(Contents.slice(Offset, UnitEnd));
  611. LineSectionSize += UnitEnd - Offset;
  612. Asm->OutStreamer->emitLabel(EndLabel);
  613. Offset = UnitEnd;
  614. }
  615. /// Emit the pubnames or pubtypes section contribution for \p
  616. /// Unit into \p Sec. The data is provided in \p Names.
  617. void DwarfStreamer::emitPubSectionForUnit(
  618. MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
  619. const std::vector<CompileUnit::AccelInfo> &Names) {
  620. if (Names.empty())
  621. return;
  622. // Start the dwarf pubnames section.
  623. Asm->OutStreamer->switchSection(Sec);
  624. MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
  625. MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
  626. bool HeaderEmitted = false;
  627. // Emit the pubnames for this compilation unit.
  628. for (const auto &Name : Names) {
  629. if (Name.SkipPubSection)
  630. continue;
  631. if (!HeaderEmitted) {
  632. // Emit the header.
  633. Asm->emitLabelDifference(EndLabel, BeginLabel, 4); // Length
  634. Asm->OutStreamer->emitLabel(BeginLabel);
  635. Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
  636. Asm->emitInt32(Unit.getStartOffset()); // Unit offset
  637. Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
  638. HeaderEmitted = true;
  639. }
  640. Asm->emitInt32(Name.Die->getOffset());
  641. // Emit the string itself.
  642. Asm->OutStreamer->emitBytes(Name.Name.getString());
  643. // Emit a null terminator.
  644. Asm->emitInt8(0);
  645. }
  646. if (!HeaderEmitted)
  647. return;
  648. Asm->emitInt32(0); // End marker.
  649. Asm->OutStreamer->emitLabel(EndLabel);
  650. }
  651. /// Emit .debug_pubnames for \p Unit.
  652. void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
  653. emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
  654. "names", Unit, Unit.getPubnames());
  655. }
  656. /// Emit .debug_pubtypes for \p Unit.
  657. void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
  658. emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
  659. "types", Unit, Unit.getPubtypes());
  660. }
  661. /// Emit a CIE into the debug_frame section.
  662. void DwarfStreamer::emitCIE(StringRef CIEBytes) {
  663. MS->switchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
  664. MS->emitBytes(CIEBytes);
  665. FrameSectionSize += CIEBytes.size();
  666. }
  667. /// Emit a FDE into the debug_frame section. \p FDEBytes
  668. /// contains the FDE data without the length, CIE offset and address
  669. /// which will be replaced with the parameter values.
  670. void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
  671. uint64_t Address, StringRef FDEBytes) {
  672. MS->switchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
  673. MS->emitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
  674. MS->emitIntValue(CIEOffset, 4);
  675. MS->emitIntValue(Address, AddrSize);
  676. MS->emitBytes(FDEBytes);
  677. FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
  678. }
  679. void DwarfStreamer::emitMacroTables(DWARFContext *Context,
  680. const Offset2UnitMap &UnitMacroMap,
  681. OffsetsStringPool &StringPool) {
  682. assert(Context != nullptr && "Empty DWARF context");
  683. // Check for .debug_macinfo table.
  684. if (const DWARFDebugMacro *Table = Context->getDebugMacinfo()) {
  685. MS->switchSection(MC->getObjectFileInfo()->getDwarfMacinfoSection());
  686. emitMacroTableImpl(Table, UnitMacroMap, StringPool, MacInfoSectionSize);
  687. }
  688. // Check for .debug_macro table.
  689. if (const DWARFDebugMacro *Table = Context->getDebugMacro()) {
  690. MS->switchSection(MC->getObjectFileInfo()->getDwarfMacroSection());
  691. emitMacroTableImpl(Table, UnitMacroMap, StringPool, MacroSectionSize);
  692. }
  693. }
  694. void DwarfStreamer::emitMacroTableImpl(const DWARFDebugMacro *MacroTable,
  695. const Offset2UnitMap &UnitMacroMap,
  696. OffsetsStringPool &StringPool,
  697. uint64_t &OutOffset) {
  698. bool DefAttributeIsReported = false;
  699. bool UndefAttributeIsReported = false;
  700. bool ImportAttributeIsReported = false;
  701. for (const DWARFDebugMacro::MacroList &List : MacroTable->MacroLists) {
  702. Offset2UnitMap::const_iterator UnitIt = UnitMacroMap.find(List.Offset);
  703. if (UnitIt == UnitMacroMap.end()) {
  704. warn(formatv(
  705. "couldn`t find compile unit for the macro table with offset = {0:x}",
  706. List.Offset));
  707. continue;
  708. }
  709. // Skip macro table if the unit was not cloned.
  710. DIE *OutputUnitDIE = UnitIt->second->getOutputUnitDIE();
  711. if (OutputUnitDIE == nullptr)
  712. continue;
  713. // Update macro attribute of cloned compile unit with the proper offset to
  714. // the macro table.
  715. bool hasDWARFv5Header = false;
  716. for (auto &V : OutputUnitDIE->values()) {
  717. if (V.getAttribute() == dwarf::DW_AT_macro_info) {
  718. V = DIEValue(V.getAttribute(), V.getForm(), DIEInteger(OutOffset));
  719. break;
  720. } else if (V.getAttribute() == dwarf::DW_AT_macros) {
  721. hasDWARFv5Header = true;
  722. V = DIEValue(V.getAttribute(), V.getForm(), DIEInteger(OutOffset));
  723. break;
  724. }
  725. }
  726. // Write DWARFv5 header.
  727. if (hasDWARFv5Header) {
  728. // Write header version.
  729. MS->emitIntValue(List.Header.Version, sizeof(List.Header.Version));
  730. OutOffset += sizeof(List.Header.Version);
  731. uint8_t Flags = List.Header.Flags;
  732. // Check for OPCODE_OPERANDS_TABLE.
  733. if (Flags &
  734. DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE) {
  735. Flags &= ~DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE;
  736. warn("opcode_operands_table is not supported yet.");
  737. }
  738. // Check for DEBUG_LINE_OFFSET.
  739. std::optional<uint64_t> StmtListOffset;
  740. if (Flags & DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET) {
  741. // Get offset to the line table from the cloned compile unit.
  742. for (auto &V : OutputUnitDIE->values()) {
  743. if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
  744. StmtListOffset = V.getDIEInteger().getValue();
  745. break;
  746. }
  747. }
  748. if (!StmtListOffset) {
  749. Flags &= ~DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET;
  750. warn("couldn`t find line table for macro table.");
  751. }
  752. }
  753. // Write flags.
  754. MS->emitIntValue(Flags, sizeof(Flags));
  755. OutOffset += sizeof(Flags);
  756. // Write offset to line table.
  757. if (StmtListOffset) {
  758. MS->emitIntValue(*StmtListOffset, List.Header.getOffsetByteSize());
  759. OutOffset += List.Header.getOffsetByteSize();
  760. }
  761. }
  762. // Write macro entries.
  763. for (const DWARFDebugMacro::Entry &MacroEntry : List.Macros) {
  764. if (MacroEntry.Type == 0) {
  765. OutOffset += MS->emitULEB128IntValue(MacroEntry.Type);
  766. continue;
  767. }
  768. uint8_t MacroType = MacroEntry.Type;
  769. switch (MacroType) {
  770. default: {
  771. bool HasVendorSpecificExtension =
  772. (!hasDWARFv5Header && MacroType == dwarf::DW_MACINFO_vendor_ext) ||
  773. (hasDWARFv5Header && (MacroType >= dwarf::DW_MACRO_lo_user &&
  774. MacroType <= dwarf::DW_MACRO_hi_user));
  775. if (HasVendorSpecificExtension) {
  776. // Write macinfo type.
  777. MS->emitIntValue(MacroType, 1);
  778. OutOffset++;
  779. // Write vendor extension constant.
  780. OutOffset += MS->emitULEB128IntValue(MacroEntry.ExtConstant);
  781. // Write vendor extension string.
  782. StringRef String = MacroEntry.ExtStr;
  783. MS->emitBytes(String);
  784. MS->emitIntValue(0, 1);
  785. OutOffset += String.size() + 1;
  786. } else
  787. warn("unknown macro type. skip.");
  788. } break;
  789. // debug_macro and debug_macinfo share some common encodings.
  790. // DW_MACRO_define == DW_MACINFO_define
  791. // DW_MACRO_undef == DW_MACINFO_undef
  792. // DW_MACRO_start_file == DW_MACINFO_start_file
  793. // DW_MACRO_end_file == DW_MACINFO_end_file
  794. // For readibility/uniformity we are using DW_MACRO_*.
  795. case dwarf::DW_MACRO_define:
  796. case dwarf::DW_MACRO_undef: {
  797. // Write macinfo type.
  798. MS->emitIntValue(MacroType, 1);
  799. OutOffset++;
  800. // Write source line.
  801. OutOffset += MS->emitULEB128IntValue(MacroEntry.Line);
  802. // Write macro string.
  803. StringRef String = MacroEntry.MacroStr;
  804. MS->emitBytes(String);
  805. MS->emitIntValue(0, 1);
  806. OutOffset += String.size() + 1;
  807. } break;
  808. case dwarf::DW_MACRO_define_strp:
  809. case dwarf::DW_MACRO_undef_strp:
  810. case dwarf::DW_MACRO_define_strx:
  811. case dwarf::DW_MACRO_undef_strx: {
  812. assert(UnitIt->second->getOrigUnit().getVersion() >= 5);
  813. // DW_MACRO_*_strx forms are not supported currently.
  814. // Convert to *_strp.
  815. switch (MacroType) {
  816. case dwarf::DW_MACRO_define_strx: {
  817. MacroType = dwarf::DW_MACRO_define_strp;
  818. if (!DefAttributeIsReported) {
  819. warn("DW_MACRO_define_strx unsupported yet. Convert to "
  820. "DW_MACRO_define_strp.");
  821. DefAttributeIsReported = true;
  822. }
  823. } break;
  824. case dwarf::DW_MACRO_undef_strx: {
  825. MacroType = dwarf::DW_MACRO_undef_strp;
  826. if (!UndefAttributeIsReported) {
  827. warn("DW_MACRO_undef_strx unsupported yet. Convert to "
  828. "DW_MACRO_undef_strp.");
  829. UndefAttributeIsReported = true;
  830. }
  831. } break;
  832. default:
  833. // Nothing to do.
  834. break;
  835. }
  836. // Write macinfo type.
  837. MS->emitIntValue(MacroType, 1);
  838. OutOffset++;
  839. // Write source line.
  840. OutOffset += MS->emitULEB128IntValue(MacroEntry.Line);
  841. // Write macro string.
  842. DwarfStringPoolEntryRef EntryRef =
  843. StringPool.getEntry(MacroEntry.MacroStr);
  844. MS->emitIntValue(EntryRef.getOffset(), List.Header.getOffsetByteSize());
  845. OutOffset += List.Header.getOffsetByteSize();
  846. break;
  847. }
  848. case dwarf::DW_MACRO_start_file: {
  849. // Write macinfo type.
  850. MS->emitIntValue(MacroType, 1);
  851. OutOffset++;
  852. // Write source line.
  853. OutOffset += MS->emitULEB128IntValue(MacroEntry.Line);
  854. // Write source file id.
  855. OutOffset += MS->emitULEB128IntValue(MacroEntry.File);
  856. } break;
  857. case dwarf::DW_MACRO_end_file: {
  858. // Write macinfo type.
  859. MS->emitIntValue(MacroType, 1);
  860. OutOffset++;
  861. } break;
  862. case dwarf::DW_MACRO_import:
  863. case dwarf::DW_MACRO_import_sup: {
  864. if (!ImportAttributeIsReported) {
  865. warn("DW_MACRO_import and DW_MACRO_import_sup are unsupported yet. "
  866. "remove.");
  867. ImportAttributeIsReported = true;
  868. }
  869. } break;
  870. }
  871. }
  872. }
  873. }
  874. } // namespace llvm