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/MCSymbol.h"
22 #include "llvm/MC/MCTargetOptions.h"
23 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Target/TargetOptions.h"
27 
28 namespace llvm {
29 
30 bool DwarfStreamer::init(Triple TheTriple) {
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   MOFI.reset(new MCObjectFileInfo);
58   MC.reset(
59       new MCContext(TheTriple, MAI.get(), MRI.get(), MOFI.get(), MSTI.get()));
60   MOFI->initMCObjectFileInfo(*MC, /*PIC=*/false);
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, *MRI, *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 
116 void DwarfStreamer::finish() { MS->Finish(); }
117 
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.
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.
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.
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.
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.
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.
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 
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 
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 
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 
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 
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.
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 
306 /// Emit the debug_range section contents for \p FuncRange by
307 /// translating the original \p Entries. The debug_range section
308 /// format is totally trivial, consisting just of pairs of address
309 /// sized addresses describing the ranges.
310 void DwarfStreamer::emitRangesEntries(
311     int64_t UnitPcOffset, uint64_t OrigLowPc,
312     const FunctionIntervals::const_iterator &FuncRange,
313     const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
314     unsigned AddressSize) {
315   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
316 
317   // Offset each range by the right amount.
318   int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
319   for (const auto &Range : Entries) {
320     if (Range.isBaseAddressSelectionEntry(AddressSize)) {
321       warn("unsupported base address selection operation",
322            "emitting debug_ranges");
323       break;
324     }
325     // Do not emit empty ranges.
326     if (Range.StartAddress == Range.EndAddress)
327       continue;
328 
329     // All range entries should lie in the function range.
330     if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
331           Range.EndAddress + OrigLowPc <= FuncRange.stop()))
332       warn("inconsistent range data.", "emitting debug_ranges");
333     MS->emitIntValue(Range.StartAddress + PcOffset, AddressSize);
334     MS->emitIntValue(Range.EndAddress + PcOffset, AddressSize);
335     RangesSectionSize += 2 * AddressSize;
336   }
337 
338   // Add the terminator entry.
339   MS->emitIntValue(0, AddressSize);
340   MS->emitIntValue(0, AddressSize);
341   RangesSectionSize += 2 * AddressSize;
342 }
343 
344 /// Emit the debug_aranges contribution of a unit and
345 /// if \p DoDebugRanges is true the debug_range contents for a
346 /// compile_unit level DW_AT_ranges attribute (Which are basically the
347 /// same thing with a different base address).
348 /// Just aggregate all the ranges gathered inside that unit.
349 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
350                                           bool DoDebugRanges) {
351   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
352   // Gather the ranges in a vector, so that we can simplify them. The
353   // IntervalMap will have coalesced the non-linked ranges, but here
354   // we want to coalesce the linked addresses.
355   std::vector<std::pair<uint64_t, uint64_t>> Ranges;
356   const auto &FunctionRanges = Unit.getFunctionRanges();
357   for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
358        Range != End; ++Range)
359     Ranges.push_back(std::make_pair(Range.start() + Range.value(),
360                                     Range.stop() + Range.value()));
361 
362   // The object addresses where sorted, but again, the linked
363   // addresses might end up in a different order.
364   llvm::sort(Ranges);
365 
366   if (!Ranges.empty()) {
367     MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
368 
369     MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
370     MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
371 
372     unsigned HeaderSize =
373         sizeof(int32_t) + // Size of contents (w/o this field
374         sizeof(int16_t) + // DWARF ARange version number
375         sizeof(int32_t) + // Offset of CU in the .debug_info section
376         sizeof(int8_t) +  // Pointer Size (in bytes)
377         sizeof(int8_t);   // Segment Size (in bytes)
378 
379     unsigned TupleSize = AddressSize * 2;
380     unsigned Padding = offsetToAlignment(HeaderSize, Align(TupleSize));
381 
382     Asm->emitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
383     Asm->OutStreamer->emitLabel(BeginLabel);
384     Asm->emitInt16(dwarf::DW_ARANGES_VERSION); // Version number
385     Asm->emitInt32(Unit.getStartOffset());     // Corresponding unit's offset
386     Asm->emitInt8(AddressSize);                // Address size
387     Asm->emitInt8(0);                          // Segment size
388 
389     Asm->OutStreamer->emitFill(Padding, 0x0);
390 
391     for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
392          ++Range) {
393       uint64_t RangeStart = Range->first;
394       MS->emitIntValue(RangeStart, AddressSize);
395       while ((Range + 1) != End && Range->second == (Range + 1)->first)
396         ++Range;
397       MS->emitIntValue(Range->second - RangeStart, AddressSize);
398     }
399 
400     // Emit terminator
401     Asm->OutStreamer->emitIntValue(0, AddressSize);
402     Asm->OutStreamer->emitIntValue(0, AddressSize);
403     Asm->OutStreamer->emitLabel(EndLabel);
404   }
405 
406   if (!DoDebugRanges)
407     return;
408 
409   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
410   // Offset each range by the right amount.
411   int64_t PcOffset = -Unit.getLowPc();
412   // Emit coalesced ranges.
413   for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
414     MS->emitIntValue(Range->first + PcOffset, AddressSize);
415     while (Range + 1 != End && Range->second == (Range + 1)->first)
416       ++Range;
417     MS->emitIntValue(Range->second + PcOffset, AddressSize);
418     RangesSectionSize += 2 * AddressSize;
419   }
420 
421   // Add the terminator entry.
422   MS->emitIntValue(0, AddressSize);
423   MS->emitIntValue(0, AddressSize);
424   RangesSectionSize += 2 * AddressSize;
425 }
426 
427 /// Emit location lists for \p Unit and update attributes to point to the new
428 /// entries.
429 void DwarfStreamer::emitLocationsForUnit(
430     const CompileUnit &Unit, DWARFContext &Dwarf,
431     std::function<void(StringRef, SmallVectorImpl<uint8_t> &)> ProcessExpr) {
432   const auto &Attributes = Unit.getLocationAttributes();
433 
434   if (Attributes.empty())
435     return;
436 
437   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
438 
439   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
440   uint64_t BaseAddressMarker = (AddressSize == 8)
441                                    ? std::numeric_limits<uint64_t>::max()
442                                    : std::numeric_limits<uint32_t>::max();
443   const DWARFSection &InputSec = Dwarf.getDWARFObj().getLocSection();
444   DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
445   DWARFUnit &OrigUnit = Unit.getOrigUnit();
446   auto OrigUnitDie = OrigUnit.getUnitDIE(false);
447   int64_t UnitPcOffset = 0;
448   if (auto OrigLowPc = dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc)))
449     UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc();
450 
451   SmallVector<uint8_t, 32> Buffer;
452   for (const auto &Attr : Attributes) {
453     uint64_t Offset = Attr.first.get();
454     Attr.first.set(LocSectionSize);
455     // This is the quantity to add to the old location address to get
456     // the correct address for the new one.
457     int64_t LocPcOffset = Attr.second + UnitPcOffset;
458     while (Data.isValidOffset(Offset)) {
459       uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
460       uint64_t High = Data.getUnsigned(&Offset, AddressSize);
461       LocSectionSize += 2 * AddressSize;
462       // End of list entry.
463       if (Low == 0 && High == 0) {
464         Asm->OutStreamer->emitIntValue(0, AddressSize);
465         Asm->OutStreamer->emitIntValue(0, AddressSize);
466         break;
467       }
468       // Base address selection entry.
469       if (Low == BaseAddressMarker) {
470         Asm->OutStreamer->emitIntValue(BaseAddressMarker, AddressSize);
471         Asm->OutStreamer->emitIntValue(High + Attr.second, AddressSize);
472         LocPcOffset = 0;
473         continue;
474       }
475       // Location list entry.
476       Asm->OutStreamer->emitIntValue(Low + LocPcOffset, AddressSize);
477       Asm->OutStreamer->emitIntValue(High + LocPcOffset, AddressSize);
478       uint64_t Length = Data.getU16(&Offset);
479       Asm->OutStreamer->emitIntValue(Length, 2);
480       // Copy the bytes into to the buffer, process them, emit them.
481       Buffer.reserve(Length);
482       Buffer.resize(0);
483       StringRef Input = InputSec.Data.substr(Offset, Length);
484       ProcessExpr(Input, Buffer);
485       Asm->OutStreamer->emitBytes(
486           StringRef((const char *)Buffer.data(), Length));
487       Offset += Length;
488       LocSectionSize += Length + 2;
489     }
490   }
491 }
492 
493 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
494                                          StringRef PrologueBytes,
495                                          unsigned MinInstLength,
496                                          std::vector<DWARFDebugLine::Row> &Rows,
497                                          unsigned PointerSize) {
498   // Switch to the section where the table will be emitted into.
499   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
500   MCSymbol *LineStartSym = MC->createTempSymbol();
501   MCSymbol *LineEndSym = MC->createTempSymbol();
502 
503   // The first 4 bytes is the total length of the information for this
504   // compilation unit (not including these 4 bytes for the length).
505   Asm->emitLabelDifference(LineEndSym, LineStartSym, 4);
506   Asm->OutStreamer->emitLabel(LineStartSym);
507   // Copy Prologue.
508   MS->emitBytes(PrologueBytes);
509   LineSectionSize += PrologueBytes.size() + 4;
510 
511   SmallString<128> EncodingBuffer;
512   raw_svector_ostream EncodingOS(EncodingBuffer);
513 
514   if (Rows.empty()) {
515     // We only have the dummy entry, dsymutil emits an entry with a 0
516     // address in that case.
517     MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
518                             EncodingOS);
519     MS->emitBytes(EncodingOS.str());
520     LineSectionSize += EncodingBuffer.size();
521     MS->emitLabel(LineEndSym);
522     return;
523   }
524 
525   // Line table state machine fields
526   unsigned FileNum = 1;
527   unsigned LastLine = 1;
528   unsigned Column = 0;
529   unsigned IsStatement = 1;
530   unsigned Isa = 0;
531   uint64_t Address = -1ULL;
532 
533   unsigned RowsSinceLastSequence = 0;
534 
535   for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
536     auto &Row = Rows[Idx];
537 
538     int64_t AddressDelta;
539     if (Address == -1ULL) {
540       MS->emitIntValue(dwarf::DW_LNS_extended_op, 1);
541       MS->emitULEB128IntValue(PointerSize + 1);
542       MS->emitIntValue(dwarf::DW_LNE_set_address, 1);
543       MS->emitIntValue(Row.Address.Address, PointerSize);
544       LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
545       AddressDelta = 0;
546     } else {
547       AddressDelta = (Row.Address.Address - Address) / MinInstLength;
548     }
549 
550     // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable.
551     // We should find a way to share this code, but the current compatibility
552     // requirement with classic dsymutil makes it hard. Revisit that once this
553     // requirement is dropped.
554 
555     if (FileNum != Row.File) {
556       FileNum = Row.File;
557       MS->emitIntValue(dwarf::DW_LNS_set_file, 1);
558       MS->emitULEB128IntValue(FileNum);
559       LineSectionSize += 1 + getULEB128Size(FileNum);
560     }
561     if (Column != Row.Column) {
562       Column = Row.Column;
563       MS->emitIntValue(dwarf::DW_LNS_set_column, 1);
564       MS->emitULEB128IntValue(Column);
565       LineSectionSize += 1 + getULEB128Size(Column);
566     }
567 
568     // FIXME: We should handle the discriminator here, but dsymutil doesn't
569     // consider it, thus ignore it for now.
570 
571     if (Isa != Row.Isa) {
572       Isa = Row.Isa;
573       MS->emitIntValue(dwarf::DW_LNS_set_isa, 1);
574       MS->emitULEB128IntValue(Isa);
575       LineSectionSize += 1 + getULEB128Size(Isa);
576     }
577     if (IsStatement != Row.IsStmt) {
578       IsStatement = Row.IsStmt;
579       MS->emitIntValue(dwarf::DW_LNS_negate_stmt, 1);
580       LineSectionSize += 1;
581     }
582     if (Row.BasicBlock) {
583       MS->emitIntValue(dwarf::DW_LNS_set_basic_block, 1);
584       LineSectionSize += 1;
585     }
586 
587     if (Row.PrologueEnd) {
588       MS->emitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
589       LineSectionSize += 1;
590     }
591 
592     if (Row.EpilogueBegin) {
593       MS->emitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
594       LineSectionSize += 1;
595     }
596 
597     int64_t LineDelta = int64_t(Row.Line) - LastLine;
598     if (!Row.EndSequence) {
599       MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
600       MS->emitBytes(EncodingOS.str());
601       LineSectionSize += EncodingBuffer.size();
602       EncodingBuffer.resize(0);
603       Address = Row.Address.Address;
604       LastLine = Row.Line;
605       RowsSinceLastSequence++;
606     } else {
607       if (LineDelta) {
608         MS->emitIntValue(dwarf::DW_LNS_advance_line, 1);
609         MS->emitSLEB128IntValue(LineDelta);
610         LineSectionSize += 1 + getSLEB128Size(LineDelta);
611       }
612       if (AddressDelta) {
613         MS->emitIntValue(dwarf::DW_LNS_advance_pc, 1);
614         MS->emitULEB128IntValue(AddressDelta);
615         LineSectionSize += 1 + getULEB128Size(AddressDelta);
616       }
617       MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(),
618                               0, EncodingOS);
619       MS->emitBytes(EncodingOS.str());
620       LineSectionSize += EncodingBuffer.size();
621       EncodingBuffer.resize(0);
622       Address = -1ULL;
623       LastLine = FileNum = IsStatement = 1;
624       RowsSinceLastSequence = Column = Isa = 0;
625     }
626   }
627 
628   if (RowsSinceLastSequence) {
629     MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
630                             EncodingOS);
631     MS->emitBytes(EncodingOS.str());
632     LineSectionSize += EncodingBuffer.size();
633     EncodingBuffer.resize(0);
634   }
635 
636   MS->emitLabel(LineEndSym);
637 }
638 
639 /// Copy the debug_line over to the updated binary while unobfuscating the file
640 /// names and directories.
641 void DwarfStreamer::translateLineTable(DataExtractor Data, uint64_t Offset) {
642   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
643   StringRef Contents = Data.getData();
644 
645   // We have to deconstruct the line table header, because it contains to
646   // length fields that will need to be updated when we change the length of
647   // the files and directories in there.
648   unsigned UnitLength = Data.getU32(&Offset);
649   uint64_t UnitEnd = Offset + UnitLength;
650   MCSymbol *BeginLabel = MC->createTempSymbol();
651   MCSymbol *EndLabel = MC->createTempSymbol();
652   unsigned Version = Data.getU16(&Offset);
653 
654   if (Version > 5) {
655     warn("Unsupported line table version: dropping contents and not "
656          "unobfsucating line table.");
657     return;
658   }
659 
660   Asm->emitLabelDifference(EndLabel, BeginLabel, 4);
661   Asm->OutStreamer->emitLabel(BeginLabel);
662   Asm->emitInt16(Version);
663   LineSectionSize += 6;
664 
665   MCSymbol *HeaderBeginLabel = MC->createTempSymbol();
666   MCSymbol *HeaderEndLabel = MC->createTempSymbol();
667   Asm->emitLabelDifference(HeaderEndLabel, HeaderBeginLabel, 4);
668   Asm->OutStreamer->emitLabel(HeaderBeginLabel);
669   Offset += 4;
670   LineSectionSize += 4;
671 
672   uint64_t AfterHeaderLengthOffset = Offset;
673   // Skip to the directories.
674   Offset += (Version >= 4) ? 5 : 4;
675   unsigned OpcodeBase = Data.getU8(&Offset);
676   Offset += OpcodeBase - 1;
677   Asm->OutStreamer->emitBytes(Contents.slice(AfterHeaderLengthOffset, Offset));
678   LineSectionSize += Offset - AfterHeaderLengthOffset;
679 
680   // Offset points to the first directory.
681   while (const char *Dir = Data.getCStr(&Offset)) {
682     if (Dir[0] == 0)
683       break;
684 
685     StringRef Translated = Translator(Dir);
686     Asm->OutStreamer->emitBytes(Translated);
687     Asm->emitInt8(0);
688     LineSectionSize += Translated.size() + 1;
689   }
690   Asm->emitInt8(0);
691   LineSectionSize += 1;
692 
693   while (const char *File = Data.getCStr(&Offset)) {
694     if (File[0] == 0)
695       break;
696 
697     StringRef Translated = Translator(File);
698     Asm->OutStreamer->emitBytes(Translated);
699     Asm->emitInt8(0);
700     LineSectionSize += Translated.size() + 1;
701 
702     uint64_t OffsetBeforeLEBs = Offset;
703     Asm->emitULEB128(Data.getULEB128(&Offset));
704     Asm->emitULEB128(Data.getULEB128(&Offset));
705     Asm->emitULEB128(Data.getULEB128(&Offset));
706     LineSectionSize += Offset - OffsetBeforeLEBs;
707   }
708   Asm->emitInt8(0);
709   LineSectionSize += 1;
710 
711   Asm->OutStreamer->emitLabel(HeaderEndLabel);
712 
713   // Copy the actual line table program over.
714   Asm->OutStreamer->emitBytes(Contents.slice(Offset, UnitEnd));
715   LineSectionSize += UnitEnd - Offset;
716 
717   Asm->OutStreamer->emitLabel(EndLabel);
718   Offset = UnitEnd;
719 }
720 
721 /// Emit the pubnames or pubtypes section contribution for \p
722 /// Unit into \p Sec. The data is provided in \p Names.
723 void DwarfStreamer::emitPubSectionForUnit(
724     MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
725     const std::vector<CompileUnit::AccelInfo> &Names) {
726   if (Names.empty())
727     return;
728 
729   // Start the dwarf pubnames section.
730   Asm->OutStreamer->SwitchSection(Sec);
731   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
732   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
733 
734   bool HeaderEmitted = false;
735   // Emit the pubnames for this compilation unit.
736   for (const auto &Name : Names) {
737     if (Name.SkipPubSection)
738       continue;
739 
740     if (!HeaderEmitted) {
741       // Emit the header.
742       Asm->emitLabelDifference(EndLabel, BeginLabel, 4); // Length
743       Asm->OutStreamer->emitLabel(BeginLabel);
744       Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
745       Asm->emitInt32(Unit.getStartOffset());      // Unit offset
746       Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
747       HeaderEmitted = true;
748     }
749     Asm->emitInt32(Name.Die->getOffset());
750 
751     // Emit the string itself.
752     Asm->OutStreamer->emitBytes(Name.Name.getString());
753     // Emit a null terminator.
754     Asm->emitInt8(0);
755   }
756 
757   if (!HeaderEmitted)
758     return;
759   Asm->emitInt32(0); // End marker.
760   Asm->OutStreamer->emitLabel(EndLabel);
761 }
762 
763 /// Emit .debug_pubnames for \p Unit.
764 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
765   emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
766                         "names", Unit, Unit.getPubnames());
767 }
768 
769 /// Emit .debug_pubtypes for \p Unit.
770 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
771   emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
772                         "types", Unit, Unit.getPubtypes());
773 }
774 
775 /// Emit a CIE into the debug_frame section.
776 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
777   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
778 
779   MS->emitBytes(CIEBytes);
780   FrameSectionSize += CIEBytes.size();
781 }
782 
783 /// Emit a FDE into the debug_frame section. \p FDEBytes
784 /// contains the FDE data without the length, CIE offset and address
785 /// which will be replaced with the parameter values.
786 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
787                             uint32_t Address, StringRef FDEBytes) {
788   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
789 
790   MS->emitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
791   MS->emitIntValue(CIEOffset, 4);
792   MS->emitIntValue(Address, AddrSize);
793   MS->emitBytes(FDEBytes);
794   FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
795 }
796 
797 } // namespace llvm
798