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/TargetRegistry.h"
23#include "llvm/Support/FormatVariadic.h"
24#include "llvm/Support/LEB128.h"
25#include "llvm/Target/TargetOptions.h"
26#include "llvm/TargetParser/Triple.h"
27
28using namespace llvm;
29using namespace dwarf_linker;
30using namespace dwarf_linker::classic;
31
32Expected<std::unique_ptr<DwarfStreamer>> DwarfStreamer::createStreamer(
33 const Triple &TheTriple, DWARFLinkerBase::OutputFileType FileType,
34 raw_pwrite_stream &OutFile, DWARFLinkerBase::MessageHandlerTy Warning) {
35 std::unique_ptr<DwarfStreamer> Streamer =
36 std::make_unique<DwarfStreamer>(args&: FileType, args&: OutFile, args&: Warning);
37 if (Error Err = Streamer->init(TheTriple, Swift5ReflectionSegmentName: "__DWARF"))
38 return std::move(Err);
39
40 return std::move(Streamer);
41}
42
43Error DwarfStreamer::init(Triple TheTriple,
44 StringRef Swift5ReflectionSegmentName) {
45 std::string ErrorStr;
46 std::string TripleName;
47
48 // Get the target.
49 const Target *TheTarget =
50 TargetRegistry::lookupTarget(ArchName: TripleName, TheTriple, Error&: ErrorStr);
51 if (!TheTarget)
52 return createStringError(EC: std::errc::invalid_argument, Fmt: ErrorStr.c_str());
53
54 TripleName = TheTriple.getTriple();
55
56 // Create all the MC Objects.
57 MRI.reset(p: TheTarget->createMCRegInfo(TT: TheTriple));
58 if (!MRI)
59 return createStringError(EC: std::errc::invalid_argument,
60 Fmt: "no register info for target %s",
61 Vals: TripleName.c_str());
62
63 MCOptions.AsmVerbose = true;
64 MCOptions.MCUseDwarfDirectory = MCTargetOptions::EnableDwarfDirectory;
65 MAI.reset(p: TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
66 if (!MAI)
67 return createStringError(EC: std::errc::invalid_argument,
68 Fmt: "no asm info for target %s", Vals: TripleName.c_str());
69
70 MSTI.reset(p: TheTarget->createMCSubtargetInfo(TheTriple, CPU: "", Features: ""));
71 if (!MSTI)
72 return createStringError(EC: std::errc::invalid_argument,
73 Fmt: "no subtarget info for target %s",
74 Vals: TripleName.c_str());
75
76 MC.reset(p: new MCContext(TheTriple, *MAI, *MRI, *MSTI, nullptr, true,
77 Swift5ReflectionSegmentName));
78 MOFI.reset(p: TheTarget->createMCObjectFileInfo(Ctx&: *MC, /*PIC=*/false, LargeCodeModel: false));
79 MC->setObjectFileInfo(MOFI.get());
80
81 MAB = TheTarget->createMCAsmBackend(STI: *MSTI, MRI: *MRI, Options: MCOptions);
82 if (!MAB)
83 return createStringError(EC: std::errc::invalid_argument,
84 Fmt: "no asm backend for target %s",
85 Vals: TripleName.c_str());
86
87 MII.reset(p: TheTarget->createMCInstrInfo());
88 if (!MII)
89 return createStringError(EC: std::errc::invalid_argument,
90 Fmt: "no instr info info for target %s",
91 Vals: TripleName.c_str());
92
93 MCE = TheTarget->createMCCodeEmitter(II: *MII, Ctx&: *MC);
94 if (!MCE)
95 return createStringError(EC: std::errc::invalid_argument,
96 Fmt: "no code emitter for target %s",
97 Vals: TripleName.c_str());
98
99 switch (OutFileType) {
100 case DWARFLinker::OutputFileType::Assembly: {
101 std::unique_ptr<MCInstPrinter> MIP(TheTarget->createMCInstPrinter(
102 T: TheTriple, SyntaxVariant: MAI->getAssemblerDialect(), MAI: *MAI, MII: *MII, MRI: *MRI));
103 MS = TheTarget->createAsmStreamer(
104 Ctx&: *MC, OS: std::make_unique<formatted_raw_ostream>(args&: OutFile), IP: std::move(MIP),
105 CE: std::unique_ptr<MCCodeEmitter>(MCE),
106 TAB: std::unique_ptr<MCAsmBackend>(MAB));
107 break;
108 }
109 case DWARFLinker::OutputFileType::Object: {
110 MS = TheTarget->createMCObjectStreamer(
111 T: TheTriple, Ctx&: *MC, TAB: std::unique_ptr<MCAsmBackend>(MAB),
112 OW: MAB->createObjectWriter(OS&: OutFile), Emitter: std::unique_ptr<MCCodeEmitter>(MCE),
113 STI: *MSTI);
114 break;
115 }
116 }
117
118 if (!MS)
119 return createStringError(EC: std::errc::invalid_argument,
120 Fmt: "no object streamer for target %s",
121 Vals: TripleName.c_str());
122
123 // Finally create the AsmPrinter we'll use to emit the DIEs.
124 TM.reset(p: TheTarget->createTargetMachine(TT: TheTriple, CPU: "", Features: "", Options: TargetOptions(),
125 RM: std::nullopt));
126 if (!TM)
127 return createStringError(EC: std::errc::invalid_argument,
128 Fmt: "no target machine for target %s",
129 Vals: TripleName.c_str());
130
131 Asm.reset(p: TheTarget->createAsmPrinter(TM&: *TM, Streamer: std::unique_ptr<MCStreamer>(MS)));
132 if (!Asm)
133 return createStringError(EC: std::errc::invalid_argument,
134 Fmt: "no asm printer for target %s",
135 Vals: TripleName.c_str());
136 Asm->setDwarfUsesRelocationsAcrossSections(false);
137
138 RangesSectionSize = 0;
139 RngListsSectionSize = 0;
140 LocSectionSize = 0;
141 LocListsSectionSize = 0;
142 LineSectionSize = 0;
143 FrameSectionSize = 0;
144 DebugInfoSectionSize = 0;
145 MacInfoSectionSize = 0;
146 MacroSectionSize = 0;
147
148 return Error::success();
149}
150
151void DwarfStreamer::finish() { MS->finish(); }
152
153void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
154 MS->switchSection(Section: MOFI->getDwarfInfoSection());
155 MC->setDwarfVersion(DwarfVersion);
156}
157
158/// Emit the compilation unit header for \p Unit in the debug_info section.
159///
160/// A Dwarf 4 section header is encoded as:
161/// uint32_t Unit length (omitting this field)
162/// uint16_t Version
163/// uint32_t Abbreviation table offset
164/// uint8_t Address size
165/// Leading to a total of 11 bytes.
166///
167/// A Dwarf 5 section header is encoded as:
168/// uint32_t Unit length (omitting this field)
169/// uint16_t Version
170/// uint8_t Unit type
171/// uint8_t Address size
172/// uint32_t Abbreviation table offset
173/// Leading to a total of 12 bytes.
174void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit,
175 unsigned DwarfVersion) {
176 switchToDebugInfoSection(DwarfVersion);
177
178 /// The start of the unit within its section.
179 Unit.setLabelBegin(Asm->createTempSymbol(Name: "cu_begin"));
180 Asm->OutStreamer->emitLabel(Symbol: Unit.getLabelBegin());
181
182 // Emit size of content not including length itself. The size has already
183 // been computed in CompileUnit::computeOffsets(). Subtract 4 to that size to
184 // account for the length field.
185 Asm->emitInt32(Value: Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
186 Asm->emitInt16(Value: DwarfVersion);
187
188 if (DwarfVersion >= 5) {
189 dwarf::Tag RootTag = Unit.getOutputUnitDIE()->getTag();
190 Asm->emitInt8(Value: RootTag == dwarf::DW_TAG_partial_unit ? dwarf::DW_UT_partial
191 : 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 // unsupported.
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, Unit, DebugStrPool,
853 DebugLineStrPool);
854
855 // Emit rows.
856 emitLineTableRows(LineTable, LineEndSym,
857 AddressByteSize: Unit.getOrigUnit().getAddressByteSize(), RowOffsets);
858}
859
860void DwarfStreamer::emitLineTablePrologue(const DWARFDebugLine::Prologue &P,
861 const CompileUnit &Unit,
862 OffsetsStringPool &DebugStrPool,
863 OffsetsStringPool &DebugLineStrPool) {
864 MCSymbol *PrologueStartSym = MC->createTempSymbol();
865 MCSymbol *PrologueEndSym = MC->createTempSymbol();
866
867 // version (uhalf).
868 MS->emitInt16(Value: P.getVersion());
869 LineSectionSize += 2;
870 if (P.getVersion() == 5) {
871 // address_size (ubyte).
872 MS->emitInt8(Value: P.getAddressSize());
873 LineSectionSize += 1;
874
875 // segment_selector_size (ubyte).
876 MS->emitInt8(Value: P.SegSelectorSize);
877 LineSectionSize += 1;
878 }
879
880 // header_length.
881 emitLabelDifference(Hi: PrologueEndSym, Lo: PrologueStartSym, Format: P.FormParams.Format,
882 SectionSize&: LineSectionSize);
883
884 Asm->OutStreamer->emitLabel(Symbol: PrologueStartSym);
885 emitLineTableProloguePayload(P, Unit, DebugStrPool, DebugLineStrPool);
886 Asm->OutStreamer->emitLabel(Symbol: PrologueEndSym);
887}
888
889void DwarfStreamer::emitLineTablePrologueV2IncludeAndFileTable(
890 const DWARFDebugLine::Prologue &P, const CompileUnit &Unit,
891 OffsetsStringPool &DebugStrPool, OffsetsStringPool &DebugLineStrPool) {
892 // include_directories (sequence of path names).
893 for (const DWARFFormValue &Include : P.IncludeDirectories)
894 emitLineTableString(P, String: Include, DebugStrPool, DebugLineStrPool, PathUnit: &Unit);
895 // The last entry is followed by a single null byte.
896 MS->emitInt8(Value: 0);
897 LineSectionSize += 1;
898
899 // file_names (sequence of file entries).
900 for (const DWARFDebugLine::FileNameEntry &File : P.FileNames) {
901 // A null-terminated string containing the full or relative path name of a
902 // source file.
903 emitLineTableString(P, String: File.Name, DebugStrPool, DebugLineStrPool, PathUnit: &Unit);
904 // An unsigned LEB128 number representing the directory index of a directory
905 // in the include_directories section.
906 LineSectionSize += MS->emitULEB128IntValue(Value: File.DirIdx);
907 // An unsigned LEB128 number representing the (implementation-defined) time
908 // of last modification for the file, or 0 if not available.
909 LineSectionSize += MS->emitULEB128IntValue(Value: File.ModTime);
910 // An unsigned LEB128 number representing the length in bytes of the file,
911 // or 0 if not available.
912 LineSectionSize += MS->emitULEB128IntValue(Value: File.Length);
913 }
914 // The last entry is followed by a single null byte.
915 MS->emitInt8(Value: 0);
916 LineSectionSize += 1;
917}
918
919void DwarfStreamer::emitLineTablePrologueV5IncludeAndFileTable(
920 const DWARFDebugLine::Prologue &P, const CompileUnit &Unit,
921 OffsetsStringPool &DebugStrPool, OffsetsStringPool &DebugLineStrPool) {
922 if (P.IncludeDirectories.empty()) {
923 // directory_entry_format_count(ubyte).
924 MS->emitInt8(Value: 0);
925 LineSectionSize += 1;
926 } else {
927 // directory_entry_format_count(ubyte).
928 MS->emitInt8(Value: 1);
929 LineSectionSize += 1;
930
931 // directory_entry_format (sequence of ULEB128 pairs).
932 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_LNCT_path);
933 LineSectionSize +=
934 MS->emitULEB128IntValue(Value: P.IncludeDirectories[0].getForm());
935 }
936
937 // directories_count (ULEB128).
938 LineSectionSize += MS->emitULEB128IntValue(Value: P.IncludeDirectories.size());
939 // directories (sequence of directory names).
940 for (auto Include : P.IncludeDirectories)
941 emitLineTableString(P, String: Include, DebugStrPool, DebugLineStrPool, PathUnit: &Unit);
942
943 bool HasChecksums = P.ContentTypes.HasMD5;
944 bool HasInlineSources = P.ContentTypes.HasSource;
945
946 if (P.FileNames.empty()) {
947 // file_name_entry_format_count (ubyte).
948 MS->emitInt8(Value: 0);
949 LineSectionSize += 1;
950 } else {
951 // file_name_entry_format_count (ubyte).
952 MS->emitInt8(Value: 2 + (HasChecksums ? 1 : 0) + (HasInlineSources ? 1 : 0));
953 LineSectionSize += 1;
954
955 // file_name_entry_format (sequence of ULEB128 pairs).
956 auto StrForm = P.FileNames[0].Name.getForm();
957 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_LNCT_path);
958 LineSectionSize += MS->emitULEB128IntValue(Value: StrForm);
959
960 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_LNCT_directory_index);
961 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_FORM_udata);
962
963 if (HasChecksums) {
964 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_LNCT_MD5);
965 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_FORM_data16);
966 }
967
968 if (HasInlineSources) {
969 LineSectionSize += MS->emitULEB128IntValue(Value: dwarf::DW_LNCT_LLVM_source);
970 LineSectionSize += MS->emitULEB128IntValue(Value: StrForm);
971 }
972 }
973
974 // file_names_count (ULEB128).
975 LineSectionSize += MS->emitULEB128IntValue(Value: P.FileNames.size());
976
977 // file_names (sequence of file name entries).
978 for (auto File : P.FileNames) {
979 emitLineTableString(P, String: File.Name, DebugStrPool, DebugLineStrPool, PathUnit: &Unit);
980 LineSectionSize += MS->emitULEB128IntValue(Value: File.DirIdx);
981 if (HasChecksums) {
982 MS->emitBinaryData(
983 Data: StringRef(reinterpret_cast<const char *>(File.Checksum.data()),
984 File.Checksum.size()));
985 LineSectionSize += File.Checksum.size();
986 }
987 if (HasInlineSources)
988 emitLineTableString(P, String: File.Source, DebugStrPool, DebugLineStrPool);
989 }
990}
991
992void DwarfStreamer::emitLineTableString(const DWARFDebugLine::Prologue &P,
993 const DWARFFormValue &String,
994 OffsetsStringPool &DebugStrPool,
995 OffsetsStringPool &DebugLineStrPool,
996 const CompileUnit *PathUnit) {
997 std::optional<const char *> StringVal = dwarf::toString(V: String);
998 if (!StringVal) {
999 warn(Warning: "Cann't read string from line table.");
1000 return;
1001 }
1002
1003 std::string RemappedPath;
1004 if (PathUnit && PathUnit->getContainingFile().PrefixMap) {
1005 RemappedPath = PathUnit->getContainingFile().remapPath(Path: *StringVal);
1006 StringVal = RemappedPath.c_str();
1007 }
1008
1009 switch (String.getForm()) {
1010 case dwarf::DW_FORM_string: {
1011 StringRef Str = *StringVal;
1012 Asm->OutStreamer->emitBytes(Data: Str.data());
1013 Asm->emitInt8(Value: 0);
1014 LineSectionSize += Str.size() + 1;
1015 } break;
1016 case dwarf::DW_FORM_strp:
1017 case dwarf::DW_FORM_line_strp: {
1018 DwarfStringPoolEntryRef StringRef =
1019 String.getForm() == dwarf::DW_FORM_strp
1020 ? DebugStrPool.getEntry(S: *StringVal)
1021 : DebugLineStrPool.getEntry(S: *StringVal);
1022
1023 emitIntOffset(Offset: StringRef.getOffset(), Format: P.FormParams.Format, SectionSize&: LineSectionSize);
1024 } break;
1025 default:
1026 warn(Warning: "Unsupported string form inside line table.");
1027 break;
1028 };
1029}
1030
1031void DwarfStreamer::emitLineTableProloguePayload(
1032 const DWARFDebugLine::Prologue &P, const CompileUnit &Unit,
1033 OffsetsStringPool &DebugStrPool, OffsetsStringPool &DebugLineStrPool) {
1034 // minimum_instruction_length (ubyte).
1035 MS->emitInt8(Value: P.MinInstLength);
1036 LineSectionSize += 1;
1037 if (P.FormParams.Version >= 4) {
1038 // maximum_operations_per_instruction (ubyte).
1039 MS->emitInt8(Value: P.MaxOpsPerInst);
1040 LineSectionSize += 1;
1041 }
1042 // default_is_stmt (ubyte).
1043 MS->emitInt8(Value: P.DefaultIsStmt);
1044 LineSectionSize += 1;
1045 // line_base (sbyte).
1046 MS->emitInt8(Value: P.LineBase);
1047 LineSectionSize += 1;
1048 // line_range (ubyte).
1049 MS->emitInt8(Value: P.LineRange);
1050 LineSectionSize += 1;
1051 // opcode_base (ubyte).
1052 MS->emitInt8(Value: P.OpcodeBase);
1053 LineSectionSize += 1;
1054
1055 // standard_opcode_lengths (array of ubyte).
1056 for (auto Length : P.StandardOpcodeLengths) {
1057 MS->emitInt8(Value: Length);
1058 LineSectionSize += 1;
1059 }
1060
1061 if (P.FormParams.Version < 5)
1062 emitLineTablePrologueV2IncludeAndFileTable(P, Unit, DebugStrPool,
1063 DebugLineStrPool);
1064 else
1065 emitLineTablePrologueV5IncludeAndFileTable(P, Unit, DebugStrPool,
1066 DebugLineStrPool);
1067}
1068
1069void DwarfStreamer::emitLineTableRows(
1070 const DWARFDebugLine::LineTable &LineTable, MCSymbol *LineEndSym,
1071 unsigned AddressByteSize, std::vector<uint64_t> *RowOffsets) {
1072
1073 MCDwarfLineTableParams Params;
1074 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
1075 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
1076 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
1077
1078 SmallString<128> EncodingBuffer;
1079
1080 if (LineTable.Rows.empty()) {
1081 // We only have the dummy entry, dsymutil emits an entry with a 0
1082 // address in that case.
1083 MCDwarfLineAddr::encode(Context&: *MC, Params, LineDelta: std::numeric_limits<int64_t>::max(), AddrDelta: 0,
1084 OS&: EncodingBuffer);
1085 MS->emitBytes(Data: EncodingBuffer);
1086 LineSectionSize += EncodingBuffer.size();
1087 MS->emitLabel(Symbol: LineEndSym);
1088 return;
1089 }
1090
1091 // Line table state machine fields
1092 unsigned FileNum = 1;
1093 unsigned LastLine = 1;
1094 unsigned Column = 0;
1095 unsigned Discriminator = 0;
1096 unsigned IsStatement = 1;
1097 unsigned Isa = 0;
1098 uint64_t Address = -1ULL;
1099
1100 unsigned RowsSinceLastSequence = 0;
1101
1102 for (const DWARFDebugLine::Row &Row : LineTable.Rows) {
1103 // If we're tracking row offsets, record the current section size as the
1104 // offset of this row.
1105 if (RowOffsets)
1106 RowOffsets->push_back(x: LineSectionSize);
1107
1108 int64_t AddressDelta;
1109 if (Address == -1ULL) {
1110 MS->emitIntValue(Value: dwarf::DW_LNS_extended_op, Size: 1);
1111 MS->emitULEB128IntValue(Value: AddressByteSize + 1);
1112 MS->emitIntValue(Value: dwarf::DW_LNE_set_address, Size: 1);
1113 MS->emitIntValue(Value: Row.Address.Address, Size: AddressByteSize);
1114 LineSectionSize +=
1115 2 + AddressByteSize + getULEB128Size(Value: AddressByteSize + 1);
1116 AddressDelta = 0;
1117 } else {
1118 AddressDelta =
1119 (Row.Address.Address - Address) / LineTable.Prologue.MinInstLength;
1120 }
1121
1122 // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable.
1123 // We should find a way to share this code, but the current compatibility
1124 // requirement with classic dsymutil makes it hard. Revisit that once this
1125 // requirement is dropped.
1126
1127 if (FileNum != Row.File) {
1128 FileNum = Row.File;
1129 MS->emitIntValue(Value: dwarf::DW_LNS_set_file, Size: 1);
1130 MS->emitULEB128IntValue(Value: FileNum);
1131 LineSectionSize += 1 + getULEB128Size(Value: FileNum);
1132 }
1133 if (Column != Row.Column) {
1134 Column = Row.Column;
1135 MS->emitIntValue(Value: dwarf::DW_LNS_set_column, Size: 1);
1136 MS->emitULEB128IntValue(Value: Column);
1137 LineSectionSize += 1 + getULEB128Size(Value: Column);
1138 }
1139 if (Discriminator != Row.Discriminator &&
1140 MS->getContext().getDwarfVersion() >= 4) {
1141 Discriminator = Row.Discriminator;
1142 unsigned Size = getULEB128Size(Value: Discriminator);
1143 MS->emitIntValue(Value: dwarf::DW_LNS_extended_op, Size: 1);
1144 MS->emitULEB128IntValue(Value: Size + 1);
1145 MS->emitIntValue(Value: dwarf::DW_LNE_set_discriminator, Size: 1);
1146 MS->emitULEB128IntValue(Value: Discriminator);
1147 LineSectionSize += /* extended op */ 1 + getULEB128Size(Value: Size + 1) +
1148 /* discriminator */ 1 + Size;
1149 }
1150 Discriminator = 0;
1151
1152 if (Isa != Row.Isa) {
1153 Isa = Row.Isa;
1154 MS->emitIntValue(Value: dwarf::DW_LNS_set_isa, Size: 1);
1155 MS->emitULEB128IntValue(Value: Isa);
1156 LineSectionSize += 1 + getULEB128Size(Value: Isa);
1157 }
1158 if (IsStatement != Row.IsStmt) {
1159 IsStatement = Row.IsStmt;
1160 MS->emitIntValue(Value: dwarf::DW_LNS_negate_stmt, Size: 1);
1161 LineSectionSize += 1;
1162 }
1163 if (Row.BasicBlock) {
1164 MS->emitIntValue(Value: dwarf::DW_LNS_set_basic_block, Size: 1);
1165 LineSectionSize += 1;
1166 }
1167
1168 if (Row.PrologueEnd) {
1169 MS->emitIntValue(Value: dwarf::DW_LNS_set_prologue_end, Size: 1);
1170 LineSectionSize += 1;
1171 }
1172
1173 if (Row.EpilogueBegin) {
1174 MS->emitIntValue(Value: dwarf::DW_LNS_set_epilogue_begin, Size: 1);
1175 LineSectionSize += 1;
1176 }
1177
1178 int64_t LineDelta = int64_t(Row.Line) - LastLine;
1179 if (!Row.EndSequence) {
1180 MCDwarfLineAddr::encode(Context&: *MC, Params, LineDelta, AddrDelta: AddressDelta,
1181 OS&: EncodingBuffer);
1182 MS->emitBytes(Data: EncodingBuffer);
1183 LineSectionSize += EncodingBuffer.size();
1184 EncodingBuffer.resize(N: 0);
1185 Address = Row.Address.Address;
1186 LastLine = Row.Line;
1187 RowsSinceLastSequence++;
1188 } else {
1189 if (LineDelta) {
1190 MS->emitIntValue(Value: dwarf::DW_LNS_advance_line, Size: 1);
1191 MS->emitSLEB128IntValue(Value: LineDelta);
1192 LineSectionSize += 1 + getSLEB128Size(Value: LineDelta);
1193 }
1194 if (AddressDelta) {
1195 MS->emitIntValue(Value: dwarf::DW_LNS_advance_pc, Size: 1);
1196 MS->emitULEB128IntValue(Value: AddressDelta);
1197 LineSectionSize += 1 + getULEB128Size(Value: AddressDelta);
1198 }
1199 MCDwarfLineAddr::encode(Context&: *MC, Params, LineDelta: std::numeric_limits<int64_t>::max(),
1200 AddrDelta: 0, OS&: EncodingBuffer);
1201 MS->emitBytes(Data: EncodingBuffer);
1202 LineSectionSize += EncodingBuffer.size();
1203 EncodingBuffer.resize(N: 0);
1204 Address = -1ULL;
1205 LastLine = FileNum = IsStatement = 1;
1206 RowsSinceLastSequence = Column = Discriminator = Isa = 0;
1207 }
1208 }
1209
1210 if (RowsSinceLastSequence) {
1211 MCDwarfLineAddr::encode(Context&: *MC, Params, LineDelta: std::numeric_limits<int64_t>::max(), AddrDelta: 0,
1212 OS&: EncodingBuffer);
1213 MS->emitBytes(Data: EncodingBuffer);
1214 LineSectionSize += EncodingBuffer.size();
1215 EncodingBuffer.resize(N: 0);
1216 }
1217
1218 MS->emitLabel(Symbol: LineEndSym);
1219}
1220
1221void DwarfStreamer::emitIntOffset(uint64_t Offset, dwarf::DwarfFormat Format,
1222 uint64_t &SectionSize) {
1223 uint8_t Size = dwarf::getDwarfOffsetByteSize(Format);
1224 MS->emitIntValue(Value: Offset, Size);
1225 SectionSize += Size;
1226}
1227
1228void DwarfStreamer::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1229 dwarf::DwarfFormat Format,
1230 uint64_t &SectionSize) {
1231 uint8_t Size = dwarf::getDwarfOffsetByteSize(Format);
1232 Asm->emitLabelDifference(Hi, Lo, Size);
1233 SectionSize += Size;
1234}
1235
1236/// Emit the pubnames or pubtypes section contribution for \p
1237/// Unit into \p Sec. The data is provided in \p Names.
1238void DwarfStreamer::emitPubSectionForUnit(
1239 MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
1240 const std::vector<CompileUnit::AccelInfo> &Names) {
1241 if (Names.empty())
1242 return;
1243
1244 // Start the dwarf pubnames section.
1245 Asm->OutStreamer->switchSection(Section: Sec);
1246 MCSymbol *BeginLabel = Asm->createTempSymbol(Name: "pub" + SecName + "_begin");
1247 MCSymbol *EndLabel = Asm->createTempSymbol(Name: "pub" + SecName + "_end");
1248
1249 bool HeaderEmitted = false;
1250 // Emit the pubnames for this compilation unit.
1251 for (const auto &Name : Names) {
1252 if (Name.SkipPubSection)
1253 continue;
1254
1255 if (!HeaderEmitted) {
1256 // Emit the header.
1257 Asm->emitLabelDifference(Hi: EndLabel, Lo: BeginLabel, Size: 4); // Length
1258 Asm->OutStreamer->emitLabel(Symbol: BeginLabel);
1259 Asm->emitInt16(Value: dwarf::DW_PUBNAMES_VERSION); // Version
1260 Asm->emitInt32(Value: Unit.getStartOffset()); // Unit offset
1261 Asm->emitInt32(Value: Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1262 HeaderEmitted = true;
1263 }
1264 Asm->emitInt32(Value: Name.Die->getOffset());
1265
1266 // Emit the string itself.
1267 Asm->OutStreamer->emitBytes(Data: Name.Name.getString());
1268 // Emit a null terminator.
1269 Asm->emitInt8(Value: 0);
1270 }
1271
1272 if (!HeaderEmitted)
1273 return;
1274 Asm->emitInt32(Value: 0); // End marker.
1275 Asm->OutStreamer->emitLabel(Symbol: EndLabel);
1276}
1277
1278/// Emit .debug_pubnames for \p Unit.
1279void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1280 emitPubSectionForUnit(Sec: MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1281 SecName: "names", Unit, Names: Unit.getPubnames());
1282}
1283
1284/// Emit .debug_pubtypes for \p Unit.
1285void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1286 emitPubSectionForUnit(Sec: MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1287 SecName: "types", Unit, Names: Unit.getPubtypes());
1288}
1289
1290/// Emit a CIE into the debug_frame section.
1291void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1292 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfFrameSection());
1293
1294 MS->emitBytes(Data: CIEBytes);
1295 FrameSectionSize += CIEBytes.size();
1296}
1297
1298/// Emit a FDE into the debug_frame section. \p FDEBytes
1299/// contains the FDE data without the length, CIE offset and address
1300/// which will be replaced with the parameter values.
1301void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1302 uint64_t Address, StringRef FDEBytes) {
1303 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfFrameSection());
1304
1305 MS->emitIntValue(Value: FDEBytes.size() + 4 + AddrSize, Size: 4);
1306 MS->emitIntValue(Value: CIEOffset, Size: 4);
1307 MS->emitIntValue(Value: Address, Size: AddrSize);
1308 MS->emitBytes(Data: FDEBytes);
1309 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1310}
1311
1312void DwarfStreamer::emitMacroTables(DWARFContext *Context,
1313 const Offset2UnitMap &UnitMacroMap,
1314 OffsetsStringPool &StringPool) {
1315 assert(Context != nullptr && "Empty DWARF context");
1316
1317 // Check for .debug_macinfo table.
1318 if (const DWARFDebugMacro *Table = Context->getDebugMacinfo()) {
1319 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfMacinfoSection());
1320 emitMacroTableImpl(MacroTable: Table, UnitMacroMap, StringPool, OutOffset&: MacInfoSectionSize);
1321 }
1322
1323 // Check for .debug_macro table.
1324 if (const DWARFDebugMacro *Table = Context->getDebugMacro()) {
1325 MS->switchSection(Section: MC->getObjectFileInfo()->getDwarfMacroSection());
1326 emitMacroTableImpl(MacroTable: Table, UnitMacroMap, StringPool, OutOffset&: MacroSectionSize);
1327 }
1328}
1329
1330void DwarfStreamer::emitMacroTableImpl(const DWARFDebugMacro *MacroTable,
1331 const Offset2UnitMap &UnitMacroMap,
1332 OffsetsStringPool &StringPool,
1333 uint64_t &OutOffset) {
1334 bool DefAttributeIsReported = false;
1335 bool UndefAttributeIsReported = false;
1336 bool ImportAttributeIsReported = false;
1337 for (const DWARFDebugMacro::MacroList &List : MacroTable->MacroLists) {
1338 Offset2UnitMap::const_iterator UnitIt = UnitMacroMap.find(Val: List.Offset);
1339 if (UnitIt == UnitMacroMap.end()) {
1340 warn(Warning: formatv(
1341 Fmt: "couldn`t find compile unit for the macro table with offset = {0:x}",
1342 Vals: List.Offset));
1343 continue;
1344 }
1345
1346 // Skip macro table if the unit was not cloned.
1347 DIE *OutputUnitDIE = UnitIt->second->getOutputUnitDIE();
1348 if (OutputUnitDIE == nullptr)
1349 continue;
1350
1351 // Update macro attribute of cloned compile unit with the proper offset to
1352 // the macro table.
1353 bool hasDWARFv5Header = false;
1354 for (auto &V : OutputUnitDIE->values()) {
1355 if (V.getAttribute() == dwarf::DW_AT_macro_info) {
1356 V = DIEValue(V.getAttribute(), V.getForm(), DIEInteger(OutOffset));
1357 break;
1358 } else if (V.getAttribute() == dwarf::DW_AT_macros) {
1359 hasDWARFv5Header = true;
1360 V = DIEValue(V.getAttribute(), V.getForm(), DIEInteger(OutOffset));
1361 break;
1362 }
1363 }
1364
1365 // Write DWARFv5 header.
1366 if (hasDWARFv5Header) {
1367 // Write header version.
1368 MS->emitIntValue(Value: List.Header.Version, Size: sizeof(List.Header.Version));
1369 OutOffset += sizeof(List.Header.Version);
1370
1371 uint8_t Flags = List.Header.Flags;
1372
1373 // Check for OPCODE_OPERANDS_TABLE.
1374 if (Flags &
1375 DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE) {
1376 Flags &= ~DWARFDebugMacro::HeaderFlagMask::MACRO_OPCODE_OPERANDS_TABLE;
1377 warn(Warning: "opcode_operands_table is not supported yet.");
1378 }
1379
1380 // Check for DEBUG_LINE_OFFSET.
1381 std::optional<uint64_t> StmtListOffset;
1382 if (Flags & DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET) {
1383 // Get offset to the line table from the cloned compile unit.
1384 for (auto &V : OutputUnitDIE->values()) {
1385 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
1386 StmtListOffset = V.getDIEInteger().getValue();
1387 break;
1388 }
1389 }
1390
1391 if (!StmtListOffset) {
1392 Flags &= ~DWARFDebugMacro::HeaderFlagMask::MACRO_DEBUG_LINE_OFFSET;
1393 warn(Warning: "couldn`t find line table for macro table.");
1394 }
1395 }
1396
1397 // Write flags.
1398 MS->emitIntValue(Value: Flags, Size: sizeof(Flags));
1399 OutOffset += sizeof(Flags);
1400
1401 // Write offset to line table.
1402 if (StmtListOffset) {
1403 MS->emitIntValue(Value: *StmtListOffset, Size: List.Header.getOffsetByteSize());
1404 OutOffset += List.Header.getOffsetByteSize();
1405 }
1406 }
1407
1408 // Write macro entries.
1409 for (const DWARFDebugMacro::Entry &MacroEntry : List.Macros) {
1410 if (MacroEntry.Type == 0) {
1411 OutOffset += MS->emitULEB128IntValue(Value: MacroEntry.Type);
1412 continue;
1413 }
1414
1415 uint8_t MacroType = MacroEntry.Type;
1416 switch (MacroType) {
1417 default: {
1418 bool HasVendorSpecificExtension =
1419 (!hasDWARFv5Header && MacroType == dwarf::DW_MACINFO_vendor_ext) ||
1420 (hasDWARFv5Header && (MacroType >= dwarf::DW_MACRO_lo_user &&
1421 MacroType <= dwarf::DW_MACRO_hi_user));
1422
1423 if (HasVendorSpecificExtension) {
1424 // Write macinfo type.
1425 MS->emitIntValue(Value: MacroType, Size: 1);
1426 OutOffset++;
1427
1428 // Write vendor extension constant.
1429 OutOffset += MS->emitULEB128IntValue(Value: MacroEntry.ExtConstant);
1430
1431 // Write vendor extension string.
1432 StringRef String = MacroEntry.ExtStr;
1433 MS->emitBytes(Data: String);
1434 MS->emitIntValue(Value: 0, Size: 1);
1435 OutOffset += String.size() + 1;
1436 } else
1437 warn(Warning: "unknown macro type. skip.");
1438 } break;
1439 // debug_macro and debug_macinfo share some common encodings.
1440 // DW_MACRO_define == DW_MACINFO_define
1441 // DW_MACRO_undef == DW_MACINFO_undef
1442 // DW_MACRO_start_file == DW_MACINFO_start_file
1443 // DW_MACRO_end_file == DW_MACINFO_end_file
1444 // For readibility/uniformity we are using DW_MACRO_*.
1445 case dwarf::DW_MACRO_define:
1446 case dwarf::DW_MACRO_undef: {
1447 // Write macinfo type.
1448 MS->emitIntValue(Value: MacroType, Size: 1);
1449 OutOffset++;
1450
1451 // Write source line.
1452 OutOffset += MS->emitULEB128IntValue(Value: MacroEntry.Line);
1453
1454 // Write macro string.
1455 StringRef String = MacroEntry.MacroStr;
1456 MS->emitBytes(Data: String);
1457 MS->emitIntValue(Value: 0, Size: 1);
1458 OutOffset += String.size() + 1;
1459 } break;
1460 case dwarf::DW_MACRO_define_strp:
1461 case dwarf::DW_MACRO_undef_strp:
1462 case dwarf::DW_MACRO_define_strx:
1463 case dwarf::DW_MACRO_undef_strx: {
1464 assert(UnitIt->second->getOrigUnit().getVersion() >= 5);
1465
1466 // DW_MACRO_*_strx forms are not supported currently.
1467 // Convert to *_strp.
1468 switch (MacroType) {
1469 case dwarf::DW_MACRO_define_strx: {
1470 MacroType = dwarf::DW_MACRO_define_strp;
1471 if (!DefAttributeIsReported) {
1472 warn(Warning: "DW_MACRO_define_strx unsupported yet. Convert to "
1473 "DW_MACRO_define_strp.");
1474 DefAttributeIsReported = true;
1475 }
1476 } break;
1477 case dwarf::DW_MACRO_undef_strx: {
1478 MacroType = dwarf::DW_MACRO_undef_strp;
1479 if (!UndefAttributeIsReported) {
1480 warn(Warning: "DW_MACRO_undef_strx unsupported yet. Convert to "
1481 "DW_MACRO_undef_strp.");
1482 UndefAttributeIsReported = true;
1483 }
1484 } break;
1485 default:
1486 // Nothing to do.
1487 break;
1488 }
1489
1490 // Write macinfo type.
1491 MS->emitIntValue(Value: MacroType, Size: 1);
1492 OutOffset++;
1493
1494 // Write source line.
1495 OutOffset += MS->emitULEB128IntValue(Value: MacroEntry.Line);
1496
1497 // Write macro string.
1498 DwarfStringPoolEntryRef EntryRef =
1499 StringPool.getEntry(S: MacroEntry.MacroStr);
1500 MS->emitIntValue(Value: EntryRef.getOffset(), Size: List.Header.getOffsetByteSize());
1501 OutOffset += List.Header.getOffsetByteSize();
1502 break;
1503 }
1504 case dwarf::DW_MACRO_start_file: {
1505 // Write macinfo type.
1506 MS->emitIntValue(Value: MacroType, Size: 1);
1507 OutOffset++;
1508 // Write source line.
1509 OutOffset += MS->emitULEB128IntValue(Value: MacroEntry.Line);
1510 // Write source file id.
1511 OutOffset += MS->emitULEB128IntValue(Value: MacroEntry.File);
1512 } break;
1513 case dwarf::DW_MACRO_end_file: {
1514 // Write macinfo type.
1515 MS->emitIntValue(Value: MacroType, Size: 1);
1516 OutOffset++;
1517 } break;
1518 case dwarf::DW_MACRO_import:
1519 case dwarf::DW_MACRO_import_sup: {
1520 if (!ImportAttributeIsReported) {
1521 warn(Warning: "DW_MACRO_import and DW_MACRO_import_sup are unsupported yet. "
1522 "remove.");
1523 ImportAttributeIsReported = true;
1524 }
1525 } break;
1526 }
1527 }
1528 }
1529}
1530