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