1//===- DebugLineSectionEmitter.h --------------------------------*- C++ -*-===//
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#ifndef LLVM_LIB_DWARFLINKER_PARALLEL_DEBUGLINESECTIONEMITTER_H
10#define LLVM_LIB_DWARFLINKER_PARALLEL_DEBUGLINESECTIONEMITTER_H
11
12#include "DWARFEmitterImpl.h"
13#include "llvm/DWARFLinker/AddressesMap.h"
14#include "llvm/DWARFLinker/Parallel/DWARFLinker.h"
15#include "llvm/DebugInfo/DWARF/DWARFObject.h"
16#include "llvm/MC/TargetRegistry.h"
17
18namespace llvm {
19namespace dwarf_linker {
20namespace parallel {
21
22/// This class emits specified line table into the .debug_line section.
23class DebugLineSectionEmitter {
24public:
25 DebugLineSectionEmitter(const Triple &TheTriple, DwarfUnit &U)
26 : TheTriple(TheTriple), U(U) {}
27
28 Error emit(const DWARFDebugLine::LineTable &LineTable,
29 ArrayRef<uint64_t> OrigRowIndices = {},
30 DenseMap<uint64_t, uint64_t> *RowIndexToSeqStartOffset = nullptr) {
31 // FIXME: remove dependence on MCDwarfLineAddr::encode.
32 // As we reuse MCDwarfLineAddr::encode, we need to create/initialize
33 // some MC* classes.
34 if (Error Err = init(TheTriple))
35 return Err;
36
37 // Get descriptor for output .debug_line section.
38 SectionDescriptor &OutSection =
39 U.getOrCreateSectionDescriptor(SectionKind: DebugSectionKind::DebugLine);
40
41 // unit_length.
42 OutSection.emitUnitLength(Length: 0xBADDEF);
43 uint64_t OffsetAfterUnitLength = OutSection.OS.tell();
44
45 // Emit prologue.
46 emitLineTablePrologue(P: LineTable.Prologue, Section&: OutSection);
47
48 // Emit rows.
49 emitLineTableRows(LineTable, Section&: OutSection, OrigRowIndices,
50 RowIndexToSeqStartOffset);
51 uint64_t OffsetAfterEnd = OutSection.OS.tell();
52
53 // Update unit length field with actual length value.
54 assert(OffsetAfterUnitLength -
55 OutSection.getFormParams().getDwarfOffsetByteSize() <
56 OffsetAfterUnitLength);
57 OutSection.apply(PatchOffset: OffsetAfterUnitLength -
58 OutSection.getFormParams().getDwarfOffsetByteSize(),
59 AttrForm: dwarf::DW_FORM_sec_offset,
60 Val: OffsetAfterEnd - OffsetAfterUnitLength);
61
62 return Error::success();
63 }
64
65private:
66 Error init(Triple TheTriple) {
67 std::string ErrorStr;
68 std::string TripleName;
69
70 // Get the target.
71 const Target *TheTarget =
72 TargetRegistry::lookupTarget(ArchName: TripleName, TheTriple, Error&: ErrorStr);
73 if (!TheTarget)
74 return createStringError(EC: std::errc::invalid_argument, Fmt: ErrorStr.c_str());
75 TripleName = TheTriple.getTriple();
76
77 // Create all the MC Objects.
78 MRI.reset(p: TheTarget->createMCRegInfo(TT: TheTriple));
79 if (!MRI)
80 return createStringError(EC: std::errc::invalid_argument,
81 Fmt: "no register info for target %s",
82 Vals: TripleName.c_str());
83
84 MAI.reset(p: TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
85 if (!MAI)
86 return createStringError(EC: std::errc::invalid_argument,
87 Fmt: "no asm info for target %s", Vals: TripleName.c_str());
88
89 MSTI.reset(p: TheTarget->createMCSubtargetInfo(TheTriple, CPU: "", Features: ""));
90 if (!MSTI)
91 return createStringError(EC: std::errc::invalid_argument,
92 Fmt: "no subtarget info for target %s",
93 Vals: TripleName.c_str());
94
95 MC.reset(
96 p: new MCContext(TheTriple, *MAI, *MRI, *MSTI, nullptr, true, "__DWARF"));
97
98 return Error::success();
99 }
100
101 void emitLineTablePrologue(const DWARFDebugLine::Prologue &P,
102 SectionDescriptor &Section) {
103 // version (uhalf).
104 Section.emitIntVal(Val: P.getVersion(), Size: 2);
105 if (P.getVersion() == 5) {
106 // address_size (ubyte).
107 Section.emitIntVal(Val: P.getAddressSize(), Size: 1);
108
109 // segment_selector_size (ubyte).
110 Section.emitIntVal(Val: P.SegSelectorSize, Size: 1);
111 }
112
113 // header_length.
114 Section.emitOffset(Val: 0xBADDEF);
115
116 uint64_t OffsetAfterPrologueLength = Section.OS.tell();
117 emitLineTableProloguePayload(P, Section);
118 uint64_t OffsetAfterPrologueEnd = Section.OS.tell();
119
120 // Update prologue length field with actual length value.
121 Section.apply(PatchOffset: OffsetAfterPrologueLength -
122 Section.getFormParams().getDwarfOffsetByteSize(),
123 AttrForm: dwarf::DW_FORM_sec_offset,
124 Val: OffsetAfterPrologueEnd - OffsetAfterPrologueLength);
125 }
126
127 void
128 emitLineTablePrologueV2IncludeAndFileTable(const DWARFDebugLine::Prologue &P,
129 SectionDescriptor &Section) {
130 // include_directories (sequence of path names).
131 for (const DWARFFormValue &Include : P.IncludeDirectories) {
132 std::optional<const char *> IncludeStr = dwarf::toString(V: Include);
133 if (!IncludeStr) {
134 U.warn(Warning: "cann't read string from line table.");
135 return;
136 }
137
138 emitPath(Section, Form: Include.getForm(), Path: *IncludeStr);
139 }
140 // The last entry is followed by a single null byte.
141 Section.emitIntVal(Val: 0, Size: 1);
142
143 // file_names (sequence of file entries).
144 for (const DWARFDebugLine::FileNameEntry &File : P.FileNames) {
145 std::optional<const char *> FileNameStr = dwarf::toString(V: File.Name);
146 if (!FileNameStr) {
147 U.warn(Warning: "cann't read string from line table.");
148 return;
149 }
150
151 // A null-terminated string containing the full or relative path name of a
152 // source file.
153 emitPath(Section, Form: File.Name.getForm(), Path: *FileNameStr);
154
155 // An unsigned LEB128 number representing the directory index of a
156 // directory in the include_directories section.
157 encodeULEB128(Value: File.DirIdx, OS&: Section.OS);
158 // An unsigned LEB128 number representing the (implementation-defined)
159 // time of last modification for the file, or 0 if not available.
160 encodeULEB128(Value: File.ModTime, OS&: Section.OS);
161 // An unsigned LEB128 number representing the length in bytes of the file,
162 // or 0 if not available.
163 encodeULEB128(Value: File.Length, OS&: Section.OS);
164 }
165 // The last entry is followed by a single null byte.
166 Section.emitIntVal(Val: 0, Size: 1);
167 }
168
169 void
170 emitLineTablePrologueV5IncludeAndFileTable(const DWARFDebugLine::Prologue &P,
171 SectionDescriptor &Section) {
172 if (P.IncludeDirectories.empty()) {
173 // directory_entry_format_count(ubyte).
174 Section.emitIntVal(Val: 0, Size: 1);
175 } else {
176 // directory_entry_format_count(ubyte).
177 Section.emitIntVal(Val: 1, Size: 1);
178
179 // directory_entry_format (sequence of ULEB128 pairs).
180 encodeULEB128(Value: dwarf::DW_LNCT_path, OS&: Section.OS);
181 encodeULEB128(Value: P.IncludeDirectories[0].getForm(), OS&: Section.OS);
182 }
183
184 // directories_count (ULEB128).
185 encodeULEB128(Value: P.IncludeDirectories.size(), OS&: Section.OS);
186 // directories (sequence of directory names).
187 for (auto Include : P.IncludeDirectories) {
188 std::optional<const char *> IncludeStr = dwarf::toString(V: Include);
189 if (!IncludeStr) {
190 U.warn(Warning: "cann't read string from line table.");
191 return;
192 }
193
194 emitPath(Section, Form: Include.getForm(), Path: *IncludeStr);
195 }
196
197 bool HasChecksums = P.ContentTypes.HasMD5;
198 bool HasInlineSources = P.ContentTypes.HasSource;
199
200 dwarf::Form FileNameForm = dwarf::DW_FORM_string;
201 dwarf::Form LLVMSourceForm = dwarf::DW_FORM_string;
202
203 if (P.FileNames.empty()) {
204 // file_name_entry_format_count (ubyte).
205 Section.emitIntVal(Val: 0, Size: 1);
206 } else {
207 FileNameForm = P.FileNames[0].Name.getForm();
208 LLVMSourceForm = P.FileNames[0].Source.getForm();
209
210 // file_name_entry_format_count (ubyte).
211 Section.emitIntVal(
212 Val: 2 + (HasChecksums ? 1 : 0) + (HasInlineSources ? 1 : 0), Size: 1);
213
214 // file_name_entry_format (sequence of ULEB128 pairs).
215 encodeULEB128(Value: dwarf::DW_LNCT_path, OS&: Section.OS);
216 encodeULEB128(Value: FileNameForm, OS&: Section.OS);
217
218 encodeULEB128(Value: dwarf::DW_LNCT_directory_index, OS&: Section.OS);
219 encodeULEB128(Value: dwarf::DW_FORM_udata, OS&: Section.OS);
220
221 if (HasChecksums) {
222 encodeULEB128(Value: dwarf::DW_LNCT_MD5, OS&: Section.OS);
223 encodeULEB128(Value: dwarf::DW_FORM_data16, OS&: Section.OS);
224 }
225
226 if (HasInlineSources) {
227 encodeULEB128(Value: dwarf::DW_LNCT_LLVM_source, OS&: Section.OS);
228 encodeULEB128(Value: LLVMSourceForm, OS&: Section.OS);
229 }
230 }
231
232 // file_names_count (ULEB128).
233 encodeULEB128(Value: P.FileNames.size(), OS&: Section.OS);
234
235 // file_names (sequence of file name entries).
236 for (auto File : P.FileNames) {
237 std::optional<const char *> FileNameStr = dwarf::toString(V: File.Name);
238 if (!FileNameStr) {
239 U.warn(Warning: "cann't read string from line table.");
240 return;
241 }
242
243 // A null-terminated string containing the full or relative path name of a
244 // source file.
245 emitPath(Section, Form: FileNameForm, Path: *FileNameStr);
246 encodeULEB128(Value: File.DirIdx, OS&: Section.OS);
247
248 if (HasChecksums) {
249 assert((File.Checksum.size() == 16) &&
250 "checksum size is not equal to 16 bytes.");
251 Section.emitBinaryData(
252 Data: StringRef(reinterpret_cast<const char *>(File.Checksum.data()),
253 File.Checksum.size()));
254 }
255
256 if (HasInlineSources) {
257 std::optional<const char *> FileSourceStr =
258 dwarf::toString(V: File.Source);
259 if (!FileSourceStr) {
260 U.warn(Warning: "cann't read string from line table.");
261 return;
262 }
263
264 Section.emitString(StringForm: LLVMSourceForm, StringVal: *FileSourceStr);
265 }
266 }
267 }
268
269 void emitLineTableProloguePayload(const DWARFDebugLine::Prologue &P,
270 SectionDescriptor &Section) {
271 // minimum_instruction_length (ubyte).
272 Section.emitIntVal(Val: P.MinInstLength, Size: 1);
273 if (P.FormParams.Version >= 4) {
274 // maximum_operations_per_instruction (ubyte).
275 Section.emitIntVal(Val: P.MaxOpsPerInst, Size: 1);
276 }
277 // default_is_stmt (ubyte).
278 Section.emitIntVal(Val: P.DefaultIsStmt, Size: 1);
279 // line_base (sbyte).
280 Section.emitIntVal(Val: P.LineBase, Size: 1);
281 // line_range (ubyte).
282 Section.emitIntVal(Val: P.LineRange, Size: 1);
283 // opcode_base (ubyte).
284 Section.emitIntVal(Val: P.OpcodeBase, Size: 1);
285
286 // standard_opcode_lengths (array of ubyte).
287 for (auto Length : P.StandardOpcodeLengths)
288 Section.emitIntVal(Val: Length, Size: 1);
289
290 if (P.FormParams.Version < 5)
291 emitLineTablePrologueV2IncludeAndFileTable(P, Section);
292 else
293 emitLineTablePrologueV5IncludeAndFileTable(P, Section);
294 }
295
296 void emitLineTableRows(
297 const DWARFDebugLine::LineTable &LineTable, SectionDescriptor &Section,
298 ArrayRef<uint64_t> OrigRowIndices = {},
299 DenseMap<uint64_t, uint64_t> *RowIndexToSeqStartOffset = nullptr) {
300
301 MCDwarfLineTableParams Params;
302 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
303 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
304 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
305
306 SmallString<128> EncodingBuffer;
307
308 if (LineTable.Rows.empty()) {
309 // We only have the dummy entry, dsymutil emits an entry with a 0
310 // address in that case.
311 MCDwarfLineAddr::encode(Context&: *MC, Params, LineDelta: std::numeric_limits<int64_t>::max(),
312 AddrDelta: 0, OS&: EncodingBuffer);
313 Section.OS.write(Ptr: EncodingBuffer.c_str(), Size: EncodingBuffer.size());
314 return;
315 }
316
317 // Line table state machine fields
318 unsigned FileNum = 1;
319 unsigned LastLine = 1;
320 unsigned Column = 0;
321 unsigned Discriminator = 0;
322 unsigned IsStatement = 1;
323 unsigned Isa = 0;
324 uint64_t Address = -1ULL;
325
326 unsigned RowsSinceLastSequence = 0;
327 // Offset of the DW_LNE_set_address opcode that opens the sequence
328 // currently being emitted. Recorded per input row index so that
329 // DW_AT_LLVM_stmt_sequence attributes can be resolved by row — which
330 // is collision-free under ICF, unlike keying by output address.
331 uint64_t CurrentSeqStartOffset = 0;
332 constexpr uint64_t InvalidRowIndex = std::numeric_limits<uint64_t>::max();
333 assert(
334 (!RowIndexToSeqStartOffset ||
335 OrigRowIndices.size() == LineTable.Rows.size()) &&
336 "OrigRowIndices must be supplied alongside RowIndexToSeqStartOffset");
337
338 for (auto [Idx, Row] : llvm::enumerate(First: LineTable.Rows)) {
339 int64_t AddressDelta;
340 if (Address == -1ULL) {
341 CurrentSeqStartOffset = Section.OS.tell();
342 Section.emitIntVal(Val: dwarf::DW_LNS_extended_op, Size: 1);
343 encodeULEB128(Value: Section.getFormParams().AddrSize + 1, OS&: Section.OS);
344 Section.emitIntVal(Val: dwarf::DW_LNE_set_address, Size: 1);
345 Section.emitIntVal(Val: Row.Address.Address,
346 Size: Section.getFormParams().AddrSize);
347 AddressDelta = 0;
348 } else {
349 AddressDelta =
350 (Row.Address.Address - Address) / LineTable.Prologue.MinInstLength;
351 }
352 if (RowIndexToSeqStartOffset) {
353 uint64_t InputRowIdx = OrigRowIndices[Idx];
354 if (InputRowIdx != InvalidRowIndex)
355 (*RowIndexToSeqStartOffset)[InputRowIdx] = CurrentSeqStartOffset;
356 }
357
358 // FIXME: code copied and transformed from
359 // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share this
360 // code, but the current compatibility requirement with classic dsymutil
361 // makes it hard. Revisit that once this requirement is dropped.
362
363 if (FileNum != Row.File) {
364 FileNum = Row.File;
365 Section.emitIntVal(Val: dwarf::DW_LNS_set_file, Size: 1);
366 encodeULEB128(Value: FileNum, OS&: Section.OS);
367 }
368 if (Column != Row.Column) {
369 Column = Row.Column;
370 Section.emitIntVal(Val: dwarf::DW_LNS_set_column, Size: 1);
371 encodeULEB128(Value: Column, OS&: Section.OS);
372 }
373 if (Discriminator != Row.Discriminator && MC->getDwarfVersion() >= 4) {
374 Discriminator = Row.Discriminator;
375 unsigned Size = getULEB128Size(Value: Discriminator);
376 Section.emitIntVal(Val: dwarf::DW_LNS_extended_op, Size: 1);
377 encodeULEB128(Value: Size + 1, OS&: Section.OS);
378 Section.emitIntVal(Val: dwarf::DW_LNE_set_discriminator, Size: 1);
379 encodeULEB128(Value: Discriminator, OS&: Section.OS);
380 }
381 Discriminator = 0;
382
383 if (Isa != Row.Isa) {
384 Isa = Row.Isa;
385 Section.emitIntVal(Val: dwarf::DW_LNS_set_isa, Size: 1);
386 encodeULEB128(Value: Isa, OS&: Section.OS);
387 }
388 if (IsStatement != Row.IsStmt) {
389 IsStatement = Row.IsStmt;
390 Section.emitIntVal(Val: dwarf::DW_LNS_negate_stmt, Size: 1);
391 }
392 if (Row.BasicBlock)
393 Section.emitIntVal(Val: dwarf::DW_LNS_set_basic_block, Size: 1);
394
395 if (Row.PrologueEnd)
396 Section.emitIntVal(Val: dwarf::DW_LNS_set_prologue_end, Size: 1);
397
398 if (Row.EpilogueBegin)
399 Section.emitIntVal(Val: dwarf::DW_LNS_set_epilogue_begin, Size: 1);
400
401 int64_t LineDelta = int64_t(Row.Line) - LastLine;
402 if (!Row.EndSequence) {
403 MCDwarfLineAddr::encode(Context&: *MC, Params, LineDelta, AddrDelta: AddressDelta,
404 OS&: EncodingBuffer);
405 Section.OS.write(Ptr: EncodingBuffer.c_str(), Size: EncodingBuffer.size());
406 EncodingBuffer.resize(N: 0);
407 Address = Row.Address.Address;
408 LastLine = Row.Line;
409 RowsSinceLastSequence++;
410 } else {
411 if (LineDelta) {
412 Section.emitIntVal(Val: dwarf::DW_LNS_advance_line, Size: 1);
413 encodeSLEB128(Value: LineDelta, OS&: Section.OS);
414 }
415 if (AddressDelta) {
416 Section.emitIntVal(Val: dwarf::DW_LNS_advance_pc, Size: 1);
417 encodeULEB128(Value: AddressDelta, OS&: Section.OS);
418 }
419 MCDwarfLineAddr::encode(Context&: *MC, Params,
420 LineDelta: std::numeric_limits<int64_t>::max(), AddrDelta: 0,
421 OS&: EncodingBuffer);
422 Section.OS.write(Ptr: EncodingBuffer.c_str(), Size: EncodingBuffer.size());
423 EncodingBuffer.resize(N: 0);
424 Address = -1ULL;
425 LastLine = FileNum = IsStatement = 1;
426 RowsSinceLastSequence = Column = Discriminator = Isa = 0;
427 }
428 }
429
430 if (RowsSinceLastSequence) {
431 MCDwarfLineAddr::encode(Context&: *MC, Params, LineDelta: std::numeric_limits<int64_t>::max(),
432 AddrDelta: 0, OS&: EncodingBuffer);
433 Section.OS.write(Ptr: EncodingBuffer.c_str(), Size: EncodingBuffer.size());
434 EncodingBuffer.resize(N: 0);
435 }
436 }
437
438 /// Emit \p Path, a path from the input line table, as a string of form
439 /// \p Form.
440 void emitPath(SectionDescriptor &Section, dwarf::Form Form,
441 const char *Path) {
442 Section.emitString(StringForm: Form, StringVal: U.remapPath(Path).c_str());
443 }
444
445 Triple TheTriple;
446 DwarfUnit &U;
447
448 MCTargetOptions MCOptions;
449 std::unique_ptr<MCRegisterInfo> MRI;
450 std::unique_ptr<MCAsmInfo> MAI;
451 std::unique_ptr<MCContext> MC;
452 std::unique_ptr<MCSubtargetInfo> MSTI;
453};
454
455} // end of namespace parallel
456} // end of namespace dwarf_linker
457} // end of namespace llvm
458
459#endif // LLVM_LIB_DWARFLINKER_PARALLEL_DEBUGLINESECTIONEMITTER_H
460