[InstCombine] Signed saturation tests. NFC
[llvm-complete.git] / tools / dsymutil / DwarfStreamer.cpp
blob88ca4b34a3e77432e7e598298a4eac65a7a3c67d
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(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, 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 uint64_t BaseAddressMarker = (AddressSize == 8)
403 ? std::numeric_limits<uint64_t>::max()
404 : std::numeric_limits<uint32_t>::max();
405 const DWARFSection &InputSec = Dwarf.getDWARFObj().getLocSection();
406 DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
407 DWARFUnit &OrigUnit = Unit.getOrigUnit();
408 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
409 int64_t UnitPcOffset = 0;
410 if (auto OrigLowPc = dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc)))
411 UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc();
413 SmallVector<uint8_t, 32> Buffer;
414 for (const auto &Attr : Attributes) {
415 uint64_t Offset = Attr.first.get();
416 Attr.first.set(LocSectionSize);
417 // This is the quantity to add to the old location address to get
418 // the correct address for the new one.
419 int64_t LocPcOffset = Attr.second + UnitPcOffset;
420 while (Data.isValidOffset(Offset)) {
421 uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
422 uint64_t High = Data.getUnsigned(&Offset, AddressSize);
423 LocSectionSize += 2 * AddressSize;
424 // End of list entry.
425 if (Low == 0 && High == 0) {
426 Asm->OutStreamer->EmitIntValue(0, AddressSize);
427 Asm->OutStreamer->EmitIntValue(0, AddressSize);
428 break;
430 // Base address selection entry.
431 if (Low == BaseAddressMarker) {
432 Asm->OutStreamer->EmitIntValue(BaseAddressMarker, AddressSize);
433 Asm->OutStreamer->EmitIntValue(High + Attr.second, AddressSize);
434 LocPcOffset = 0;
435 continue;
437 // Location list entry.
438 Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
439 Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
440 uint64_t Length = Data.getU16(&Offset);
441 Asm->OutStreamer->EmitIntValue(Length, 2);
442 // Copy the bytes into to the buffer, process them, emit them.
443 Buffer.reserve(Length);
444 Buffer.resize(0);
445 StringRef Input = InputSec.Data.substr(Offset, Length);
446 ProcessExpr(Input, Buffer);
447 Asm->OutStreamer->EmitBytes(
448 StringRef((const char *)Buffer.data(), Length));
449 Offset += Length;
450 LocSectionSize += Length + 2;
455 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
456 StringRef PrologueBytes,
457 unsigned MinInstLength,
458 std::vector<DWARFDebugLine::Row> &Rows,
459 unsigned PointerSize) {
460 // Switch to the section where the table will be emitted into.
461 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
462 MCSymbol *LineStartSym = MC->createTempSymbol();
463 MCSymbol *LineEndSym = MC->createTempSymbol();
465 // The first 4 bytes is the total length of the information for this
466 // compilation unit (not including these 4 bytes for the length).
467 Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
468 Asm->OutStreamer->EmitLabel(LineStartSym);
469 // Copy Prologue.
470 MS->EmitBytes(PrologueBytes);
471 LineSectionSize += PrologueBytes.size() + 4;
473 SmallString<128> EncodingBuffer;
474 raw_svector_ostream EncodingOS(EncodingBuffer);
476 if (Rows.empty()) {
477 // We only have the dummy entry, dsymutil emits an entry with a 0
478 // address in that case.
479 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
480 EncodingOS);
481 MS->EmitBytes(EncodingOS.str());
482 LineSectionSize += EncodingBuffer.size();
483 MS->EmitLabel(LineEndSym);
484 return;
487 // Line table state machine fields
488 unsigned FileNum = 1;
489 unsigned LastLine = 1;
490 unsigned Column = 0;
491 unsigned IsStatement = 1;
492 unsigned Isa = 0;
493 uint64_t Address = -1ULL;
495 unsigned RowsSinceLastSequence = 0;
497 for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
498 auto &Row = Rows[Idx];
500 int64_t AddressDelta;
501 if (Address == -1ULL) {
502 MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
503 MS->EmitULEB128IntValue(PointerSize + 1);
504 MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
505 MS->EmitIntValue(Row.Address.Address, PointerSize);
506 LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
507 AddressDelta = 0;
508 } else {
509 AddressDelta = (Row.Address.Address - Address) / MinInstLength;
512 // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable.
513 // We should find a way to share this code, but the current compatibility
514 // requirement with classic dsymutil makes it hard. Revisit that once this
515 // requirement is dropped.
517 if (FileNum != Row.File) {
518 FileNum = Row.File;
519 MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
520 MS->EmitULEB128IntValue(FileNum);
521 LineSectionSize += 1 + getULEB128Size(FileNum);
523 if (Column != Row.Column) {
524 Column = Row.Column;
525 MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
526 MS->EmitULEB128IntValue(Column);
527 LineSectionSize += 1 + getULEB128Size(Column);
530 // FIXME: We should handle the discriminator here, but dsymutil doesn't
531 // consider it, thus ignore it for now.
533 if (Isa != Row.Isa) {
534 Isa = Row.Isa;
535 MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
536 MS->EmitULEB128IntValue(Isa);
537 LineSectionSize += 1 + getULEB128Size(Isa);
539 if (IsStatement != Row.IsStmt) {
540 IsStatement = Row.IsStmt;
541 MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
542 LineSectionSize += 1;
544 if (Row.BasicBlock) {
545 MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
546 LineSectionSize += 1;
549 if (Row.PrologueEnd) {
550 MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
551 LineSectionSize += 1;
554 if (Row.EpilogueBegin) {
555 MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
556 LineSectionSize += 1;
559 int64_t LineDelta = int64_t(Row.Line) - LastLine;
560 if (!Row.EndSequence) {
561 MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
562 MS->EmitBytes(EncodingOS.str());
563 LineSectionSize += EncodingBuffer.size();
564 EncodingBuffer.resize(0);
565 Address = Row.Address.Address;
566 LastLine = Row.Line;
567 RowsSinceLastSequence++;
568 } else {
569 if (LineDelta) {
570 MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
571 MS->EmitSLEB128IntValue(LineDelta);
572 LineSectionSize += 1 + getSLEB128Size(LineDelta);
574 if (AddressDelta) {
575 MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
576 MS->EmitULEB128IntValue(AddressDelta);
577 LineSectionSize += 1 + getULEB128Size(AddressDelta);
579 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(),
580 0, EncodingOS);
581 MS->EmitBytes(EncodingOS.str());
582 LineSectionSize += EncodingBuffer.size();
583 EncodingBuffer.resize(0);
584 Address = -1ULL;
585 LastLine = FileNum = IsStatement = 1;
586 RowsSinceLastSequence = Column = Isa = 0;
590 if (RowsSinceLastSequence) {
591 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
592 EncodingOS);
593 MS->EmitBytes(EncodingOS.str());
594 LineSectionSize += EncodingBuffer.size();
595 EncodingBuffer.resize(0);
598 MS->EmitLabel(LineEndSym);
601 /// Copy the debug_line over to the updated binary while unobfuscating the file
602 /// names and directories.
603 void DwarfStreamer::translateLineTable(DataExtractor Data, uint64_t Offset) {
604 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
605 StringRef Contents = Data.getData();
607 // We have to deconstruct the line table header, because it contains to
608 // length fields that will need to be updated when we change the length of
609 // the files and directories in there.
610 unsigned UnitLength = Data.getU32(&Offset);
611 uint64_t UnitEnd = Offset + UnitLength;
612 MCSymbol *BeginLabel = MC->createTempSymbol();
613 MCSymbol *EndLabel = MC->createTempSymbol();
614 unsigned Version = Data.getU16(&Offset);
616 if (Version > 5) {
617 warn("Unsupported line table version: dropping contents and not "
618 "unobfsucating line table.");
619 return;
622 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
623 Asm->OutStreamer->EmitLabel(BeginLabel);
624 Asm->emitInt16(Version);
625 LineSectionSize += 6;
627 MCSymbol *HeaderBeginLabel = MC->createTempSymbol();
628 MCSymbol *HeaderEndLabel = MC->createTempSymbol();
629 Asm->EmitLabelDifference(HeaderEndLabel, HeaderBeginLabel, 4);
630 Asm->OutStreamer->EmitLabel(HeaderBeginLabel);
631 Offset += 4;
632 LineSectionSize += 4;
634 uint64_t AfterHeaderLengthOffset = Offset;
635 // Skip to the directories.
636 Offset += (Version >= 4) ? 5 : 4;
637 unsigned OpcodeBase = Data.getU8(&Offset);
638 Offset += OpcodeBase - 1;
639 Asm->OutStreamer->EmitBytes(Contents.slice(AfterHeaderLengthOffset, Offset));
640 LineSectionSize += Offset - AfterHeaderLengthOffset;
642 // Offset points to the first directory.
643 while (const char *Dir = Data.getCStr(&Offset)) {
644 if (Dir[0] == 0)
645 break;
647 StringRef Translated = Options.Translator(Dir);
648 Asm->OutStreamer->EmitBytes(Translated);
649 Asm->emitInt8(0);
650 LineSectionSize += Translated.size() + 1;
652 Asm->emitInt8(0);
653 LineSectionSize += 1;
655 while (const char *File = Data.getCStr(&Offset)) {
656 if (File[0] == 0)
657 break;
659 StringRef Translated = Options.Translator(File);
660 Asm->OutStreamer->EmitBytes(Translated);
661 Asm->emitInt8(0);
662 LineSectionSize += Translated.size() + 1;
664 uint64_t OffsetBeforeLEBs = Offset;
665 Asm->EmitULEB128(Data.getULEB128(&Offset));
666 Asm->EmitULEB128(Data.getULEB128(&Offset));
667 Asm->EmitULEB128(Data.getULEB128(&Offset));
668 LineSectionSize += Offset - OffsetBeforeLEBs;
670 Asm->emitInt8(0);
671 LineSectionSize += 1;
673 Asm->OutStreamer->EmitLabel(HeaderEndLabel);
675 // Copy the actual line table program over.
676 Asm->OutStreamer->EmitBytes(Contents.slice(Offset, UnitEnd));
677 LineSectionSize += UnitEnd - Offset;
679 Asm->OutStreamer->EmitLabel(EndLabel);
680 Offset = UnitEnd;
683 static void emitSectionContents(const object::ObjectFile &Obj,
684 StringRef SecName, MCStreamer *MS) {
685 if (auto Sec = getSectionByName(Obj, SecName)) {
686 if (Expected<StringRef> E = Sec->getContents())
687 MS->EmitBytes(*E);
688 else
689 consumeError(E.takeError());
693 void DwarfStreamer::copyInvariantDebugSection(const object::ObjectFile &Obj) {
694 if (!Options.Translator) {
695 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
696 emitSectionContents(Obj, "debug_line", MS);
699 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
700 emitSectionContents(Obj, "debug_loc", MS);
702 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
703 emitSectionContents(Obj, "debug_ranges", MS);
705 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
706 emitSectionContents(Obj, "debug_frame", MS);
708 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
709 emitSectionContents(Obj, "debug_aranges", MS);
712 /// Emit the pubnames or pubtypes section contribution for \p
713 /// Unit into \p Sec. The data is provided in \p Names.
714 void DwarfStreamer::emitPubSectionForUnit(
715 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
716 const std::vector<CompileUnit::AccelInfo> &Names) {
717 if (Names.empty())
718 return;
720 // Start the dwarf pubnames section.
721 Asm->OutStreamer->SwitchSection(Sec);
722 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
723 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
725 bool HeaderEmitted = false;
726 // Emit the pubnames for this compilation unit.
727 for (const auto &Name : Names) {
728 if (Name.SkipPubSection)
729 continue;
731 if (!HeaderEmitted) {
732 // Emit the header.
733 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
734 Asm->OutStreamer->EmitLabel(BeginLabel);
735 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
736 Asm->emitInt32(Unit.getStartOffset()); // Unit offset
737 Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
738 HeaderEmitted = true;
740 Asm->emitInt32(Name.Die->getOffset());
742 // Emit the string itself.
743 Asm->OutStreamer->EmitBytes(Name.Name.getString());
744 // Emit a null terminator.
745 Asm->emitInt8(0);
748 if (!HeaderEmitted)
749 return;
750 Asm->emitInt32(0); // End marker.
751 Asm->OutStreamer->EmitLabel(EndLabel);
754 /// Emit .debug_pubnames for \p Unit.
755 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
756 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
757 "names", Unit, Unit.getPubnames());
760 /// Emit .debug_pubtypes for \p Unit.
761 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
762 emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
763 "types", Unit, Unit.getPubtypes());
766 /// Emit a CIE into the debug_frame section.
767 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
768 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
770 MS->EmitBytes(CIEBytes);
771 FrameSectionSize += CIEBytes.size();
774 /// Emit a FDE into the debug_frame section. \p FDEBytes
775 /// contains the FDE data without the length, CIE offset and address
776 /// which will be replaced with the parameter values.
777 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
778 uint32_t Address, StringRef FDEBytes) {
779 MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
781 MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
782 MS->EmitIntValue(CIEOffset, 4);
783 MS->EmitIntValue(Address, AddrSize);
784 MS->EmitBytes(FDEBytes);
785 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
788 } // namespace dsymutil
789 } // namespace llvm