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