[llvm] [cmake] Add possibility to use ChooseMSVCCRT.cmake when include LLVM library
[llvm-core.git] / tools / dsymutil / DwarfStreamer.cpp
blob5d0f7c1067cd8d7f8574451f423308ecba71f34a
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 if (Expected<StringRef> NameOrErr = Section.getName())
35 SectionName = *NameOrErr;
36 else
37 consumeError(NameOrErr.takeError());
39 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
40 if (SectionName != SecName)
41 continue;
42 return Section;
44 return None;
47 bool DwarfStreamer::init(Triple TheTriple) {
48 std::string ErrorStr;
49 std::string TripleName;
50 StringRef Context = "dwarf streamer init";
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();
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);
64 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
65 if (!MAI)
66 return error("no asm info for target " + TripleName, Context);
68 MOFI.reset(new MCObjectFileInfo);
69 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
70 MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, *MC);
72 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
73 if (!MSTI)
74 return error("no subtarget info for target " + TripleName, Context);
76 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
77 MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, MCOptions);
78 if (!MAB)
79 return error("no asm backend for target " + TripleName, Context);
81 MII.reset(TheTarget->createMCInstrInfo());
82 if (!MII)
83 return error("no instr info info for target " + TripleName, Context);
85 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
86 if (!MCE)
87 return error("no code emitter for target " + TripleName, Context);
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;
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;
109 if (!MS)
110 return error("no object streamer for target " + TripleName, Context);
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);
118 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
119 if (!Asm)
120 return error("no asm printer for target " + TripleName, Context);
122 RangesSectionSize = 0;
123 LocSectionSize = 0;
124 LineSectionSize = 0;
125 FrameSectionSize = 0;
127 return true;
130 bool DwarfStreamer::finish(const DebugMap &DM, SymbolMapTranslator &T) {
131 bool Result = true;
132 if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty() &&
133 Options.FileType == OutputFileType::Object)
134 Result = MachOUtils::generateDsymCompanion(DM, T, *MS, OutFile);
135 else
136 MS->Finish();
137 return Result;
140 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
141 MS->SwitchSection(MOFI->getDwarfInfoSection());
142 MC->setDwarfVersion(DwarfVersion);
145 /// Emit the compilation unit header for \p Unit in the debug_info section.
147 /// A Dwarf section header is encoded as:
148 /// uint32_t Unit length (omitting this field)
149 /// uint16_t Version
150 /// uint32_t Abbreviation table offset
151 /// uint8_t Address size
153 /// Leading to a total of 11 bytes.
154 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
155 unsigned Version = Unit.getOrigUnit().getVersion();
156 switchToDebugInfoSection(Version);
158 /// The start of the unit within its section.
159 Unit.setLabelBegin(Asm->createTempSymbol("cu_begin"));
160 Asm->OutStreamer->EmitLabel(Unit.getLabelBegin());
162 // Emit size of content not including length itself. The size has already
163 // been computed in CompileUnit::computeOffsets(). Subtract 4 to that size to
164 // account for the length field.
165 Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
166 Asm->emitInt16(Version);
168 // We share one abbreviations table across all units so it's always at the
169 // start of the section.
170 Asm->emitInt32(0);
171 Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize());
173 // Remember this CU.
174 EmittedUnits.push_back({Unit.getUniqueID(), Unit.getLabelBegin()});
177 /// Emit the \p Abbrevs array as the shared abbreviation table
178 /// for the linked Dwarf file.
179 void DwarfStreamer::emitAbbrevs(
180 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs,
181 unsigned DwarfVersion) {
182 MS->SwitchSection(MOFI->getDwarfAbbrevSection());
183 MC->setDwarfVersion(DwarfVersion);
184 Asm->emitDwarfAbbrevs(Abbrevs);
187 /// Recursively emit the DIE tree rooted at \p Die.
188 void DwarfStreamer::emitDIE(DIE &Die) {
189 MS->SwitchSection(MOFI->getDwarfInfoSection());
190 Asm->emitDwarfDIE(Die);
193 /// Emit the debug_str section stored in \p Pool.
194 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
195 Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
196 std::vector<DwarfStringPoolEntryRef> Entries = Pool.getEntriesForEmission();
197 for (auto Entry : Entries) {
198 // Emit the string itself.
199 Asm->OutStreamer->EmitBytes(Entry.getString());
200 // Emit a null terminator.
201 Asm->emitInt8(0);
205 void DwarfStreamer::emitDebugNames(
206 AccelTable<DWARF5AccelTableStaticData> &Table) {
207 if (EmittedUnits.empty())
208 return;
210 // Build up data structures needed to emit this section.
211 std::vector<MCSymbol *> CompUnits;
212 DenseMap<unsigned, size_t> UniqueIdToCuMap;
213 unsigned Id = 0;
214 for (auto &CU : EmittedUnits) {
215 CompUnits.push_back(CU.LabelBegin);
216 // We might be omitting CUs, so we need to remap them.
217 UniqueIdToCuMap[CU.ID] = Id++;
220 Asm->OutStreamer->SwitchSection(MOFI->getDwarfDebugNamesSection());
221 emitDWARF5AccelTable(
222 Asm.get(), Table, CompUnits,
223 [&UniqueIdToCuMap](const DWARF5AccelTableStaticData &Entry) {
224 return UniqueIdToCuMap[Entry.getCUIndex()];
228 void DwarfStreamer::emitAppleNamespaces(
229 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
230 Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelNamespaceSection());
231 auto *SectionBegin = Asm->createTempSymbol("namespac_begin");
232 Asm->OutStreamer->EmitLabel(SectionBegin);
233 emitAppleAccelTable(Asm.get(), Table, "namespac", SectionBegin);
236 void DwarfStreamer::emitAppleNames(
237 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
238 Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelNamesSection());
239 auto *SectionBegin = Asm->createTempSymbol("names_begin");
240 Asm->OutStreamer->EmitLabel(SectionBegin);
241 emitAppleAccelTable(Asm.get(), Table, "names", SectionBegin);
244 void DwarfStreamer::emitAppleObjc(
245 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
246 Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelObjCSection());
247 auto *SectionBegin = Asm->createTempSymbol("objc_begin");
248 Asm->OutStreamer->EmitLabel(SectionBegin);
249 emitAppleAccelTable(Asm.get(), Table, "objc", SectionBegin);
252 void DwarfStreamer::emitAppleTypes(
253 AccelTable<AppleAccelTableStaticTypeData> &Table) {
254 Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelTypesSection());
255 auto *SectionBegin = Asm->createTempSymbol("types_begin");
256 Asm->OutStreamer->EmitLabel(SectionBegin);
257 emitAppleAccelTable(Asm.get(), Table, "types", SectionBegin);
260 /// Emit the swift_ast section stored in \p Buffers.
261 void DwarfStreamer::emitSwiftAST(StringRef Buffer) {
262 MCSection *SwiftASTSection = MOFI->getDwarfSwiftASTSection();
263 SwiftASTSection->setAlignment(llvm::Align(32));
264 MS->SwitchSection(SwiftASTSection);
265 MS->EmitBytes(Buffer);
268 /// Emit the debug_range section contents for \p FuncRange by
269 /// translating the original \p Entries. The debug_range section
270 /// format is totally trivial, consisting just of pairs of address
271 /// sized addresses describing the ranges.
272 void DwarfStreamer::emitRangesEntries(
273 int64_t UnitPcOffset, uint64_t OrigLowPc,
274 const FunctionIntervals::const_iterator &FuncRange,
275 const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
276 unsigned AddressSize) {
277 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
279 // Offset each range by the right amount.
280 int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
281 for (const auto &Range : Entries) {
282 if (Range.isBaseAddressSelectionEntry(AddressSize)) {
283 warn("unsupported base address selection operation",
284 "emitting debug_ranges");
285 break;
287 // Do not emit empty ranges.
288 if (Range.StartAddress == Range.EndAddress)
289 continue;
291 // All range entries should lie in the function range.
292 if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
293 Range.EndAddress + OrigLowPc <= FuncRange.stop()))
294 warn("inconsistent range data.", "emitting debug_ranges");
295 MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
296 MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
297 RangesSectionSize += 2 * AddressSize;
300 // Add the terminator entry.
301 MS->EmitIntValue(0, AddressSize);
302 MS->EmitIntValue(0, AddressSize);
303 RangesSectionSize += 2 * AddressSize;
306 /// Emit the debug_aranges contribution of a unit and
307 /// if \p DoDebugRanges is true the debug_range contents for a
308 /// compile_unit level DW_AT_ranges attribute (Which are basically the
309 /// same thing with a different base address).
310 /// Just aggregate all the ranges gathered inside that unit.
311 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
312 bool DoDebugRanges) {
313 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
314 // Gather the ranges in a vector, so that we can simplify them. The
315 // IntervalMap will have coalesced the non-linked ranges, but here
316 // we want to coalesce the linked addresses.
317 std::vector<std::pair<uint64_t, uint64_t>> Ranges;
318 const auto &FunctionRanges = Unit.getFunctionRanges();
319 for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
320 Range != End; ++Range)
321 Ranges.push_back(std::make_pair(Range.start() + Range.value(),
322 Range.stop() + Range.value()));
324 // The object addresses where sorted, but again, the linked
325 // addresses might end up in a different order.
326 llvm::sort(Ranges);
328 if (!Ranges.empty()) {
329 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
331 MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
332 MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
334 unsigned HeaderSize =
335 sizeof(int32_t) + // Size of contents (w/o this field
336 sizeof(int16_t) + // DWARF ARange version number
337 sizeof(int32_t) + // Offset of CU in the .debug_info section
338 sizeof(int8_t) + // Pointer Size (in bytes)
339 sizeof(int8_t); // Segment Size (in bytes)
341 unsigned TupleSize = AddressSize * 2;
342 unsigned Padding = offsetToAlignment(HeaderSize, llvm::Align(TupleSize));
344 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
345 Asm->OutStreamer->EmitLabel(BeginLabel);
346 Asm->emitInt16(dwarf::DW_ARANGES_VERSION); // Version number
347 Asm->emitInt32(Unit.getStartOffset()); // Corresponding unit's offset
348 Asm->emitInt8(AddressSize); // Address size
349 Asm->emitInt8(0); // Segment size
351 Asm->OutStreamer->emitFill(Padding, 0x0);
353 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
354 ++Range) {
355 uint64_t RangeStart = Range->first;
356 MS->EmitIntValue(RangeStart, AddressSize);
357 while ((Range + 1) != End && Range->second == (Range + 1)->first)
358 ++Range;
359 MS->EmitIntValue(Range->second - RangeStart, AddressSize);
362 // Emit terminator
363 Asm->OutStreamer->EmitIntValue(0, AddressSize);
364 Asm->OutStreamer->EmitIntValue(0, AddressSize);
365 Asm->OutStreamer->EmitLabel(EndLabel);
368 if (!DoDebugRanges)
369 return;
371 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
372 // Offset each range by the right amount.
373 int64_t PcOffset = -Unit.getLowPc();
374 // Emit coalesced ranges.
375 for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
376 MS->EmitIntValue(Range->first + PcOffset, AddressSize);
377 while (Range + 1 != End && Range->second == (Range + 1)->first)
378 ++Range;
379 MS->EmitIntValue(Range->second + PcOffset, AddressSize);
380 RangesSectionSize += 2 * AddressSize;
383 // Add the terminator entry.
384 MS->EmitIntValue(0, AddressSize);
385 MS->EmitIntValue(0, AddressSize);
386 RangesSectionSize += 2 * AddressSize;
389 /// Emit location lists for \p Unit and update attributes to point to the new
390 /// entries.
391 void DwarfStreamer::emitLocationsForUnit(
392 const CompileUnit &Unit, DWARFContext &Dwarf,
393 std::function<void(StringRef, SmallVectorImpl<uint8_t> &)> ProcessExpr) {
394 const auto &Attributes = Unit.getLocationAttributes();
396 if (Attributes.empty())
397 return;
399 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
401 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
402 const DWARFSection &InputSec = Dwarf.getDWARFObj().getLocSection();
403 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
404 DWARFUnit &OrigUnit = Unit.getOrigUnit();
405 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
406 int64_t UnitPcOffset = 0;
407 if (auto OrigLowPc = dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc)))
408 UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc();
410 SmallVector<uint8_t, 32> Buffer;
411 for (const auto &Attr : Attributes) {
412 uint64_t Offset = Attr.first.get();
413 Attr.first.set(LocSectionSize);
414 // This is the quantity to add to the old location address to get
415 // the correct address for the new one.
416 int64_t LocPcOffset = Attr.second + UnitPcOffset;
417 while (Data.isValidOffset(Offset)) {
418 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
419 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
420 LocSectionSize += 2 * AddressSize;
421 if (Low == 0 && High == 0) {
422 Asm->OutStreamer->EmitIntValue(0, AddressSize);
423 Asm->OutStreamer->EmitIntValue(0, AddressSize);
424 break;
426 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
427 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
428 uint64_t Length = Data.getU16(&Offset);
429 Asm->OutStreamer->EmitIntValue(Length, 2);
430 // Copy the bytes into to the buffer, process them, emit them.
431 Buffer.reserve(Length);
432 Buffer.resize(0);
433 StringRef Input = InputSec.Data.substr(Offset, Length);
434 ProcessExpr(Input, Buffer);
435 Asm->OutStreamer->EmitBytes(
436 StringRef((const char *)Buffer.data(), Length));
437 Offset += Length;
438 LocSectionSize += Length + 2;
443 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
444 StringRef PrologueBytes,
445 unsigned MinInstLength,
446 std::vector<DWARFDebugLine::Row> &Rows,
447 unsigned PointerSize) {
448 // Switch to the section where the table will be emitted into.
449 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
450 MCSymbol *LineStartSym = MC->createTempSymbol();
451 MCSymbol *LineEndSym = MC->createTempSymbol();
453 // The first 4 bytes is the total length of the information for this
454 // compilation unit (not including these 4 bytes for the length).
455 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
456 Asm->OutStreamer->EmitLabel(LineStartSym);
457 // Copy Prologue.
458 MS->EmitBytes(PrologueBytes);
459 LineSectionSize += PrologueBytes.size() + 4;
461 SmallString<128> EncodingBuffer;
462 raw_svector_ostream EncodingOS(EncodingBuffer);
464 if (Rows.empty()) {
465 // We only have the dummy entry, dsymutil emits an entry with a 0
466 // address in that case.
467 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
468 EncodingOS);
469 MS->EmitBytes(EncodingOS.str());
470 LineSectionSize += EncodingBuffer.size();
471 MS->EmitLabel(LineEndSym);
472 return;
475 // Line table state machine fields
476 unsigned FileNum = 1;
477 unsigned LastLine = 1;
478 unsigned Column = 0;
479 unsigned IsStatement = 1;
480 unsigned Isa = 0;
481 uint64_t Address = -1ULL;
483 unsigned RowsSinceLastSequence = 0;
485 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
486 auto &Row = Rows[Idx];
488 int64_t AddressDelta;
489 if (Address == -1ULL) {
490 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
491 MS->EmitULEB128IntValue(PointerSize + 1);
492 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
493 MS->EmitIntValue(Row.Address.Address, PointerSize);
494 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
495 AddressDelta = 0;
496 } else {
497 AddressDelta = (Row.Address.Address - Address) / MinInstLength;
500 // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable.
501 // We should find a way to share this code, but the current compatibility
502 // requirement with classic dsymutil makes it hard. Revisit that once this
503 // requirement is dropped.
505 if (FileNum != Row.File) {
506 FileNum = Row.File;
507 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
508 MS->EmitULEB128IntValue(FileNum);
509 LineSectionSize += 1 + getULEB128Size(FileNum);
511 if (Column != Row.Column) {
512 Column = Row.Column;
513 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
514 MS->EmitULEB128IntValue(Column);
515 LineSectionSize += 1 + getULEB128Size(Column);
518 // FIXME: We should handle the discriminator here, but dsymutil doesn't
519 // consider it, thus ignore it for now.
521 if (Isa != Row.Isa) {
522 Isa = Row.Isa;
523 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
524 MS->EmitULEB128IntValue(Isa);
525 LineSectionSize += 1 + getULEB128Size(Isa);
527 if (IsStatement != Row.IsStmt) {
528 IsStatement = Row.IsStmt;
529 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
530 LineSectionSize += 1;
532 if (Row.BasicBlock) {
533 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
534 LineSectionSize += 1;
537 if (Row.PrologueEnd) {
538 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
539 LineSectionSize += 1;
542 if (Row.EpilogueBegin) {
543 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
544 LineSectionSize += 1;
547 int64_t LineDelta = int64_t(Row.Line) - LastLine;
548 if (!Row.EndSequence) {
549 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
550 MS->EmitBytes(EncodingOS.str());
551 LineSectionSize += EncodingBuffer.size();
552 EncodingBuffer.resize(0);
553 Address = Row.Address.Address;
554 LastLine = Row.Line;
555 RowsSinceLastSequence++;
556 } else {
557 if (LineDelta) {
558 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
559 MS->EmitSLEB128IntValue(LineDelta);
560 LineSectionSize += 1 + getSLEB128Size(LineDelta);
562 if (AddressDelta) {
563 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
564 MS->EmitULEB128IntValue(AddressDelta);
565 LineSectionSize += 1 + getULEB128Size(AddressDelta);
567 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(),
568 0, EncodingOS);
569 MS->EmitBytes(EncodingOS.str());
570 LineSectionSize += EncodingBuffer.size();
571 EncodingBuffer.resize(0);
572 Address = -1ULL;
573 LastLine = FileNum = IsStatement = 1;
574 RowsSinceLastSequence = Column = Isa = 0;
578 if (RowsSinceLastSequence) {
579 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
580 EncodingOS);
581 MS->EmitBytes(EncodingOS.str());
582 LineSectionSize += EncodingBuffer.size();
583 EncodingBuffer.resize(0);
586 MS->EmitLabel(LineEndSym);
589 /// Copy the debug_line over to the updated binary while unobfuscating the file
590 /// names and directories.
591 void DwarfStreamer::translateLineTable(DataExtractor Data, uint64_t Offset) {
592 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
593 StringRef Contents = Data.getData();
595 // We have to deconstruct the line table header, because it contains to
596 // length fields that will need to be updated when we change the length of
597 // the files and directories in there.
598 unsigned UnitLength = Data.getU32(&Offset);
599 uint64_t UnitEnd = Offset + UnitLength;
600 MCSymbol *BeginLabel = MC->createTempSymbol();
601 MCSymbol *EndLabel = MC->createTempSymbol();
602 unsigned Version = Data.getU16(&Offset);
604 if (Version > 5) {
605 warn("Unsupported line table version: dropping contents and not "
606 "unobfsucating line table.");
607 return;
610 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
611 Asm->OutStreamer->EmitLabel(BeginLabel);
612 Asm->emitInt16(Version);
613 LineSectionSize += 6;
615 MCSymbol *HeaderBeginLabel = MC->createTempSymbol();
616 MCSymbol *HeaderEndLabel = MC->createTempSymbol();
617 Asm->EmitLabelDifference(HeaderEndLabel, HeaderBeginLabel, 4);
618 Asm->OutStreamer->EmitLabel(HeaderBeginLabel);
619 Offset += 4;
620 LineSectionSize += 4;
622 uint64_t AfterHeaderLengthOffset = Offset;
623 // Skip to the directories.
624 Offset += (Version >= 4) ? 5 : 4;
625 unsigned OpcodeBase = Data.getU8(&Offset);
626 Offset += OpcodeBase - 1;
627 Asm->OutStreamer->EmitBytes(Contents.slice(AfterHeaderLengthOffset, Offset));
628 LineSectionSize += Offset - AfterHeaderLengthOffset;
630 // Offset points to the first directory.
631 while (const char *Dir = Data.getCStr(&Offset)) {
632 if (Dir[0] == 0)
633 break;
635 StringRef Translated = Options.Translator(Dir);
636 Asm->OutStreamer->EmitBytes(Translated);
637 Asm->emitInt8(0);
638 LineSectionSize += Translated.size() + 1;
640 Asm->emitInt8(0);
641 LineSectionSize += 1;
643 while (const char *File = Data.getCStr(&Offset)) {
644 if (File[0] == 0)
645 break;
647 StringRef Translated = Options.Translator(File);
648 Asm->OutStreamer->EmitBytes(Translated);
649 Asm->emitInt8(0);
650 LineSectionSize += Translated.size() + 1;
652 uint64_t OffsetBeforeLEBs = Offset;
653 Asm->EmitULEB128(Data.getULEB128(&Offset));
654 Asm->EmitULEB128(Data.getULEB128(&Offset));
655 Asm->EmitULEB128(Data.getULEB128(&Offset));
656 LineSectionSize += Offset - OffsetBeforeLEBs;
658 Asm->emitInt8(0);
659 LineSectionSize += 1;
661 Asm->OutStreamer->EmitLabel(HeaderEndLabel);
663 // Copy the actual line table program over.
664 Asm->OutStreamer->EmitBytes(Contents.slice(Offset, UnitEnd));
665 LineSectionSize += UnitEnd - Offset;
667 Asm->OutStreamer->EmitLabel(EndLabel);
668 Offset = UnitEnd;
671 static void emitSectionContents(const object::ObjectFile &Obj,
672 StringRef SecName, MCStreamer *MS) {
673 if (auto Sec = getSectionByName(Obj, SecName)) {
674 if (Expected<StringRef> E = Sec->getContents())
675 MS->EmitBytes(*E);
676 else
677 consumeError(E.takeError());
681 void DwarfStreamer::copyInvariantDebugSection(const object::ObjectFile &Obj) {
682 if (!Options.Translator) {
683 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
684 emitSectionContents(Obj, "debug_line", MS);
687 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
688 emitSectionContents(Obj, "debug_loc", MS);
690 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
691 emitSectionContents(Obj, "debug_ranges", MS);
693 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
694 emitSectionContents(Obj, "debug_frame", MS);
696 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
697 emitSectionContents(Obj, "debug_aranges", MS);
700 /// Emit the pubnames or pubtypes section contribution for \p
701 /// Unit into \p Sec. The data is provided in \p Names.
702 void DwarfStreamer::emitPubSectionForUnit(
703 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
704 const std::vector<CompileUnit::AccelInfo> &Names) {
705 if (Names.empty())
706 return;
708 // Start the dwarf pubnames section.
709 Asm->OutStreamer->SwitchSection(Sec);
710 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
711 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
713 bool HeaderEmitted = false;
714 // Emit the pubnames for this compilation unit.
715 for (const auto &Name : Names) {
716 if (Name.SkipPubSection)
717 continue;
719 if (!HeaderEmitted) {
720 // Emit the header.
721 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
722 Asm->OutStreamer->EmitLabel(BeginLabel);
723 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
724 Asm->emitInt32(Unit.getStartOffset()); // Unit offset
725 Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
726 HeaderEmitted = true;
728 Asm->emitInt32(Name.Die->getOffset());
730 // Emit the string itself.
731 Asm->OutStreamer->EmitBytes(Name.Name.getString());
732 // Emit a null terminator.
733 Asm->emitInt8(0);
736 if (!HeaderEmitted)
737 return;
738 Asm->emitInt32(0); // End marker.
739 Asm->OutStreamer->EmitLabel(EndLabel);
742 /// Emit .debug_pubnames for \p Unit.
743 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
744 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
745 "names", Unit, Unit.getPubnames());
748 /// Emit .debug_pubtypes for \p Unit.
749 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
750 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
751 "types", Unit, Unit.getPubtypes());
754 /// Emit a CIE into the debug_frame section.
755 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
756 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
758 MS->EmitBytes(CIEBytes);
759 FrameSectionSize += CIEBytes.size();
762 /// Emit a FDE into the debug_frame section. \p FDEBytes
763 /// contains the FDE data without the length, CIE offset and address
764 /// which will be replaced with the parameter values.
765 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
766 uint32_t Address, StringRef FDEBytes) {
767 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
769 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
770 MS->EmitIntValue(CIEOffset, 4);
771 MS->EmitIntValue(Address, AddrSize);
772 MS->EmitBytes(FDEBytes);
773 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
776 } // namespace dsymutil
777 } // namespace llvm