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