Revert r354244 "[DAGCombiner] Eliminate dead stores to stack."
[llvm-complete.git] / tools / dsymutil / DwarfStreamer.cpp
blob2814167400152f96fffc6844afe98333963a083b
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 //===----------------------------------------------------------------------===//
9 #include "DwarfStreamer.h"
10 #include "CompileUnit.h"
11 #include "LinkUtils.h"
12 #include "MachOUtils.h"
13 #include "llvm/ADT/Triple.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"
22 namespace llvm {
23 namespace dsymutil {
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>
31 getSectionByName(const object::ObjectFile &Obj, StringRef SecName) {
32 for (const object::SectionRef &Section : Obj.sections()) {
33 StringRef SectionName;
34 Section.getName(SectionName);
35 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
36 if (SectionName != SecName)
37 continue;
38 return Section;
40 return None;
43 bool DwarfStreamer::init(Triple TheTriple) {
44 std::string ErrorStr;
45 std::string TripleName;
46 StringRef Context = "dwarf streamer init";
48 // Get the target.
49 const Target *TheTarget =
50 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
51 if (!TheTarget)
52 return error(ErrorStr, Context);
53 TripleName = TheTriple.getTriple();
55 // Create all the MC Objects.
56 MRI.reset(TheTarget->createMCRegInfo(TripleName));
57 if (!MRI)
58 return error(Twine("no register info for target ") + TripleName, Context);
60 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
61 if (!MAI)
62 return error("no asm info for target " + TripleName, Context);
64 MOFI.reset(new MCObjectFileInfo);
65 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
66 MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, *MC);
68 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
69 if (!MSTI)
70 return error("no subtarget info for target " + TripleName, Context);
72 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
73 MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, MCOptions);
74 if (!MAB)
75 return error("no asm backend for target " + TripleName, Context);
77 MII.reset(TheTarget->createMCInstrInfo());
78 if (!MII)
79 return error("no instr info info for target " + TripleName, Context);
81 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
82 if (!MCE)
83 return error("no code emitter for target " + TripleName, Context);
85 switch (Options.FileType) {
86 case OutputFileType::Assembly: {
87 MIP = TheTarget->createMCInstPrinter(TheTriple, MAI->getAssemblerDialect(),
88 *MAI, *MII, *MRI);
89 MS = TheTarget->createAsmStreamer(
90 *MC, llvm::make_unique<formatted_raw_ostream>(OutFile), true, true, MIP,
91 std::unique_ptr<MCCodeEmitter>(MCE), std::unique_ptr<MCAsmBackend>(MAB),
92 true);
93 break;
95 case OutputFileType::Object: {
96 MS = TheTarget->createMCObjectStreamer(
97 TheTriple, *MC, std::unique_ptr<MCAsmBackend>(MAB),
98 MAB->createObjectWriter(OutFile), std::unique_ptr<MCCodeEmitter>(MCE),
99 *MSTI, MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
100 /*DWARFMustBeAtTheEnd*/ false);
101 break;
105 if (!MS)
106 return error("no object streamer for target " + TripleName, Context);
108 // Finally create the AsmPrinter we'll use to emit the DIEs.
109 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
110 None));
111 if (!TM)
112 return error("no target machine for target " + TripleName, Context);
114 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
115 if (!Asm)
116 return error("no asm printer for target " + TripleName, Context);
118 RangesSectionSize = 0;
119 LocSectionSize = 0;
120 LineSectionSize = 0;
121 FrameSectionSize = 0;
123 return true;
126 bool DwarfStreamer::finish(const DebugMap &DM, SymbolMapTranslator &T) {
127 bool Result = true;
128 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty() &&
129 Options.FileType == OutputFileType::Object)
130 Result = MachOUtils::generateDsymCompanion(DM, T, *MS, OutFile);
131 else
132 MS->Finish();
133 return Result;
136 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
137 MS->SwitchSection(MOFI->getDwarfInfoSection());
138 MC->setDwarfVersion(DwarfVersion);
141 /// Emit the compilation unit header for \p Unit in the debug_info section.
143 /// A Dwarf section header is encoded as:
144 /// uint32_t Unit length (omitting this field)
145 /// uint16_t Version
146 /// uint32_t Abbreviation table offset
147 /// uint8_t Address size
149 /// Leading to a total of 11 bytes.
150 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
151 unsigned Version = Unit.getOrigUnit().getVersion();
152 switchToDebugInfoSection(Version);
154 /// The start of the unit within its section.
155 Unit.setLabelBegin(Asm->createTempSymbol("cu_begin"));
156 Asm->OutStreamer->EmitLabel(Unit.getLabelBegin());
158 // Emit size of content not including length itself. The size has already
159 // been computed in CompileUnit::computeOffsets(). Subtract 4 to that size to
160 // account for the length field.
161 Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
162 Asm->emitInt16(Version);
164 // We share one abbreviations table across all units so it's always at the
165 // start of the section.
166 Asm->emitInt32(0);
167 Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize());
169 // Remember this CU.
170 EmittedUnits.push_back({Unit.getUniqueID(), Unit.getLabelBegin()});
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);
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);
189 /// Emit the debug_str section stored in \p Pool.
190 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
191 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
192 std::vector<DwarfStringPoolEntryRef> Entries = Pool.getEntriesForEmission();
193 for (auto Entry : Entries) {
194 // Emit the string itself.
195 Asm->OutStreamer->EmitBytes(Entry.getString());
196 // Emit a null terminator.
197 Asm->emitInt8(0);
201 void DwarfStreamer::emitDebugNames(
202 AccelTable<DWARF5AccelTableStaticData> &Table) {
203 if (EmittedUnits.empty())
204 return;
206 // Build up data structures needed to emit this section.
207 std::vector<MCSymbol *> CompUnits;
208 DenseMap<unsigned, size_t> UniqueIdToCuMap;
209 unsigned Id = 0;
210 for (auto &CU : EmittedUnits) {
211 CompUnits.push_back(CU.LabelBegin);
212 // We might be omitting CUs, so we need to remap them.
213 UniqueIdToCuMap[CU.ID] = Id++;
216 Asm->OutStreamer->SwitchSection(MOFI->getDwarfDebugNamesSection());
217 emitDWARF5AccelTable(
218 Asm.get(), Table, CompUnits,
219 [&UniqueIdToCuMap](const DWARF5AccelTableStaticData &Entry) {
220 return UniqueIdToCuMap[Entry.getCUIndex()];
224 void DwarfStreamer::emitAppleNamespaces(
225 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
226 Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelNamespaceSection());
227 auto *SectionBegin = Asm->createTempSymbol("namespac_begin");
228 Asm->OutStreamer->EmitLabel(SectionBegin);
229 emitAppleAccelTable(Asm.get(), Table, "namespac", SectionBegin);
232 void DwarfStreamer::emitAppleNames(
233 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
234 Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelNamesSection());
235 auto *SectionBegin = Asm->createTempSymbol("names_begin");
236 Asm->OutStreamer->EmitLabel(SectionBegin);
237 emitAppleAccelTable(Asm.get(), Table, "names", SectionBegin);
240 void DwarfStreamer::emitAppleObjc(
241 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
242 Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelObjCSection());
243 auto *SectionBegin = Asm->createTempSymbol("objc_begin");
244 Asm->OutStreamer->EmitLabel(SectionBegin);
245 emitAppleAccelTable(Asm.get(), Table, "objc", SectionBegin);
248 void DwarfStreamer::emitAppleTypes(
249 AccelTable<AppleAccelTableStaticTypeData> &Table) {
250 Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelTypesSection());
251 auto *SectionBegin = Asm->createTempSymbol("types_begin");
252 Asm->OutStreamer->EmitLabel(SectionBegin);
253 emitAppleAccelTable(Asm.get(), Table, "types", SectionBegin);
256 /// Emit the swift_ast section stored in \p Buffers.
257 void DwarfStreamer::emitSwiftAST(StringRef Buffer) {
258 MCSection *SwiftASTSection = MOFI->getDwarfSwiftASTSection();
259 SwiftASTSection->setAlignment(1 << 5);
260 MS->SwitchSection(SwiftASTSection);
261 MS->EmitBytes(Buffer);
264 /// Emit the debug_range section contents for \p FuncRange by
265 /// translating the original \p Entries. The debug_range section
266 /// format is totally trivial, consisting just of pairs of address
267 /// sized addresses describing the ranges.
268 void DwarfStreamer::emitRangesEntries(
269 int64_t UnitPcOffset, uint64_t OrigLowPc,
270 const FunctionIntervals::const_iterator &FuncRange,
271 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
272 unsigned AddressSize) {
273 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
275 // Offset each range by the right amount.
276 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
277 for (const auto &Range : Entries) {
278 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
279 warn("unsupported base address selection operation",
280 "emitting debug_ranges");
281 break;
283 // Do not emit empty ranges.
284 if (Range.StartAddress == Range.EndAddress)
285 continue;
287 // All range entries should lie in the function range.
288 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
289 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
290 warn("inconsistent range data.", "emitting debug_ranges");
291 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
292 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
293 RangesSectionSize += 2 * AddressSize;
296 // Add the terminator entry.
297 MS->EmitIntValue(0, AddressSize);
298 MS->EmitIntValue(0, AddressSize);
299 RangesSectionSize += 2 * AddressSize;
302 /// Emit the debug_aranges contribution of a unit and
303 /// if \p DoDebugRanges is true the debug_range contents for a
304 /// compile_unit level DW_AT_ranges attribute (Which are basically the
305 /// same thing with a different base address).
306 /// Just aggregate all the ranges gathered inside that unit.
307 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
308 bool DoDebugRanges) {
309 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
310 // Gather the ranges in a vector, so that we can simplify them. The
311 // IntervalMap will have coalesced the non-linked ranges, but here
312 // we want to coalesce the linked addresses.
313 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
314 const auto &FunctionRanges = Unit.getFunctionRanges();
315 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
316 Range != End; ++Range)
317 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
318 Range.stop() + Range.value()));
320 // The object addresses where sorted, but again, the linked
321 // addresses might end up in a different order.
322 llvm::sort(Ranges);
324 if (!Ranges.empty()) {
325 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
327 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
328 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
330 unsigned HeaderSize =
331 sizeof(int32_t) + // Size of contents (w/o this field
332 sizeof(int16_t) + // DWARF ARange version number
333 sizeof(int32_t) + // Offset of CU in the .debug_info section
334 sizeof(int8_t) + // Pointer Size (in bytes)
335 sizeof(int8_t); // Segment Size (in bytes)
337 unsigned TupleSize = AddressSize * 2;
338 unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
340 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
341 Asm->OutStreamer->EmitLabel(BeginLabel);
342 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); // Version number
343 Asm->emitInt32(Unit.getStartOffset()); // Corresponding unit's offset
344 Asm->emitInt8(AddressSize); // Address size
345 Asm->emitInt8(0); // Segment size
347 Asm->OutStreamer->emitFill(Padding, 0x0);
349 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
350 ++Range) {
351 uint64_t RangeStart = Range->first;
352 MS->EmitIntValue(RangeStart, AddressSize);
353 while ((Range + 1) != End && Range->second == (Range + 1)->first)
354 ++Range;
355 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
358 // Emit terminator
359 Asm->OutStreamer->EmitIntValue(0, AddressSize);
360 Asm->OutStreamer->EmitIntValue(0, AddressSize);
361 Asm->OutStreamer->EmitLabel(EndLabel);
364 if (!DoDebugRanges)
365 return;
367 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
368 // Offset each range by the right amount.
369 int64_t PcOffset = -Unit.getLowPc();
370 // Emit coalesced ranges.
371 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
372 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
373 while (Range + 1 != End && Range->second == (Range + 1)->first)
374 ++Range;
375 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
376 RangesSectionSize += 2 * AddressSize;
379 // Add the terminator entry.
380 MS->EmitIntValue(0, AddressSize);
381 MS->EmitIntValue(0, AddressSize);
382 RangesSectionSize += 2 * AddressSize;
385 /// Emit location lists for \p Unit and update attributes to point to the new
386 /// entries.
387 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
388 DWARFContext &Dwarf) {
389 const auto &Attributes = Unit.getLocationAttributes();
391 if (Attributes.empty())
392 return;
394 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
396 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
397 const DWARFSection &InputSec = Dwarf.getDWARFObj().getLocSection();
398 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
399 DWARFUnit &OrigUnit = Unit.getOrigUnit();
400 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
401 int64_t UnitPcOffset = 0;
402 if (auto OrigLowPc = dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc)))
403 UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc();
405 for (const auto &Attr : Attributes) {
406 uint32_t Offset = Attr.first.get();
407 Attr.first.set(LocSectionSize);
408 // This is the quantity to add to the old location address to get
409 // the correct address for the new one.
410 int64_t LocPcOffset = Attr.second + UnitPcOffset;
411 while (Data.isValidOffset(Offset)) {
412 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
413 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
414 LocSectionSize += 2 * AddressSize;
415 if (Low == 0 && High == 0) {
416 Asm->OutStreamer->EmitIntValue(0, AddressSize);
417 Asm->OutStreamer->EmitIntValue(0, AddressSize);
418 break;
420 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
421 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
422 uint64_t Length = Data.getU16(&Offset);
423 Asm->OutStreamer->EmitIntValue(Length, 2);
424 // Just copy the bytes over.
425 Asm->OutStreamer->EmitBytes(
426 StringRef(InputSec.Data.substr(Offset, Length)));
427 Offset += Length;
428 LocSectionSize += Length + 2;
433 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
434 StringRef PrologueBytes,
435 unsigned MinInstLength,
436 std::vector<DWARFDebugLine::Row> &Rows,
437 unsigned PointerSize) {
438 // Switch to the section where the table will be emitted into.
439 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
440 MCSymbol *LineStartSym = MC->createTempSymbol();
441 MCSymbol *LineEndSym = MC->createTempSymbol();
443 // The first 4 bytes is the total length of the information for this
444 // compilation unit (not including these 4 bytes for the length).
445 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
446 Asm->OutStreamer->EmitLabel(LineStartSym);
447 // Copy Prologue.
448 MS->EmitBytes(PrologueBytes);
449 LineSectionSize += PrologueBytes.size() + 4;
451 SmallString<128> EncodingBuffer;
452 raw_svector_ostream EncodingOS(EncodingBuffer);
454 if (Rows.empty()) {
455 // We only have the dummy entry, dsymutil emits an entry with a 0
456 // address in that case.
457 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
458 EncodingOS);
459 MS->EmitBytes(EncodingOS.str());
460 LineSectionSize += EncodingBuffer.size();
461 MS->EmitLabel(LineEndSym);
462 return;
465 // Line table state machine fields
466 unsigned FileNum = 1;
467 unsigned LastLine = 1;
468 unsigned Column = 0;
469 unsigned IsStatement = 1;
470 unsigned Isa = 0;
471 uint64_t Address = -1ULL;
473 unsigned RowsSinceLastSequence = 0;
475 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
476 auto &Row = Rows[Idx];
478 int64_t AddressDelta;
479 if (Address == -1ULL) {
480 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
481 MS->EmitULEB128IntValue(PointerSize + 1);
482 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
483 MS->EmitIntValue(Row.Address, PointerSize);
484 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
485 AddressDelta = 0;
486 } else {
487 AddressDelta = (Row.Address - Address) / MinInstLength;
490 // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable.
491 // We should find a way to share this code, but the current compatibility
492 // requirement with classic dsymutil makes it hard. Revisit that once this
493 // requirement is dropped.
495 if (FileNum != Row.File) {
496 FileNum = Row.File;
497 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
498 MS->EmitULEB128IntValue(FileNum);
499 LineSectionSize += 1 + getULEB128Size(FileNum);
501 if (Column != Row.Column) {
502 Column = Row.Column;
503 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
504 MS->EmitULEB128IntValue(Column);
505 LineSectionSize += 1 + getULEB128Size(Column);
508 // FIXME: We should handle the discriminator here, but dsymutil doesn't
509 // consider it, thus ignore it for now.
511 if (Isa != Row.Isa) {
512 Isa = Row.Isa;
513 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
514 MS->EmitULEB128IntValue(Isa);
515 LineSectionSize += 1 + getULEB128Size(Isa);
517 if (IsStatement != Row.IsStmt) {
518 IsStatement = Row.IsStmt;
519 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
520 LineSectionSize += 1;
522 if (Row.BasicBlock) {
523 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
524 LineSectionSize += 1;
527 if (Row.PrologueEnd) {
528 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
529 LineSectionSize += 1;
532 if (Row.EpilogueBegin) {
533 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
534 LineSectionSize += 1;
537 int64_t LineDelta = int64_t(Row.Line) - LastLine;
538 if (!Row.EndSequence) {
539 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
540 MS->EmitBytes(EncodingOS.str());
541 LineSectionSize += EncodingBuffer.size();
542 EncodingBuffer.resize(0);
543 Address = Row.Address;
544 LastLine = Row.Line;
545 RowsSinceLastSequence++;
546 } else {
547 if (LineDelta) {
548 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
549 MS->EmitSLEB128IntValue(LineDelta);
550 LineSectionSize += 1 + getSLEB128Size(LineDelta);
552 if (AddressDelta) {
553 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
554 MS->EmitULEB128IntValue(AddressDelta);
555 LineSectionSize += 1 + getULEB128Size(AddressDelta);
557 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(),
558 0, EncodingOS);
559 MS->EmitBytes(EncodingOS.str());
560 LineSectionSize += EncodingBuffer.size();
561 EncodingBuffer.resize(0);
562 Address = -1ULL;
563 LastLine = FileNum = IsStatement = 1;
564 RowsSinceLastSequence = Column = Isa = 0;
568 if (RowsSinceLastSequence) {
569 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
570 EncodingOS);
571 MS->EmitBytes(EncodingOS.str());
572 LineSectionSize += EncodingBuffer.size();
573 EncodingBuffer.resize(0);
576 MS->EmitLabel(LineEndSym);
579 /// Copy the debug_line over to the updated binary while unobfuscating the file
580 /// names and directories.
581 void DwarfStreamer::translateLineTable(DataExtractor Data, uint32_t Offset,
582 LinkOptions &Options) {
583 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
584 StringRef Contents = Data.getData();
586 // We have to deconstruct the line table header, because it contains to
587 // length fields that will need to be updated when we change the length of
588 // the files and directories in there.
589 unsigned UnitLength = Data.getU32(&Offset);
590 unsigned UnitEnd = Offset + UnitLength;
591 MCSymbol *BeginLabel = MC->createTempSymbol();
592 MCSymbol *EndLabel = MC->createTempSymbol();
593 unsigned Version = Data.getU16(&Offset);
595 if (Version > 5) {
596 warn("Unsupported line table version: dropping contents and not "
597 "unobfsucating line table.");
598 return;
601 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
602 Asm->OutStreamer->EmitLabel(BeginLabel);
603 Asm->emitInt16(Version);
604 LineSectionSize += 6;
606 MCSymbol *HeaderBeginLabel = MC->createTempSymbol();
607 MCSymbol *HeaderEndLabel = MC->createTempSymbol();
608 Asm->EmitLabelDifference(HeaderEndLabel, HeaderBeginLabel, 4);
609 Asm->OutStreamer->EmitLabel(HeaderBeginLabel);
610 Offset += 4;
611 LineSectionSize += 4;
613 uint32_t AfterHeaderLengthOffset = Offset;
614 // Skip to the directories.
615 Offset += (Version >= 4) ? 5 : 4;
616 unsigned OpcodeBase = Data.getU8(&Offset);
617 Offset += OpcodeBase - 1;
618 Asm->OutStreamer->EmitBytes(Contents.slice(AfterHeaderLengthOffset, Offset));
619 LineSectionSize += Offset - AfterHeaderLengthOffset;
621 // Offset points to the first directory.
622 while (const char *Dir = Data.getCStr(&Offset)) {
623 if (Dir[0] == 0)
624 break;
626 StringRef Translated = Options.Translator(Dir);
627 Asm->OutStreamer->EmitBytes(Translated);
628 Asm->emitInt8(0);
629 LineSectionSize += Translated.size() + 1;
631 Asm->emitInt8(0);
632 LineSectionSize += 1;
634 while (const char *File = Data.getCStr(&Offset)) {
635 if (File[0] == 0)
636 break;
638 StringRef Translated = Options.Translator(File);
639 Asm->OutStreamer->EmitBytes(Translated);
640 Asm->emitInt8(0);
641 LineSectionSize += Translated.size() + 1;
643 uint32_t OffsetBeforeLEBs = Offset;
644 Asm->EmitULEB128(Data.getULEB128(&Offset));
645 Asm->EmitULEB128(Data.getULEB128(&Offset));
646 Asm->EmitULEB128(Data.getULEB128(&Offset));
647 LineSectionSize += Offset - OffsetBeforeLEBs;
649 Asm->emitInt8(0);
650 LineSectionSize += 1;
652 Asm->OutStreamer->EmitLabel(HeaderEndLabel);
654 // Copy the actual line table program over.
655 Asm->OutStreamer->EmitBytes(Contents.slice(Offset, UnitEnd));
656 LineSectionSize += UnitEnd - Offset;
658 Asm->OutStreamer->EmitLabel(EndLabel);
659 Offset = UnitEnd;
662 static void emitSectionContents(const object::ObjectFile &Obj,
663 StringRef SecName, MCStreamer *MS) {
664 StringRef Contents;
665 if (auto Sec = getSectionByName(Obj, SecName))
666 if (!Sec->getContents(Contents))
667 MS->EmitBytes(Contents);
670 void DwarfStreamer::copyInvariantDebugSection(const object::ObjectFile &Obj) {
671 if (!Options.Translator) {
672 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
673 emitSectionContents(Obj, "debug_line", MS);
676 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
677 emitSectionContents(Obj, "debug_loc", MS);
679 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
680 emitSectionContents(Obj, "debug_ranges", MS);
682 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
683 emitSectionContents(Obj, "debug_frame", MS);
685 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
686 emitSectionContents(Obj, "debug_aranges", MS);
689 /// Emit the pubnames or pubtypes section contribution for \p
690 /// Unit into \p Sec. The data is provided in \p Names.
691 void DwarfStreamer::emitPubSectionForUnit(
692 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
693 const std::vector<CompileUnit::AccelInfo> &Names) {
694 if (Names.empty())
695 return;
697 // Start the dwarf pubnames section.
698 Asm->OutStreamer->SwitchSection(Sec);
699 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
700 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
702 bool HeaderEmitted = false;
703 // Emit the pubnames for this compilation unit.
704 for (const auto &Name : Names) {
705 if (Name.SkipPubSection)
706 continue;
708 if (!HeaderEmitted) {
709 // Emit the header.
710 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
711 Asm->OutStreamer->EmitLabel(BeginLabel);
712 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
713 Asm->emitInt32(Unit.getStartOffset()); // Unit offset
714 Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
715 HeaderEmitted = true;
717 Asm->emitInt32(Name.Die->getOffset());
719 // Emit the string itself.
720 Asm->OutStreamer->EmitBytes(Name.Name.getString());
721 // Emit a null terminator.
722 Asm->emitInt8(0);
725 if (!HeaderEmitted)
726 return;
727 Asm->emitInt32(0); // End marker.
728 Asm->OutStreamer->EmitLabel(EndLabel);
731 /// Emit .debug_pubnames for \p Unit.
732 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
733 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
734 "names", Unit, Unit.getPubnames());
737 /// Emit .debug_pubtypes for \p Unit.
738 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
739 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
740 "types", Unit, Unit.getPubtypes());
743 /// Emit a CIE into the debug_frame section.
744 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
745 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
747 MS->EmitBytes(CIEBytes);
748 FrameSectionSize += CIEBytes.size();
751 /// Emit a FDE into the debug_frame section. \p FDEBytes
752 /// contains the FDE data without the length, CIE offset and address
753 /// which will be replaced with the parameter values.
754 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
755 uint32_t Address, StringRef FDEBytes) {
756 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
758 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
759 MS->EmitIntValue(CIEOffset, 4);
760 MS->EmitIntValue(Address, AddrSize);
761 MS->EmitBytes(FDEBytes);
762 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
765 } // namespace dsymutil
766 } // namespace llvm