1//===- DwarfStreamer.cpp --------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/DWARFLinker/Classic/DWARFStreamer.h"
10#include "llvm/CodeGen/NonRelocatableStringpool.h"
11#include "llvm/DWARFLinker/Classic/DWARFLinkerCompileUnit.h"
12#include "llvm/DebugInfo/DWARF/DWARFContext.h"
13#include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h"
14#include "llvm/MC/MCAsmBackend.h"
15#include "llvm/MC/MCCodeEmitter.h"
16#include "llvm/MC/MCDwarf.h"
17#include "llvm/MC/MCInstPrinter.h"
18#include "llvm/MC/MCObjectWriter.h"
19#include "llvm/MC/MCSection.h"
20#include "llvm/MC/MCStreamer.h"
21#include "llvm/MC/MCTargetOptions.h"
22#include "llvm/MC/MCTargetOptionsCommandFlags.h"
23#include "llvm/MC/TargetRegistry.h"
24#include "llvm/Support/FormatVariadic.h"
25#include "llvm/Support/LEB128.h"
26#include "llvm/Target/TargetOptions.h"
27#include "llvm/TargetParser/Triple.h"
28
29using namespace llvm;
30using namespace dwarf_linker;
31using namespace dwarf_linker::classic;
32
33Expected<std::unique_ptr<DwarfStreamer>> DwarfStreamer::createStreamer(
34 const Triple &TheTriple, DWARFLinkerBase::OutputFileType FileType,
35 raw_pwrite_stream &OutFile, DWARFLinkerBase::MessageHandlerTy Warning) {
36 std::unique_ptr<DwarfStreamer> Streamer =
37 std::make_unique<DwarfStreamer>(args&: FileType, args&: OutFile, args&: Warning);
38 if (Error Err = Streamer->init(TheTriple, Swift5ReflectionSegmentName: "__DWARF"))
39 return std::move(Err);
40
41 return std::move(Streamer);
42}
43
44Error DwarfStreamer::init(Triple TheTriple,
45 StringRef Swift5ReflectionSegmentName) {
46 std::string ErrorStr;
47 std::string TripleName;
48
49 // Get the target.
50 const Target *TheTarget =
51 TargetRegistry::lookupTarget(ArchName: TripleName, TheTriple, Error&: ErrorStr);
52 if (!TheTarget)
53 return createStringError(EC: std::errc::invalid_argument, Fmt: ErrorStr.c_str());
54
55 TripleName = TheTriple.getTriple();
56
57 // Create all the MC Objects.
58 MRI.reset(p: TheTarget->createMCRegInfo(TT: TheTriple));
59 if (!MRI)
60 return createStringError(EC: std::errc::invalid_argument,
61 Fmt: "no register info for target %s",
62 Vals: TripleName.c_str());
63
64 MCOptions = mc::InitMCTargetOptionsFromFlags();
65 MCOptions.AsmVerbose = true;
66 MCOptions.MCUseDwarfDirectory = MCTargetOptions::EnableDwarfDirectory;
67 MAI.reset(p: TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
68 if (!MAI)
69 return createStringError(EC: std::errc::invalid_argument,
70 Fmt: "no asm info for target %s", Vals: TripleName.c_str());
71
72 MSTI.reset(p: TheTarget->createMCSubtargetInfo(TheTriple, CPU: "", Features: ""));
73 if (!MSTI)
74 return createStringError(EC: std::errc::invalid_argument,
75 Fmt: "no subtarget info for target %s",
76 Vals: TripleName.c_str());
77
78 MC.reset(p: new MCContext(TheTriple, *MAI, *MRI, *MSTI, nullptr, true,
79 Swift5ReflectionSegmentName));
80 MOFI.reset(p: TheTarget->createMCObjectFileInfo(Ctx&: *MC, /*PIC=*/false, LargeCodeModel: false));
81 MC->setObjectFileInfo(MOFI.get());
82
83 MAB = TheTarget->createMCAsmBackend(STI: *MSTI, MRI: *MRI, Options: MCOptions);
84 if (!MAB)
85 return createStringError(EC: std::errc::invalid_argument,
86 Fmt: "no asm backend for target %s",
87 Vals: TripleName.c_str());
88
89 MII.reset(p: TheTarget->createMCInstrInfo());
90 if (!MII)
91 return createStringError(EC: std::errc::invalid_argument,
92 Fmt: "no instr info info for target %s",
93 Vals: TripleName.c_str());
94
95 MCE = TheTarget->createMCCodeEmitter(II: *MII, Ctx&: *MC);
96 if (!MCE)
97 return createStringError(EC: std::errc::invalid_argument,
98 Fmt: "no code emitter for target %s",
99 Vals: TripleName.c_str());
100
101 switch (OutFileType) {
102 case DWARFLinker::OutputFileType::Assembly: {
103 std::unique_ptr<MCInstPrinter> MIP(TheTarget->createMCInstPrinter(
104 T: TheTriple, SyntaxVariant: MAI->getAssemblerDialect(), MAI: *MAI, MII: *MII, MRI: *MRI));
105 MS = TheTarget->createAsmStreamer(
106 Ctx&: *MC, OS: std::make_unique<formatted_raw_ostream>(args&: OutFile), IP: std::move(MIP),
107 CE: std::unique_ptr<MCCodeEmitter>(MCE),
108 TAB: std::unique_ptr<MCAsmBackend>(MAB));
109 break;
110 }
111 case DWARFLinker::OutputFileType::Object: {
112 MS = TheTarget->createMCObjectStreamer(
113 T: TheTriple, Ctx&: *MC, TAB: std::unique_ptr<MCAsmBackend>(MAB),
114 OW: MAB->createObjectWriter(OS&: OutFile), Emitter: std::unique_ptr<MCCodeEmitter>(MCE),
115 STI: *MSTI);
116 break;
117 }
118 }
119
120 if (!MS)
121 return createStringError(EC: std::errc::invalid_argument,
122 Fmt: "no object streamer for target %s",
123 Vals: TripleName.c_str());
124
125 // Finally create the AsmPrinter we'll use to emit the DIEs.
126 TM.reset(p: TheTarget->createTargetMachine(TT: TheTriple, CPU: "", Features: "", Options: TargetOptions(),
127 RM: std::nullopt));
128 if (!TM)
129 return createStringError(EC: std::errc::invalid_argument,
130 Fmt: "no target machine for target %s",
131 Vals: TripleName.c_str());
132
133 Asm.reset(p: TheTarget->createAsmPrinter(TM&: *TM, Streamer: std::unique_ptr<MCStreamer>(MS)));
134 if (!Asm)
135 return createStringError(EC: std::errc::invalid_argument,
136 Fmt: "no asm printer for target %s",
137 Vals: TripleName.c_str());
138 Asm->setDwarfUsesRelocationsAcrossSections(false);
139
140 RangesSectionSize = 0;
141 RngListsSectionSize = 0;
142 LocSectionSize = 0;
143 LocListsSectionSize = 0;
144 LineSectionSize = 0;
145 FrameSectionSize = 0;
146 DebugInfoSectionSize = 0;
147 MacInfoSectionSize = 0;
148 MacroSectionSize = 0;
149
150 return Error::success();
151}
152
153void DwarfStreamer::finish() { MS->finish(); }
154
155void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
156 MS->switchSection(Section: MOFI->getDwarfInfoSection());
157 MC->setDwarfVersion(DwarfVersion);
158}
159
160/// Emit the compilation unit header for \p Unit in the debug_info section.
161///
162/// A Dwarf 4 section header is encoded as:
163/// uint32_t Unit length (omitting this field)
164/// uint16_t Version
165/// uint32_t Abbreviation table offset
166/// uint8_t Address size
167/// Leading to a total of 11 bytes.
168///
169/// A Dwarf 5 section header is encoded as:
170/// uint32_t Unit length (omitting this field)
171/// uint16_t Version
172/// uint8_t Unit type
173/// uint8_t Address size
174/// uint32_t Abbreviation table offset
175/// Leading to a total of 12 bytes.
176void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit,
177 unsigned DwarfVersion) {
178 switchToDebugInfoSection(DwarfVersion);
179
180 /// The start of the unit within its section.
181 Unit.setLabelBegin(Asm->createTempSymbol(Name: "cu_begin"));
182 Asm->OutStreamer->emitLabel(Symbol: Unit.getLabelBegin());
183
184 // Emit size of content not including length itself. The size has already
185 // been computed in CompileUnit::computeOffsets(). Subtract 4 to that size to
186 // account for the length field.
187 Asm->emitInt32(Value: Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
188 Asm->emitInt16(Value: DwarfVersion);
189
190 if (DwarfVersion >= 5) {
191 Asm->emitInt8(Value: dwarf::DW_UT_compile);
192 Asm->emitInt8(Value: Unit.getOrigUnit().getAddressByteSize());
193 // We share one abbreviations table across all units so it's always at the
194 // start of the section.
195 Asm->emitInt32(Value: 0);
196 DebugInfoSectionSize += 12;
197 } else {
198 // We share one abbreviations table across all units so it's always at the
199 // start of the section.
200 Asm->emitInt32(Value: 0);
201 Asm->emitInt8(Value: Unit.getOrigUnit().getAddressByteSize());
202 DebugInfoSectionSize += 11;
203 }
204
205 // Remember this CU.
206 EmittedUnits.push_back(x: {.ID: Unit.getUniqueID(), .LabelBegin: Unit.getLabelBegin()});
207}
208
209/// Emit the \p Abbrevs array as the shared abbreviation table
210/// for the linked Dwarf file.
211void DwarfStreamer::emitAbbrevs(
212 const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs,
213 unsigned DwarfVersion) {
214 MS->switchSection(Section: MOFI->getDwarfAbbrevSection());
215 MC->setDwarfVersion(DwarfVersion);
216 Asm->emitDwarfAbbrevs(Abbrevs);
217}
218
219/// Recursively emit the DIE tree rooted at \p Die.
220void DwarfStreamer::emitDIE(DIE &Die) {
221 MS->switchSection(Section: MOFI->getDwarfInfoSection());
222 Asm->emitDwarfDIE(Die);
223 DebugInfoSectionSize += Die.getSize();
224}
225
226/// Emit contents of section SecName From Obj.
227void DwarfStreamer::emitSectionContents(StringRef SecData,
228 DebugSectionKind SecKind) {
229 if (SecData.empty())
230 return;
231
232 if (MCSection *Section = getMCSection(SecKind)) {
233 MS->switchSection(Section);
234
235 MS->emitBytes(Data: SecData);
236 }
237}
238
239MCSection *DwarfStreamer::getMCSection(DebugSectionKind SecKind) {
240 switch (SecKind) {
241 case DebugSectionKind::DebugInfo:
242 return MC->getObjectFileInfo()->getDwarfInfoSection();
243 case DebugSectionKind::DebugLine:
244 return MC->getObjectFileInfo()->getDwarfLineSection();
245 case DebugSectionKind::DebugFrame:
246 return MC->getObjectFileInfo()->getDwarfFrameSection();
247 case DebugSectionKind::DebugRange:
248 return MC->getObjectFileInfo()->getDwarfRangesSection();
249 case DebugSectionKind::DebugRngLists:
250 return MC->getObjectFileInfo()->getDwarfRnglistsSection();
251 case DebugSectionKind::DebugLoc:
252 return MC->getObjectFileInfo()->getDwarfLocSection();
253 case DebugSectionKind::DebugLocLists:
254 return MC->getObjectFileInfo()->getDwarfLoclistsSection();
255 case DebugSectionKind::DebugARanges:
256 return MC->getObjectFileInfo()->getDwarfARangesSection();
257 case DebugSectionKind::DebugAbbrev:
258 return MC->getObjectFileInfo()->getDwarfAbbrevSection();
259 case DebugSectionKind::DebugMacinfo:
260 return MC->getObjectFileInfo()->getDwarfMacinfoSection();
261 case DebugSectionKind::DebugMacro:
262 return MC->getObjectFileInfo()->getDwarfMacroSection();
263 case DebugSectionKind::DebugAddr:
264 return MC->getObjectFileInfo()->getDwarfAddrSection();
265 case DebugSectionKind::DebugStr:
266 return MC->getObjectFileInfo()->getDwarfStrSection();
267 case DebugSectionKind::DebugLineStr:
268 return MC->getObjectFileInfo()->getDwarfLineStrSection();
269 case DebugSectionKind::DebugStrOffsets:
270 return MC->getObjectFileInfo()->getDwarfStrOffSection();
271 case DebugSectionKind::DebugPubNames:
272 return MC->getObjectFileInfo()->getDwarfPubNamesSection();
273 case DebugSectionKind::DebugPubTypes:
274 return MC->getObjectFileInfo()->getDwarfPubTypesSection();
275 case DebugSectionKind::DebugNames:
276 return MC->getObjectFileInfo()->getDwarfDebugNamesSection();
277 case DebugSectionKind::AppleNames:
278 return MC->getObjectFileInfo()->getDwarfAccelNamesSection();
279 case DebugSectionKind::AppleNamespaces:
280 return MC->getObjectFileInfo()->getDwarfAccelNamespaceSection();
281 case DebugSectionKind::AppleObjC:
282 return MC->getObjectFileInfo()->getDwarfAccelObjCSection();
283 case DebugSectionKind::AppleTypes:
284 return MC->getObjectFileInfo()->getDwarfAccelTypesSection();
285 case DebugSectionKind::NumberOfEnumEntries:
286 llvm_unreachable("Unknown DebugSectionKind value");
287 break;
288 }
289
290 return nullptr;
291}
292
293/// Emit the debug_str section stored in \p Pool.
294void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
295 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfStrSection());
296 std::vector<DwarfStringPoolEntryRef> Entries = Pool.getEntriesForEmission();
297 for (auto Entry : Entries) {
298 // Emit the string itself.
299 Asm->OutStreamer->emitBytes(Data: Entry.getString());
300 // Emit a null terminator.
301 Asm->emitInt8(Value: 0);
302 }
303}
304
305/// Emit the debug string offset table described by \p StringOffsets into the
306/// .debug_str_offsets table.
307void DwarfStreamer::emitStringOffsets(
308 const SmallVector<uint64_t> &StringOffsets, uint16_t TargetDWARFVersion) {
309
310 if (TargetDWARFVersion < 5 || StringOffsets.empty())
311 return;
312
313 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfStrOffSection());
314
315 MCSymbol *BeginLabel = Asm->createTempSymbol(Name: "Bdebugstroff");
316 MCSymbol *EndLabel = Asm->createTempSymbol(Name: "Edebugstroff");
317
318 // Length.
319 Asm->emitLabelDifference(Hi: EndLabel, Lo: BeginLabel, Size: sizeof(uint32_t));
320 Asm->OutStreamer->emitLabel(Symbol: BeginLabel);
321 StrOffsetSectionSize += sizeof(uint32_t);
322
323 // Version.
324 MS->emitInt16(Value: 5);
325 StrOffsetSectionSize += sizeof(uint16_t);
326
327 // Padding.
328 MS->emitInt16(Value: 0);
329 StrOffsetSectionSize += sizeof(uint16_t);
330
331 for (auto Off : StringOffsets) {
332 Asm->OutStreamer->emitInt32(Value: Off);
333 StrOffsetSectionSize += sizeof(uint32_t);
334 }
335 Asm->OutStreamer->emitLabel(Symbol: EndLabel);
336}
337
338/// Emit the debug_line_str section stored in \p Pool.
339void DwarfStreamer::emitLineStrings(const NonRelocatableStringpool &Pool) {
340 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfLineStrSection());
341 std::vector<DwarfStringPoolEntryRef> Entries = Pool.getEntriesForEmission();
342 for (auto Entry : Entries) {
343 // Emit the string itself.
344 Asm->OutStreamer->emitBytes(Data: Entry.getString());
345 // Emit a null terminator.
346 Asm->emitInt8(Value: 0);
347 }
348}
349
350void DwarfStreamer::emitDebugNames(DWARF5AccelTable &Table) {
351 if (EmittedUnits.empty())
352 return;
353
354 // Build up data structures needed to emit this section.
355 std::vector<std::variant<MCSymbol *, uint64_t>> CompUnits;
356 DenseMap<unsigned, unsigned> UniqueIdToCuMap;
357 unsigned Id = 0;
358 for (auto &CU : EmittedUnits) {
359 CompUnits.push_back(x: CU.LabelBegin);
360 // We might be omitting CUs, so we need to remap them.
361 UniqueIdToCuMap[CU.ID] = Id++;
362 }
363
364 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfDebugNamesSection());
365 dwarf::Form Form = DIEInteger::BestForm(/*IsSigned*/ false,
366 Int: (uint64_t)UniqueIdToCuMap.size() - 1);
367 /// llvm-dwarfutil doesn't support type units + .debug_names right now.
368 // FIXME: add support for type units + .debug_names. For now the behavior is
369 // unsuported.
370 emitDWARF5AccelTable(
371 Asm: Asm.get(), Contents&: Table, CUs: CompUnits,
372 getIndexForEntry: [&](const DWARF5AccelTableData &Entry)
373 -> std::optional<DWARF5AccelTable::UnitIndexAndEncoding> {
374 if (UniqueIdToCuMap.size() > 1)
375 return {{.Index: UniqueIdToCuMap[Entry.getUnitID()],
376 .Encoding: {.Index: dwarf::DW_IDX_compile_unit, .Form: Form}}};
377 return std::nullopt;
378 });
379}
380
381void DwarfStreamer::emitAppleNamespaces(
382 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
383 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfAccelNamespaceSection());
384 auto *SectionBegin = Asm->createTempSymbol(Name: "namespac_begin");
385 Asm->OutStreamer->emitLabel(Symbol: SectionBegin);
386 emitAppleAccelTable(Asm: Asm.get(), Contents&: Table, Prefix: "namespac", SecBegin: SectionBegin);
387}
388
389void DwarfStreamer::emitAppleNames(
390 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
391 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfAccelNamesSection());
392 auto *SectionBegin = Asm->createTempSymbol(Name: "names_begin");
393 Asm->OutStreamer->emitLabel(Symbol: SectionBegin);
394 emitAppleAccelTable(Asm: Asm.get(), Contents&: Table, Prefix: "names", SecBegin: SectionBegin);
395}
396
397void DwarfStreamer::emitAppleObjc(
398 AccelTable<AppleAccelTableStaticOffsetData> &Table) {
399 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfAccelObjCSection());
400 auto *SectionBegin = Asm->createTempSymbol(Name: "objc_begin");
401 Asm->OutStreamer->emitLabel(Symbol: SectionBegin);
402 emitAppleAccelTable(Asm: Asm.get(), Contents&: Table, Prefix: "objc", SecBegin: SectionBegin);
403}
404
405void DwarfStreamer::emitAppleTypes(
406 AccelTable<AppleAccelTableStaticTypeData> &Table) {
407 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfAccelTypesSection());
408 auto *SectionBegin = Asm->createTempSymbol(Name: "types_begin");
409 Asm->OutStreamer->emitLabel(Symbol: SectionBegin);
410 emitAppleAccelTable(Asm: Asm.get(), Contents&: Table, Prefix: "types", SecBegin: SectionBegin);
411}
412
413/// Emit the swift_ast section stored in \p Buffers.
414void DwarfStreamer::emitSwiftAST(StringRef Buffer) {
415 MCSection *SwiftASTSection = MOFI->getDwarfSwiftASTSection();
416 SwiftASTSection->setAlignment(Align(32));
417 MS->switchSection(Section: SwiftASTSection);
418 MS->emitBytes(Data: Buffer);
419}
420
421void DwarfStreamer::emitSwiftReflectionSection(
422 llvm::binaryformat::Swift5ReflectionSectionKind ReflSectionKind,
423 StringRef Buffer, uint32_t Alignment, uint32_t Size) {
424 MCSection *ReflectionSection =
425 MOFI->getSwift5ReflectionSection(ReflSectionKind);
426 if (ReflectionSection == nullptr)
427 return;
428 ReflectionSection->setAlignment(Align(Alignment));
429 MS->switchSection(Section: ReflectionSection);
430 MS->emitBytes(Data: Buffer);
431}
432
433void DwarfStreamer::emitDwarfDebugArangesTable(
434 const CompileUnit &Unit, const AddressRanges &LinkedRanges) {
435 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
436
437 // Make .debug_aranges to be current section.
438 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfARangesSection());
439
440 // Emit Header.
441 MCSymbol *BeginLabel = Asm->createTempSymbol(Name: "Barange");
442 MCSymbol *EndLabel = Asm->createTempSymbol(Name: "Earange");
443
444 unsigned HeaderSize =
445 sizeof(int32_t) + // Size of contents (w/o this field
446 sizeof(int16_t) + // DWARF ARange version number
447 sizeof(int32_t) + // Offset of CU in the .debug_info section
448 sizeof(int8_t) + // Pointer Size (in bytes)
449 sizeof(int8_t); // Segment Size (in bytes)
450
451 unsigned TupleSize = AddressSize * 2;
452 unsigned Padding = offsetToAlignment(Value: HeaderSize, Alignment: Align(TupleSize));
453
454 Asm->emitLabelDifference(Hi: EndLabel, Lo: BeginLabel, Size: 4); // Arange length
455 Asm->OutStreamer->emitLabel(Symbol: BeginLabel);
456 Asm->emitInt16(Value: dwarf::DW_ARANGES_VERSION); // Version number
457 Asm->emitInt32(Value: Unit.getStartOffset()); // Corresponding unit's offset
458 Asm->emitInt8(Value: AddressSize); // Address size
459 Asm->emitInt8(Value: 0); // Segment size
460
461 Asm->OutStreamer->emitFill(NumBytes: Padding, FillValue: 0x0);
462
463 // Emit linked ranges.
464 for (const AddressRange &Range : LinkedRanges) {
465 MS->emitIntValue(Value: Range.start(), Size: AddressSize);
466 MS->emitIntValue(Value: Range.end() - Range.start(), Size: AddressSize);
467 }
468
469 // Emit terminator.
470 Asm->OutStreamer->emitIntValue(Value: 0, Size: AddressSize);
471 Asm->OutStreamer->emitIntValue(Value: 0, Size: AddressSize);
472 Asm->OutStreamer->emitLabel(Symbol: EndLabel);
473}
474
475Error DwarfStreamer::emitDwarfDebugRangesTableFragment(
476 const CompileUnit &Unit, const AddressRanges &LinkedRanges,
477 PatchLocation Patch) {
478 Expected<uint64_t> Offset = clampSecOffset(
479 Offset: RangesSectionSize, FP: Unit.getOrigUnit().getFormParams(), Section: ".debug_ranges");
480 if (!Offset)
481 return Offset.takeError();
482 Patch.set(*Offset);
483
484 // Make .debug_ranges to be current section.
485 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfRangesSection());
486 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
487
488 // Emit ranges.
489 uint64_t BaseAddress = 0;
490 if (std::optional<uint64_t> LowPC = Unit.getLowPc())
491 BaseAddress = *LowPC;
492
493 for (const AddressRange &Range : LinkedRanges) {
494 MS->emitIntValue(Value: Range.start() - BaseAddress, Size: AddressSize);
495 MS->emitIntValue(Value: Range.end() - BaseAddress, Size: AddressSize);
496
497 RangesSectionSize += AddressSize;
498 RangesSectionSize += AddressSize;
499 }
500
501 // Add the terminator entry.
502 MS->emitIntValue(Value: 0, Size: AddressSize);
503 MS->emitIntValue(Value: 0, Size: AddressSize);
504
505 RangesSectionSize += AddressSize;
506 RangesSectionSize += AddressSize;
507 return Error::success();
508}
509
510MCSymbol *
511DwarfStreamer::emitDwarfDebugRangeListHeader(const CompileUnit &Unit) {
512 if (Unit.getOrigUnit().getVersion() < 5)
513 return nullptr;
514
515 // Make .debug_rnglists to be current section.
516 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfRnglistsSection());
517
518 MCSymbol *BeginLabel = Asm->createTempSymbol(Name: "Brnglists");
519 MCSymbol *EndLabel = Asm->createTempSymbol(Name: "Ernglists");
520 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
521
522 // Length
523 Asm->emitLabelDifference(Hi: EndLabel, Lo: BeginLabel, Size: sizeof(uint32_t));
524 Asm->OutStreamer->emitLabel(Symbol: BeginLabel);
525 RngListsSectionSize += sizeof(uint32_t);
526
527 // Version.
528 MS->emitInt16(Value: 5);
529 RngListsSectionSize += sizeof(uint16_t);
530
531 // Address size.
532 MS->emitInt8(Value: AddressSize);
533 RngListsSectionSize++;
534
535 // Seg_size
536 MS->emitInt8(Value: 0);
537 RngListsSectionSize++;
538
539 // Offset entry count
540 MS->emitInt32(Value: 0);
541 RngListsSectionSize += sizeof(uint32_t);
542
543 return EndLabel;
544}
545
546Error DwarfStreamer::emitDwarfDebugRangeListFragment(
547 const CompileUnit &Unit, const AddressRanges &LinkedRanges,
548 PatchLocation Patch, DebugDieValuePool &AddrPool) {
549 if (Unit.getOrigUnit().getVersion() < 5) {
550 return emitDwarfDebugRangesTableFragment(Unit, LinkedRanges, Patch);
551 }
552
553 return emitDwarfDebugRngListsTableFragment(Unit, LinkedRanges, Patch,
554 AddrPool);
555}
556
557void DwarfStreamer::emitDwarfDebugRangeListFooter(const CompileUnit &Unit,
558 MCSymbol *EndLabel) {
559 if (Unit.getOrigUnit().getVersion() < 5)
560 return;
561
562 // Make .debug_rnglists to be current section.
563 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfRnglistsSection());
564
565 if (EndLabel != nullptr)
566 Asm->OutStreamer->emitLabel(Symbol: EndLabel);
567}
568
569Error DwarfStreamer::emitDwarfDebugRngListsTableFragment(
570 const CompileUnit &Unit, const AddressRanges &LinkedRanges,
571 PatchLocation Patch, DebugDieValuePool &AddrPool) {
572 Expected<uint64_t> Offset =
573 clampSecOffset(Offset: RngListsSectionSize, FP: Unit.getOrigUnit().getFormParams(),
574 Section: ".debug_rnglists");
575 if (!Offset)
576 return Offset.takeError();
577 Patch.set(*Offset);
578
579 // Make .debug_rnglists to be current section.
580 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfRnglistsSection());
581 std::optional<uint64_t> BaseAddress;
582
583 for (const AddressRange &Range : LinkedRanges) {
584
585 if (!BaseAddress) {
586 BaseAddress = Range.start();
587
588 // Emit base address.
589 MS->emitInt8(Value: dwarf::DW_RLE_base_addressx);
590 RngListsSectionSize += 1;
591 RngListsSectionSize +=
592 MS->emitULEB128IntValue(Value: AddrPool.getValueIndex(Value: *BaseAddress));
593 }
594
595 // Emit type of entry.
596 MS->emitInt8(Value: dwarf::DW_RLE_offset_pair);
597 RngListsSectionSize += 1;
598
599 // Emit start offset relative to base address.
600 RngListsSectionSize +=
601 MS->emitULEB128IntValue(Value: Range.start() - *BaseAddress);
602
603 // Emit end offset relative to base address.
604 RngListsSectionSize += MS->emitULEB128IntValue(Value: Range.end() - *BaseAddress);
605 }
606
607 // Emit the terminator entry.
608 MS->emitInt8(Value: dwarf::DW_RLE_end_of_list);
609 RngListsSectionSize += 1;
610 return Error::success();
611}
612
613/// Emit debug locations(.debug_loc, .debug_loclists) header.
614MCSymbol *DwarfStreamer::emitDwarfDebugLocListHeader(const CompileUnit &Unit) {
615 if (Unit.getOrigUnit().getVersion() < 5)
616 return nullptr;
617
618 // Make .debug_loclists the current section.
619 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfLoclistsSection());
620
621 MCSymbol *BeginLabel = Asm->createTempSymbol(Name: "Bloclists");
622 MCSymbol *EndLabel = Asm->createTempSymbol(Name: "Eloclists");
623 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
624
625 // Length
626 Asm->emitLabelDifference(Hi: EndLabel, Lo: BeginLabel, Size: sizeof(uint32_t));
627 Asm->OutStreamer->emitLabel(Symbol: BeginLabel);
628 LocListsSectionSize += sizeof(uint32_t);
629
630 // Version.
631 MS->emitInt16(Value: 5);
632 LocListsSectionSize += sizeof(uint16_t);
633
634 // Address size.
635 MS->emitInt8(Value: AddressSize);
636 LocListsSectionSize++;
637
638 // Seg_size
639 MS->emitInt8(Value: 0);
640 LocListsSectionSize++;
641
642 // Offset entry count
643 MS->emitInt32(Value: 0);
644 LocListsSectionSize += sizeof(uint32_t);
645
646 return EndLabel;
647}
648
649/// Emit debug locations(.debug_loc, .debug_loclists) fragment.
650Error DwarfStreamer::emitDwarfDebugLocListFragment(
651 const CompileUnit &Unit,
652 const DWARFLocationExpressionsVector &LinkedLocationExpression,
653 PatchLocation Patch, DebugDieValuePool &AddrPool) {
654 if (Unit.getOrigUnit().getVersion() < 5) {
655 return emitDwarfDebugLocTableFragment(Unit, LinkedLocationExpression,
656 Patch);
657 }
658
659 return emitDwarfDebugLocListsTableFragment(Unit, LinkedLocationExpression,
660 Patch, AddrPool);
661}
662
663/// Emit debug locations(.debug_loc, .debug_loclists) footer.
664void DwarfStreamer::emitDwarfDebugLocListFooter(const CompileUnit &Unit,
665 MCSymbol *EndLabel) {
666 if (Unit.getOrigUnit().getVersion() < 5)
667 return;
668
669 // Make .debug_loclists the current section.
670 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfLoclistsSection());
671
672 if (EndLabel != nullptr)
673 Asm->OutStreamer->emitLabel(Symbol: EndLabel);
674}
675
676/// Emit piece of .debug_loc for \p LinkedLocationExpression.
677Error DwarfStreamer::emitDwarfDebugLocTableFragment(
678 const CompileUnit &Unit,
679 const DWARFLocationExpressionsVector &LinkedLocationExpression,
680 PatchLocation Patch) {
681 Expected<uint64_t> Offset = clampSecOffset(
682 Offset: LocSectionSize, FP: Unit.getOrigUnit().getFormParams(), Section: ".debug_loc");
683 if (!Offset)
684 return Offset.takeError();
685 Patch.set(*Offset);
686
687 // Make .debug_loc to be current section.
688 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfLocSection());
689 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
690
691 // Emit ranges.
692 uint64_t BaseAddress = 0;
693 if (std::optional<uint64_t> LowPC = Unit.getLowPc())
694 BaseAddress = *LowPC;
695
696 for (const DWARFLocationExpression &LocExpression :
697 LinkedLocationExpression) {
698 if (LocExpression.Range) {
699 MS->emitIntValue(Value: LocExpression.Range->LowPC - BaseAddress, Size: AddressSize);
700 MS->emitIntValue(Value: LocExpression.Range->HighPC - BaseAddress, Size: AddressSize);
701
702 LocSectionSize += AddressSize;
703 LocSectionSize += AddressSize;
704 }
705
706 Asm->OutStreamer->emitIntValue(Value: LocExpression.Expr.size(), Size: 2);
707 Asm->OutStreamer->emitBytes(Data: StringRef(
708 (const char *)LocExpression.Expr.data(), LocExpression.Expr.size()));
709 LocSectionSize += LocExpression.Expr.size() + 2;
710 }
711
712 // Add the terminator entry.
713 MS->emitIntValue(Value: 0, Size: AddressSize);
714 MS->emitIntValue(Value: 0, Size: AddressSize);
715
716 LocSectionSize += AddressSize;
717 LocSectionSize += AddressSize;
718 return Error::success();
719}
720
721/// Emit .debug_addr header.
722MCSymbol *DwarfStreamer::emitDwarfDebugAddrsHeader(const CompileUnit &Unit) {
723
724 // Make .debug_addr the current section.
725 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfAddrSection());
726
727 MCSymbol *BeginLabel = Asm->createTempSymbol(Name: "Bdebugaddr");
728 MCSymbol *EndLabel = Asm->createTempSymbol(Name: "Edebugaddr");
729 unsigned AddrSize = Unit.getOrigUnit().getAddressByteSize();
730
731 // Emit length.
732 Asm->emitLabelDifference(Hi: EndLabel, Lo: BeginLabel, Size: sizeof(uint32_t));
733 Asm->OutStreamer->emitLabel(Symbol: BeginLabel);
734 AddrSectionSize += sizeof(uint32_t);
735
736 // Emit version.
737 Asm->emitInt16(Value: 5);
738 AddrSectionSize += 2;
739
740 // Emit address size.
741 Asm->emitInt8(Value: AddrSize);
742 AddrSectionSize += 1;
743
744 // Emit segment size.
745 Asm->emitInt8(Value: 0);
746 AddrSectionSize += 1;
747
748 return EndLabel;
749}
750
751/// Emit the .debug_addr addresses stored in \p Addrs.
752void DwarfStreamer::emitDwarfDebugAddrs(const SmallVector<uint64_t> &Addrs,
753 uint8_t AddrSize) {
754 Asm->OutStreamer->switchSection(Section: MOFI->getDwarfAddrSection());
755 for (auto Addr : Addrs) {
756 Asm->OutStreamer->emitIntValue(Value: Addr, Size: AddrSize);
757 AddrSectionSize += AddrSize;
758 }
759}
760
761/// Emit .debug_addr footer.
762void DwarfStreamer::emitDwarfDebugAddrsFooter(const CompileUnit &Unit,
763 MCSymbol *EndLabel) {
764
765 // Make .debug_addr the current section.
766 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfAddrSection());
767
768 if (EndLabel != nullptr)
769 Asm->OutStreamer->emitLabel(Symbol: EndLabel);
770}
771
772/// Emit piece of .debug_loclists for \p LinkedLocationExpression.
773Error DwarfStreamer::emitDwarfDebugLocListsTableFragment(
774 const CompileUnit &Unit,
775 const DWARFLocationExpressionsVector &LinkedLocationExpression,
776 PatchLocation Patch, DebugDieValuePool &AddrPool) {
777 Expected<uint64_t> Offset =
778 clampSecOffset(Offset: LocListsSectionSize, FP: Unit.getOrigUnit().getFormParams(),
779 Section: ".debug_loclists");
780 if (!Offset)
781 return Offset.takeError();
782 Patch.set(*Offset);
783
784 // Make .debug_loclists the current section.
785 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfLoclistsSection());
786 std::optional<uint64_t> BaseAddress;
787
788 for (const DWARFLocationExpression &LocExpression :
789 LinkedLocationExpression) {
790 if (LocExpression.Range) {
791
792 if (!BaseAddress) {
793
794 BaseAddress = LocExpression.Range->LowPC;
795
796 // Emit base address.
797 MS->emitInt8(Value: dwarf::DW_LLE_base_addressx);
798 LocListsSectionSize += 1;
799 LocListsSectionSize +=
800 MS->emitULEB128IntValue(Value: AddrPool.getValueIndex(Value: *BaseAddress));
801 }
802
803 // Emit type of entry.
804 MS->emitInt8(Value: dwarf::DW_LLE_offset_pair);
805 LocListsSectionSize += 1;
806
807 // Emit start offset relative to base address.
808 LocListsSectionSize +=
809 MS->emitULEB128IntValue(Value: LocExpression.Range->LowPC - *BaseAddress);
810
811 // Emit end offset relative to base address.
812 LocListsSectionSize +=
813 MS->emitULEB128IntValue(Value: LocExpression.Range->HighPC - *BaseAddress);
814 } else {
815 // Emit type of entry.
816 MS->emitInt8(Value: dwarf::DW_LLE_default_location);
817 LocListsSectionSize += 1;
818 }
819
820 LocListsSectionSize += MS->emitULEB128IntValue(Value: LocExpression.Expr.size());
821 Asm->OutStreamer->emitBytes(Data: StringRef(
822 (const char *)LocExpression.Expr.data(), LocExpression.Expr.size()));
823 LocListsSectionSize += LocExpression.Expr.size();
824 }
825
826 // Emit the terminator entry.
827 MS->emitInt8(Value: dwarf::DW_LLE_end_of_list);
828 LocListsSectionSize += 1;
829 return Error::success();
830}
831
832void DwarfStreamer::emitLineTableForUnit(
833 const DWARFDebugLine::LineTable &LineTable, const CompileUnit &Unit,
834 OffsetsStringPool &DebugStrPool, OffsetsStringPool &DebugLineStrPool,
835 std::vector<uint64_t> *RowOffsets) {
836 // Switch to the section where the table will be emitted into.
837 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfLineSection());
838
839 MCSymbol *LineStartSym = MC->createTempSymbol();
840 MCSymbol *LineEndSym = MC->createTempSymbol();
841
842 // unit_length.
843 if (LineTable.Prologue.FormParams.Format == dwarf::DwarfFormat::DWARF64) {
844 MS->emitInt32(Value: dwarf::DW_LENGTH_DWARF64);
845 LineSectionSize += 4;
846 }
847 emitLabelDifference(Hi: LineEndSym, Lo: LineStartSym,
848 Format: LineTable.Prologue.FormParams.Format, SectionSize&: LineSectionSize);
849 Asm->OutStreamer->emitLabel(Symbol: LineStartSym);
850
851 // Emit prologue.
852 emitLineTablePrologue(P: LineTable.Prologue, DebugStrPool, DebugLineStrPool);
853
854 // Emit rows.
855 emitLineTableRows(LineTable, LineEndSym,
856 AddressByteSize: Unit.getOrigUnit().getAddressByteSize(), RowOffsets);
857}
858
859void DwarfStreamer::emitLineTablePrologue(const DWARFDebugLine::Prologue &P,
860 OffsetsStringPool &DebugStrPool,
861 OffsetsStringPool &DebugLineStrPool) {
862 MCSymbol *PrologueStartSym = MC->createTempSymbol();
863 MCSymbol *PrologueEndSym = MC->createTempSymbol();
864
865 // version (uhalf).
866 MS->emitInt16(Value: P.getVersion());
867 LineSectionSize += 2;
868 if (P.getVersion() == 5) {
869 // address_size (ubyte).
870 MS->emitInt8(Value: P.getAddressSize());
871 LineSectionSize += 1;
872
873 // segment_selector_size (ubyte).
874 MS->emitInt8(Value: P.SegSelectorSize);
875 LineSectionSize += 1;
876 }
877
878 // header_length.
879 emitLabelDifference(Hi: PrologueEndSym, Lo: PrologueStartSym, Format: P.FormParams.Format,
880 SectionSize&: LineSectionSize);
881
882 Asm->OutStreamer->emitLabel(Symbol: PrologueStartSym);
883 emitLineTableProloguePayload(P, DebugStrPool, DebugLineStrPool);
884 Asm->OutStreamer->emitLabel(Symbol: PrologueEndSym);
885}
886
887void DwarfStreamer::emitLineTablePrologueV2IncludeAndFileTable(
888 const DWARFDebugLine::Prologue &P, OffsetsStringPool &DebugStrPool,
889 OffsetsStringPool &DebugLineStrPool) {
890 // include_directories (sequence of path names).
891 for (const DWARFFormValue &Include : P.IncludeDirectories)
892 emitLineTableString(P, String: Include, DebugStrPool, DebugLineStrPool);
893 // The last entry is followed by a single null byte.
894 MS->emitInt8(Value: 0);
895 LineSectionSize += 1;
896
897 // file_names (sequence of file entries).
898 for (const DWARFDebugLine::FileNameEntry &File : P.FileNames) {
899 // A null-terminated string containing the full or relative path name of a
900 // source file.
901 emitLineTableString(P, String: File.Name, DebugStrPool, DebugLineStrPool);
902 // An unsigned LEB128 number representing the directory index of a directory
903 // in the include_directories section.
904 LineSectionSize += MS->emitULEB128IntValue(Value: File.DirIdx);
905 // An unsigned LEB128 number representing the (implementation-defined) time
906 // of last modification for the file, or 0 if not available.
907 LineSectionSize += MS->emitULEB128IntValue(Value: File.ModTime);
908 // An unsigned LEB128 number representing the length in bytes of the file,
909 // or 0 if not available.
910 LineSectionSize += MS->emitULEB128IntValue(Value: File.Length);
911 }
912 // The last entry is followed by a single null byte.
913 MS->emitInt8(Value: 0);
914 LineSectionSize += 1;
915}
916
917void DwarfStreamer::emitLineTablePrologueV5IncludeAndFileTable(
918 const DWARFDebugLine::Prologue &P, OffsetsStringPool &DebugStrPool,
919 OffsetsStringPool &DebugLineStrPool) {
920 if (P.IncludeDirectories.empty()) {
921 // directory_entry_format_count(ubyte).
922 MS->emitInt8(Value: 0);
923 LineSectionSize += 1;
924 } else {
925 // directory_entry_format_count(ubyte).
926 MS->emitInt8(Value: 1);
927 LineSectionSize += 1;
928
929 // directory_entry_format (sequence of ULEB128 pairs).
930 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_LNCT_path);
931 LineSectionSize +=
932 MS->emitULEB128IntValue(Value: P.IncludeDirectories[0].getForm());
933 }
934
935 // directories_count (ULEB128).
936 LineSectionSize += MS->emitULEB128IntValue(Value: P.IncludeDirectories.size());
937 // directories (sequence of directory names).
938 for (auto Include : P.IncludeDirectories)
939 emitLineTableString(P, String: Include, DebugStrPool, DebugLineStrPool);
940
941 bool HasChecksums = P.ContentTypes.HasMD5;
942 bool HasInlineSources = P.ContentTypes.HasSource;
943
944 if (P.FileNames.empty()) {
945 // file_name_entry_format_count (ubyte).
946 MS->emitInt8(Value: 0);
947 LineSectionSize += 1;
948 } else {
949 // file_name_entry_format_count (ubyte).
950 MS->emitInt8(Value: 2 + (HasChecksums ? 1 : 0) + (HasInlineSources ? 1 : 0));
951 LineSectionSize += 1;
952
953 // file_name_entry_format (sequence of ULEB128 pairs).
954 auto StrForm = P.FileNames[0].Name.getForm();
955 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_LNCT_path);
956 LineSectionSize += MS->emitULEB128IntValue(Value: StrForm);
957
958 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_LNCT_directory_index);
959 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_FORM_udata);
960
961 if (HasChecksums) {
962 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_LNCT_MD5);
963 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_FORM_data16);
964 }
965
966 if (HasInlineSources) {
967 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_LNCT_LLVM_source);
968 LineSectionSize += MS->emitULEB128IntValue(Value: StrForm);
969 }
970 }
971
972 // file_names_count (ULEB128).
973 LineSectionSize += MS->emitULEB128IntValue(Value: P.FileNames.size());
974
975 // file_names (sequence of file name entries).
976 for (auto File : P.FileNames) {
977 emitLineTableString(P, String: File.Name, DebugStrPool, DebugLineStrPool);
978 LineSectionSize += MS->emitULEB128IntValue(Value: File.DirIdx);
979 if (HasChecksums) {
980 MS->emitBinaryData(
981 Data: StringRef(reinterpret_cast<const char *>(File.Checksum.data()),
982 File.Checksum.size()));
983 LineSectionSize += File.Checksum.size();
984 }
985 if (HasInlineSources)
986 emitLineTableString(P, String: File.Source, DebugStrPool, DebugLineStrPool);
987 }
988}
989
990void DwarfStreamer::emitLineTableString(const DWARFDebugLine::Prologue &P,
991 const DWARFFormValue &String,
992 OffsetsStringPool &DebugStrPool,
993 OffsetsStringPool &DebugLineStrPool) {
994 std::optional<const char *> StringVal = dwarf::toString(V: String);
995 if (!StringVal) {
996 warn(Warning: "Cann't read string from line table.");
997 return;
998 }
999
1000 switch (String.getForm()) {
1001 case dwarf::DW_FORM_string: {
1002 StringRef Str = *StringVal;
1003 Asm->OutStreamer->emitBytes(Data: Str.data());
1004 Asm->emitInt8(Value: 0);
1005 LineSectionSize += Str.size() + 1;
1006 } break;
1007 case dwarf::DW_FORM_strp:
1008 case dwarf::DW_FORM_line_strp: {
1009 DwarfStringPoolEntryRef StringRef =
1010 String.getForm() == dwarf::DW_FORM_strp
1011 ? DebugStrPool.getEntry(S: *StringVal)
1012 : DebugLineStrPool.getEntry(S: *StringVal);
1013
1014 emitIntOffset(Offset: StringRef.getOffset(), Format: P.FormParams.Format, SectionSize&: LineSectionSize);
1015 } break;
1016 default:
1017 warn(Warning: "Unsupported string form inside line table.");
1018 break;
1019 };
1020}
1021
1022void DwarfStreamer::emitLineTableProloguePayload(
1023 const DWARFDebugLine::Prologue &P, OffsetsStringPool &DebugStrPool,
1024 OffsetsStringPool &DebugLineStrPool) {
1025 // minimum_instruction_length (ubyte).
1026 MS->emitInt8(Value: P.MinInstLength);
1027 LineSectionSize += 1;
1028 if (P.FormParams.Version >= 4) {
1029 // maximum_operations_per_instruction (ubyte).
1030 MS->emitInt8(Value: P.MaxOpsPerInst);
1031 LineSectionSize += 1;
1032 }
1033 // default_is_stmt (ubyte).
1034 MS->emitInt8(Value: P.DefaultIsStmt);
1035 LineSectionSize += 1;
1036 // line_base (sbyte).
1037 MS->emitInt8(Value: P.LineBase);
1038 LineSectionSize += 1;
1039 // line_range (ubyte).
1040 MS->emitInt8(Value: P.LineRange);
1041 LineSectionSize += 1;
1042 // opcode_base (ubyte).
1043 MS->emitInt8(Value: P.OpcodeBase);
1044 LineSectionSize += 1;
1045
1046 // standard_opcode_lengths (array of ubyte).
1047 for (auto Length : P.StandardOpcodeLengths) {
1048 MS->emitInt8(Value: Length);
1049 LineSectionSize += 1;
1050 }
1051
1052 if (P.FormParams.Version < 5)
1053 emitLineTablePrologueV2IncludeAndFileTable(P, DebugStrPool,
1054 DebugLineStrPool);
1055 else
1056 emitLineTablePrologueV5IncludeAndFileTable(P, DebugStrPool,
1057 DebugLineStrPool);
1058}
1059
1060void DwarfStreamer::emitLineTableRows(
1061 const DWARFDebugLine::LineTable &LineTable, MCSymbol *LineEndSym,
1062 unsigned AddressByteSize, std::vector<uint64_t> *RowOffsets) {
1063
1064 MCDwarfLineTableParams Params;
1065 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
1066 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
1067 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
1068
1069 SmallString<128> EncodingBuffer;
1070
1071 if (LineTable.Rows.empty()) {
1072 // We only have the dummy entry, dsymutil emits an entry with a 0
1073 // address in that case.
1074 MCDwarfLineAddr::encode(Context&: *MC, Params, LineDelta: std::numeric_limits<int64_t>::max(), AddrDelta: 0,
1075 OS&: EncodingBuffer);
1076 MS->emitBytes(Data: EncodingBuffer);
1077 LineSectionSize += EncodingBuffer.size();
1078 MS->emitLabel(Symbol: LineEndSym);
1079 return;
1080 }
1081
1082 // Line table state machine fields
1083 unsigned FileNum = 1;
1084 unsigned LastLine = 1;
1085 unsigned Column = 0;
1086 unsigned Discriminator = 0;
1087 unsigned IsStatement = 1;
1088 unsigned Isa = 0;
1089 uint64_t Address = -1ULL;
1090
1091 unsigned RowsSinceLastSequence = 0;
1092
1093 for (const DWARFDebugLine::Row &Row : LineTable.Rows) {
1094 // If we're tracking row offsets, record the current section size as the
1095 // offset of this row.
1096 if (RowOffsets)
1097 RowOffsets->push_back(x: LineSectionSize);
1098
1099 int64_t AddressDelta;
1100 if (Address == -1ULL) {
1101 MS->emitIntValue(Value: dwarf::DW_LNS_extended_op, Size: 1);
1102 MS->emitULEB128IntValue(Value: AddressByteSize + 1);
1103 MS->emitIntValue(Value: dwarf::DW_LNE_set_address, Size: 1);
1104 MS->emitIntValue(Value: Row.Address.Address, Size: AddressByteSize);
1105 LineSectionSize +=
1106 2 + AddressByteSize + getULEB128Size(Value: AddressByteSize + 1);
1107 AddressDelta = 0;
1108 } else {
1109 AddressDelta =
1110 (Row.Address.Address - Address) / LineTable.Prologue.MinInstLength;
1111 }
1112
1113 // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable.
1114 // We should find a way to share this code, but the current compatibility
1115 // requirement with classic dsymutil makes it hard. Revisit that once this
1116 // requirement is dropped.
1117
1118 if (FileNum != Row.File) {
1119 FileNum = Row.File;
1120 MS->emitIntValue(Value: dwarf::DW_LNS_set_file, Size: 1);
1121 MS->emitULEB128IntValue(Value: FileNum);
1122 LineSectionSize += 1 + getULEB128Size(Value: FileNum);
1123 }
1124 if (Column != Row.Column) {
1125 Column = Row.Column;
1126 MS->emitIntValue(Value: dwarf::DW_LNS_set_column, Size: 1);
1127 MS->emitULEB128IntValue(Value: Column);
1128 LineSectionSize += 1 + getULEB128Size(Value: Column);
1129 }
1130 if (Discriminator != Row.Discriminator &&
1131 MS->getContext().getDwarfVersion() >= 4) {
1132 Discriminator = Row.Discriminator;
1133 unsigned Size = getULEB128Size(Value: Discriminator);
1134 MS->emitIntValue(Value: dwarf::DW_LNS_extended_op, Size: 1);
1135 MS->emitULEB128IntValue(Value: Size + 1);
1136 MS->emitIntValue(Value: dwarf::DW_LNE_set_discriminator, Size: 1);
1137 MS->emitULEB128IntValue(Value: Discriminator);
1138 LineSectionSize += /* extended op */ 1 + getULEB128Size(Value: Size + 1) +
1139 /* discriminator */ 1 + Size;
1140 }
1141 Discriminator = 0;
1142
1143 if (Isa != Row.Isa) {
1144 Isa = Row.Isa;
1145 MS->emitIntValue(Value: dwarf::DW_LNS_set_isa, Size: 1);
1146 MS->emitULEB128IntValue(Value: Isa);
1147 LineSectionSize += 1 + getULEB128Size(Value: Isa);
1148 }
1149 if (IsStatement != Row.IsStmt) {
1150 IsStatement = Row.IsStmt;
1151 MS->emitIntValue(Value: dwarf::DW_LNS_negate_stmt, Size: 1);
1152 LineSectionSize += 1;
1153 }
1154 if (Row.BasicBlock) {
1155 MS->emitIntValue(Value: dwarf::DW_LNS_set_basic_block, Size: 1);
1156 LineSectionSize += 1;
1157 }
1158
1159 if (Row.PrologueEnd) {
1160 MS->emitIntValue(Value: dwarf::DW_LNS_set_prologue_end, Size: 1);
1161 LineSectionSize += 1;
1162 }
1163
1164 if (Row.EpilogueBegin) {
1165 MS->emitIntValue(Value: dwarf::DW_LNS_set_epilogue_begin, Size: 1);
1166 LineSectionSize += 1;
1167 }
1168
1169 int64_t LineDelta = int64_t(Row.Line) - LastLine;
1170 if (!Row.EndSequence) {
1171 MCDwarfLineAddr::encode(Context&: *MC, Params, LineDelta, AddrDelta: AddressDelta,
1172 OS&: EncodingBuffer);
1173 MS->emitBytes(Data: EncodingBuffer);
1174 LineSectionSize += EncodingBuffer.size();
1175 EncodingBuffer.resize(N: 0);
1176 Address = Row.Address.Address;
1177 LastLine = Row.Line;
1178 RowsSinceLastSequence++;
1179 } else {
1180 if (LineDelta) {
1181 MS->emitIntValue(Value: dwarf::DW_LNS_advance_line, Size: 1);
1182 MS->emitSLEB128IntValue(Value: LineDelta);
1183 LineSectionSize += 1 + getSLEB128Size(Value: LineDelta);
1184 }
1185 if (AddressDelta) {
1186 MS->emitIntValue(Value: dwarf::DW_LNS_advance_pc, Size: 1);
1187 MS->emitULEB128IntValue(Value: AddressDelta);
1188 LineSectionSize += 1 + getULEB128Size(Value: AddressDelta);
1189 }
1190 MCDwarfLineAddr::encode(Context&: *MC, Params, LineDelta: std::numeric_limits<int64_t>::max(),
1191 AddrDelta: 0, OS&: EncodingBuffer);
1192 MS->emitBytes(Data: EncodingBuffer);
1193 LineSectionSize += EncodingBuffer.size();
1194 EncodingBuffer.resize(N: 0);
1195 Address = -1ULL;
1196 LastLine = FileNum = IsStatement = 1;
1197 RowsSinceLastSequence = Column = Discriminator = Isa = 0;
1198 }
1199 }
1200
1201 if (RowsSinceLastSequence) {
1202 MCDwarfLineAddr::encode(Context&: *MC, Params, LineDelta: std::numeric_limits<int64_t>::max(), AddrDelta: 0,
1203 OS&: EncodingBuffer);
1204 MS->emitBytes(Data: EncodingBuffer);
1205 LineSectionSize += EncodingBuffer.size();
1206 EncodingBuffer.resize(N: 0);
1207 }
1208
1209 MS->emitLabel(Symbol: LineEndSym);
1210}
1211
1212void DwarfStreamer::emitIntOffset(uint64_t Offset, dwarf::DwarfFormat Format,
1213 uint64_t &SectionSize) {
1214 uint8_t Size = dwarf::getDwarfOffsetByteSize(Format);
1215 MS->emitIntValue(Value: Offset, Size);
1216 SectionSize += Size;
1217}
1218
1219void DwarfStreamer::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1220 dwarf::DwarfFormat Format,
1221 uint64_t &SectionSize) {
1222 uint8_t Size = dwarf::getDwarfOffsetByteSize(Format);
1223 Asm->emitLabelDifference(Hi, Lo, Size);
1224 SectionSize += Size;
1225}
1226
1227/// Emit the pubnames or pubtypes section contribution for \p
1228/// Unit into \p Sec. The data is provided in \p Names.
1229void DwarfStreamer::emitPubSectionForUnit(
1230 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
1231 const std::vector<CompileUnit::AccelInfo> &Names) {
1232 if (Names.empty())
1233 return;
1234
1235 // Start the dwarf pubnames section.
1236 Asm->OutStreamer->switchSection(Section: Sec);
1237 MCSymbol *BeginLabel = Asm->createTempSymbol(Name: "pub" + SecName + "_begin");
1238 MCSymbol *EndLabel = Asm->createTempSymbol(Name: "pub" + SecName + "_end");
1239
1240 bool HeaderEmitted = false;
1241 // Emit the pubnames for this compilation unit.
1242 for (const auto &Name : Names) {
1243 if (Name.SkipPubSection)
1244 continue;
1245
1246 if (!HeaderEmitted) {
1247 // Emit the header.
1248 Asm->emitLabelDifference(Hi: EndLabel, Lo: BeginLabel, Size: 4); // Length
1249 Asm->OutStreamer->emitLabel(Symbol: BeginLabel);
1250 Asm->emitInt16(Value: dwarf::DW_PUBNAMES_VERSION); // Version
1251 Asm->emitInt32(Value: Unit.getStartOffset()); // Unit offset
1252 Asm->emitInt32(Value: Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1253 HeaderEmitted = true;
1254 }
1255 Asm->emitInt32(Value: Name.Die->getOffset());
1256
1257 // Emit the string itself.
1258 Asm->OutStreamer->emitBytes(Data: Name.Name.getString());
1259 // Emit a null terminator.
1260 Asm->emitInt8(Value: 0);
1261 }
1262
1263 if (!HeaderEmitted)
1264 return;
1265 Asm->emitInt32(Value: 0); // End marker.
1266 Asm->OutStreamer->emitLabel(Symbol: EndLabel);
1267}
1268
1269/// Emit .debug_pubnames for \p Unit.
1270void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1271 emitPubSectionForUnit(Sec: MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1272 SecName: "names", Unit, Names: Unit.getPubnames());
1273}
1274
1275/// Emit .debug_pubtypes for \p Unit.
1276void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1277 emitPubSectionForUnit(Sec: MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1278 SecName: "types", Unit, Names: Unit.getPubtypes());
1279}
1280
1281/// Emit a CIE into the debug_frame section.
1282void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1283 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfFrameSection());
1284
1285 MS->emitBytes(Data: CIEBytes);
1286 FrameSectionSize += CIEBytes.size();
1287}
1288
1289/// Emit a FDE into the debug_frame section. \p FDEBytes
1290/// contains the FDE data without the length, CIE offset and address
1291/// which will be replaced with the parameter values.
1292void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1293 uint64_t Address, StringRef FDEBytes) {
1294 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfFrameSection());
1295
1296 MS->emitIntValue(Value: FDEBytes.size() + 4 + AddrSize, Size: 4);
1297 MS->emitIntValue(Value: CIEOffset, Size: 4);
1298 MS->emitIntValue(Value: Address, Size: AddrSize);
1299 MS->emitBytes(Data: FDEBytes);
1300 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1301}
1302
1303void DwarfStreamer::emitMacroTables(DWARFContext *Context,
1304 const Offset2UnitMap &UnitMacroMap,
1305 OffsetsStringPool &StringPool) {
1306 assert(Context != nullptr && "Empty DWARF context");
1307
1308 // Check for .debug_macinfo table.
1309 if (const DWARFDebugMacro *Table = Context->getDebugMacinfo()) {
1310 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfMacinfoSection());
1311 emitMacroTableImpl(MacroTable: Table, UnitMacroMap, StringPool, OutOffset&: MacInfoSectionSize);
1312 }
1313
1314 // Check for .debug_macro table.
1315 if (const DWARFDebugMacro *Table = Context->getDebugMacro()) {
1316 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfMacroSection());
1317 emitMacroTableImpl(MacroTable: Table, UnitMacroMap, StringPool, OutOffset&: MacroSectionSize);
1318 }
1319}
1320
1321void DwarfStreamer::emitMacroTableImpl(const DWARFDebugMacro *MacroTable,
1322 const Offset2UnitMap &UnitMacroMap,
1323 OffsetsStringPool &StringPool,
1324 uint64_t &OutOffset) {
1325 bool DefAttributeIsReported = false;
1326 bool UndefAttributeIsReported = false;
1327 bool ImportAttributeIsReported = false;
1328 for (const DWARFDebugMacro::MacroList &List : MacroTable->MacroLists) {
1329 Offset2UnitMap::const_iterator UnitIt = UnitMacroMap.find(Val: List.Offset);
1330 if (UnitIt == UnitMacroMap.end()) {
1331 warn(Warning: formatv(
1332 Fmt: "couldn`t find compile unit for the macro table with offset = {0:x}",
1333 Vals: List.Offset));
1334 continue;
1335 }
1336
1337 // Skip macro table if the unit was not cloned.
1338 DIE *OutputUnitDIE = UnitIt->second->getOutputUnitDIE();
1339 if (OutputUnitDIE == nullptr)
1340 continue;
1341
1342 // Update macro attribute of cloned compile unit with the proper offset to
1343 // the macro table.
1344 bool hasDWARFv5Header = false;
1345 for (auto &V : OutputUnitDIE->values()) {
1346 if (V.getAttribute() == dwarf::DW_AT_macro_info) {
1347 V = DIEValue(V.getAttribute(), V.getForm(), DIEInteger(OutOffset));
1348 break;
1349 } else if (V.getAttribute() == dwarf::DW_AT_macros) {
1350 hasDWARFv5Header = true;
1351 V = DIEValue(V.getAttribute(), V.getForm(), DIEInteger(OutOffset));
1352 break;
1353 }
1354 }
1355
1356 // Write DWARFv5 header.
1357 if (hasDWARFv5Header) {
1358 // Write header version.
1359 MS->emitIntValue(Value: List.Header.Version, Size: sizeof(List.Header.Version));
1360 OutOffset += sizeof(List.Header.Version);
1361
1362 uint8_t Flags = List.Header.Flags;
1363
1364 // Check for OPCODE_OPERANDS_TABLE.
1365 if (Flags &
1366 DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE) {
1367 Flags &= ~DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE;
1368 warn(Warning: "opcode_operands_table is not supported yet.");
1369 }
1370
1371 // Check for DEBUG_LINE_OFFSET.
1372 std::optional<uint64_t> StmtListOffset;
1373 if (Flags & DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET) {
1374 // Get offset to the line table from the cloned compile unit.
1375 for (auto &V : OutputUnitDIE->values()) {
1376 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
1377 StmtListOffset = V.getDIEInteger().getValue();
1378 break;
1379 }
1380 }
1381
1382 if (!StmtListOffset) {
1383 Flags &= ~DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET;
1384 warn(Warning: "couldn`t find line table for macro table.");
1385 }
1386 }
1387
1388 // Write flags.
1389 MS->emitIntValue(Value: Flags, Size: sizeof(Flags));
1390 OutOffset += sizeof(Flags);
1391
1392 // Write offset to line table.
1393 if (StmtListOffset) {
1394 MS->emitIntValue(Value: *StmtListOffset, Size: List.Header.getOffsetByteSize());
1395 OutOffset += List.Header.getOffsetByteSize();
1396 }
1397 }
1398
1399 // Write macro entries.
1400 for (const DWARFDebugMacro::Entry &MacroEntry : List.Macros) {
1401 if (MacroEntry.Type == 0) {
1402 OutOffset += MS->emitULEB128IntValue(Value: MacroEntry.Type);
1403 continue;
1404 }
1405
1406 uint8_t MacroType = MacroEntry.Type;
1407 switch (MacroType) {
1408 default: {
1409 bool HasVendorSpecificExtension =
1410 (!hasDWARFv5Header && MacroType == dwarf::DW_MACINFO_vendor_ext) ||
1411 (hasDWARFv5Header && (MacroType >= dwarf::DW_MACRO_lo_user &&
1412 MacroType <= dwarf::DW_MACRO_hi_user));
1413
1414 if (HasVendorSpecificExtension) {
1415 // Write macinfo type.
1416 MS->emitIntValue(Value: MacroType, Size: 1);
1417 OutOffset++;
1418
1419 // Write vendor extension constant.
1420 OutOffset += MS->emitULEB128IntValue(Value: MacroEntry.ExtConstant);
1421
1422 // Write vendor extension string.
1423 StringRef String = MacroEntry.ExtStr;
1424 MS->emitBytes(Data: String);
1425 MS->emitIntValue(Value: 0, Size: 1);
1426 OutOffset += String.size() + 1;
1427 } else
1428 warn(Warning: "unknown macro type. skip.");
1429 } break;
1430 // debug_macro and debug_macinfo share some common encodings.
1431 // DW_MACRO_define == DW_MACINFO_define
1432 // DW_MACRO_undef == DW_MACINFO_undef
1433 // DW_MACRO_start_file == DW_MACINFO_start_file
1434 // DW_MACRO_end_file == DW_MACINFO_end_file
1435 // For readibility/uniformity we are using DW_MACRO_*.
1436 case dwarf::DW_MACRO_define:
1437 case dwarf::DW_MACRO_undef: {
1438 // Write macinfo type.
1439 MS->emitIntValue(Value: MacroType, Size: 1);
1440 OutOffset++;
1441
1442 // Write source line.
1443 OutOffset += MS->emitULEB128IntValue(Value: MacroEntry.Line);
1444
1445 // Write macro string.
1446 StringRef String = MacroEntry.MacroStr;
1447 MS->emitBytes(Data: String);
1448 MS->emitIntValue(Value: 0, Size: 1);
1449 OutOffset += String.size() + 1;
1450 } break;
1451 case dwarf::DW_MACRO_define_strp:
1452 case dwarf::DW_MACRO_undef_strp:
1453 case dwarf::DW_MACRO_define_strx:
1454 case dwarf::DW_MACRO_undef_strx: {
1455 assert(UnitIt->second->getOrigUnit().getVersion() >= 5);
1456
1457 // DW_MACRO_*_strx forms are not supported currently.
1458 // Convert to *_strp.
1459 switch (MacroType) {
1460 case dwarf::DW_MACRO_define_strx: {
1461 MacroType = dwarf::DW_MACRO_define_strp;
1462 if (!DefAttributeIsReported) {
1463 warn(Warning: "DW_MACRO_define_strx unsupported yet. Convert to "
1464 "DW_MACRO_define_strp.");
1465 DefAttributeIsReported = true;
1466 }
1467 } break;
1468 case dwarf::DW_MACRO_undef_strx: {
1469 MacroType = dwarf::DW_MACRO_undef_strp;
1470 if (!UndefAttributeIsReported) {
1471 warn(Warning: "DW_MACRO_undef_strx unsupported yet. Convert to "
1472 "DW_MACRO_undef_strp.");
1473 UndefAttributeIsReported = true;
1474 }
1475 } break;
1476 default:
1477 // Nothing to do.
1478 break;
1479 }
1480
1481 // Write macinfo type.
1482 MS->emitIntValue(Value: MacroType, Size: 1);
1483 OutOffset++;
1484
1485 // Write source line.
1486 OutOffset += MS->emitULEB128IntValue(Value: MacroEntry.Line);
1487
1488 // Write macro string.
1489 DwarfStringPoolEntryRef EntryRef =
1490 StringPool.getEntry(S: MacroEntry.MacroStr);
1491 MS->emitIntValue(Value: EntryRef.getOffset(), Size: List.Header.getOffsetByteSize());
1492 OutOffset += List.Header.getOffsetByteSize();
1493 break;
1494 }
1495 case dwarf::DW_MACRO_start_file: {
1496 // Write macinfo type.
1497 MS->emitIntValue(Value: MacroType, Size: 1);
1498 OutOffset++;
1499 // Write source line.
1500 OutOffset += MS->emitULEB128IntValue(Value: MacroEntry.Line);
1501 // Write source file id.
1502 OutOffset += MS->emitULEB128IntValue(Value: MacroEntry.File);
1503 } break;
1504 case dwarf::DW_MACRO_end_file: {
1505 // Write macinfo type.
1506 MS->emitIntValue(Value: MacroType, Size: 1);
1507 OutOffset++;
1508 } break;
1509 case dwarf::DW_MACRO_import:
1510 case dwarf::DW_MACRO_import_sup: {
1511 if (!ImportAttributeIsReported) {
1512 warn(Warning: "DW_MACRO_import and DW_MACRO_import_sup are unsupported yet. "
1513 "remove.");
1514 ImportAttributeIsReported = true;
1515 }
1516 } break;
1517 }
1518 }
1519 }
1520}
1521