aboutsummaryrefslogtreecommitdiff
path: root/contrib/llvm-project/llvm/lib/DWARFLinker/Parallel/DebugLineSectionEmitter.h
blob: 1839164dcec17e63c80d17634667f3ac58d48725 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//===- DebugLineSectionEmitter.h --------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_LIB_DWARFLINKER_PARALLEL_DEBUGLINESECTIONEMITTER_H
#define LLVM_LIB_DWARFLINKER_PARALLEL_DEBUGLINESECTIONEMITTER_H

#include "DWARFEmitterImpl.h"
#include "llvm/DWARFLinker/AddressesMap.h"
#include "llvm/DWARFLinker/Parallel/DWARFLinker.h"
#include "llvm/DebugInfo/DWARF/DWARFObject.h"
#include "llvm/MC/MCTargetOptionsCommandFlags.h"
#include "llvm/MC/TargetRegistry.h"

namespace llvm {
namespace dwarf_linker {
namespace parallel {

/// This class emits specified line table into the .debug_line section.
class DebugLineSectionEmitter {
public:
  DebugLineSectionEmitter(const Triple &TheTriple, DwarfUnit &U)
      : TheTriple(TheTriple), U(U) {}

  Error emit(const DWARFDebugLine::LineTable &LineTable) {
    // FIXME: remove dependence on MCDwarfLineAddr::encode.
    // As we reuse MCDwarfLineAddr::encode, we need to create/initialize
    // some MC* classes.
    if (Error Err = init(TheTriple))
      return Err;

    // Get descriptor for output .debug_line section.
    SectionDescriptor &OutSection =
        U.getOrCreateSectionDescriptor(DebugSectionKind::DebugLine);

    // unit_length.
    OutSection.emitUnitLength(0xBADDEF);
    uint64_t OffsetAfterUnitLength = OutSection.OS.tell();

    // Emit prologue.
    emitLineTablePrologue(LineTable.Prologue, OutSection);

    // Emit rows.
    emitLineTableRows(LineTable, OutSection);
    uint64_t OffsetAfterEnd = OutSection.OS.tell();

    // Update unit length field with actual length value.
    assert(OffsetAfterUnitLength -
               OutSection.getFormParams().getDwarfOffsetByteSize() <
           OffsetAfterUnitLength);
    OutSection.apply(OffsetAfterUnitLength -
                         OutSection.getFormParams().getDwarfOffsetByteSize(),
                     dwarf::DW_FORM_sec_offset,
                     OffsetAfterEnd - OffsetAfterUnitLength);

    return Error::success();
  }

private:
  Error init(Triple TheTriple) {
    std::string ErrorStr;
    std::string TripleName;

    // Get the target.
    const Target *TheTarget =
        TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
    if (!TheTarget)
      return createStringError(std::errc::invalid_argument, ErrorStr.c_str());
    TripleName = TheTriple.getTriple();

    // Create all the MC Objects.
    MRI.reset(TheTarget->createMCRegInfo(TripleName));
    if (!MRI)
      return createStringError(std::errc::invalid_argument,
                               "no register info for target %s",
                               TripleName.c_str());

    MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
    MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
    if (!MAI)
      return createStringError(std::errc::invalid_argument,
                               "no asm info for target %s", TripleName.c_str());

    MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
    if (!MSTI)
      return createStringError(std::errc::invalid_argument,
                               "no subtarget info for target %s",
                               TripleName.c_str());

    MC.reset(new MCContext(TheTriple, MAI.get(), MRI.get(), MSTI.get(), nullptr,
                           nullptr, true, "__DWARF"));

    return Error::success();
  }

  void emitLineTablePrologue(const DWARFDebugLine::Prologue &P,
                             SectionDescriptor &Section) {
    // version (uhalf).
    Section.emitIntVal(P.getVersion(), 2);
    if (P.getVersion() == 5) {
      // address_size (ubyte).
      Section.emitIntVal(P.getAddressSize(), 1);

      // segment_selector_size (ubyte).
      Section.emitIntVal(P.SegSelectorSize, 1);
    }

    // header_length.
    Section.emitOffset(0xBADDEF);

    uint64_t OffsetAfterPrologueLength = Section.OS.tell();
    emitLineTableProloguePayload(P, Section);
    uint64_t OffsetAfterPrologueEnd = Section.OS.tell();

    // Update prologue length field with actual length value.
    Section.apply(OffsetAfterPrologueLength -
                      Section.getFormParams().getDwarfOffsetByteSize(),
                  dwarf::DW_FORM_sec_offset,
                  OffsetAfterPrologueEnd - OffsetAfterPrologueLength);
  }

  void
  emitLineTablePrologueV2IncludeAndFileTable(const DWARFDebugLine::Prologue &P,
                                             SectionDescriptor &Section) {
    // include_directories (sequence of path names).
    for (const DWARFFormValue &Include : P.IncludeDirectories) {
      std::optional<const char *> IncludeStr = dwarf::toString(Include);
      if (!IncludeStr) {
        U.warn("cann't read string from line table.");
        return;
      }

      Section.emitString(Include.getForm(), *IncludeStr);
    }
    // The last entry is followed by a single null byte.
    Section.emitIntVal(0, 1);

    // file_names (sequence of file entries).
    for (const DWARFDebugLine::FileNameEntry &File : P.FileNames) {
      std::optional<const char *> FileNameStr = dwarf::toString(File.Name);
      if (!FileNameStr) {
        U.warn("cann't read string from line table.");
        return;
      }

      // A null-terminated string containing the full or relative path name of a
      // source file.
      Section.emitString(File.Name.getForm(), *FileNameStr);

      // An unsigned LEB128 number representing the directory index of a
      // directory in the include_directories section.
      encodeULEB128(File.DirIdx, Section.OS);
      // An unsigned LEB128 number representing the (implementation-defined)
      // time of last modification for the file, or 0 if not available.
      encodeULEB128(File.ModTime, Section.OS);
      // An unsigned LEB128 number representing the length in bytes of the file,
      // or 0 if not available.
      encodeULEB128(File.Length, Section.OS);
    }
    // The last entry is followed by a single null byte.
    Section.emitIntVal(0, 1);
  }

  void
  emitLineTablePrologueV5IncludeAndFileTable(const DWARFDebugLine::Prologue &P,
                                             SectionDescriptor &Section) {
    if (P.IncludeDirectories.empty()) {
      // directory_entry_format_count(ubyte).
      Section.emitIntVal(0, 1);
    } else {
      // directory_entry_format_count(ubyte).
      Section.emitIntVal(1, 1);

      // directory_entry_format (sequence of ULEB128 pairs).
      encodeULEB128(dwarf::DW_LNCT_path, Section.OS);
      encodeULEB128(P.IncludeDirectories[0].getForm(), Section.OS);
    }

    // directories_count (ULEB128).
    encodeULEB128(P.IncludeDirectories.size(), Section.OS);
    // directories (sequence of directory names).
    for (auto Include : P.IncludeDirectories) {
      std::optional<const char *> IncludeStr = dwarf::toString(Include);
      if (!IncludeStr) {
        U.warn("cann't read string from line table.");
        return;
      }

      Section.emitString(Include.getForm(), *IncludeStr);
    }

    bool HasChecksums = P.ContentTypes.HasMD5;
    bool HasInlineSources = P.ContentTypes.HasSource;

    dwarf::Form FileNameForm = dwarf::DW_FORM_string;
    dwarf::Form LLVMSourceForm = dwarf::DW_FORM_string;

    if (P.FileNames.empty()) {
      // file_name_entry_format_count (ubyte).
      Section.emitIntVal(0, 1);
    } else {
      FileNameForm = P.FileNames[0].Name.getForm();
      LLVMSourceForm = P.FileNames[0].Source.getForm();

      // file_name_entry_format_count (ubyte).
      Section.emitIntVal(
          2 + (HasChecksums ? 1 : 0) + (HasInlineSources ? 1 : 0), 1);

      // file_name_entry_format (sequence of ULEB128 pairs).
      encodeULEB128(dwarf::DW_LNCT_path, Section.OS);
      encodeULEB128(FileNameForm, Section.OS);

      encodeULEB128(dwarf::DW_LNCT_directory_index, Section.OS);
      encodeULEB128(dwarf::DW_FORM_data1, Section.OS);

      if (HasChecksums) {
        encodeULEB128(dwarf::DW_LNCT_MD5, Section.OS);
        encodeULEB128(dwarf::DW_FORM_data16, Section.OS);
      }

      if (HasInlineSources) {
        encodeULEB128(dwarf::DW_LNCT_LLVM_source, Section.OS);
        encodeULEB128(LLVMSourceForm, Section.OS);
      }
    }

    // file_names_count (ULEB128).
    encodeULEB128(P.FileNames.size(), Section.OS);

    // file_names (sequence of file name entries).
    for (auto File : P.FileNames) {
      std::optional<const char *> FileNameStr = dwarf::toString(File.Name);
      if (!FileNameStr) {
        U.warn("cann't read string from line table.");
        return;
      }

      // A null-terminated string containing the full or relative path name of a
      // source file.
      Section.emitString(FileNameForm, *FileNameStr);
      Section.emitIntVal(File.DirIdx, 1);

      if (HasChecksums) {
        assert((File.Checksum.size() == 16) &&
               "checksum size is not equal to 16 bytes.");
        Section.emitBinaryData(
            StringRef(reinterpret_cast<const char *>(File.Checksum.data()),
                      File.Checksum.size()));
      }

      if (HasInlineSources) {
        std::optional<const char *> FileSourceStr =
            dwarf::toString(File.Source);
        if (!FileSourceStr) {
          U.warn("cann't read string from line table.");
          return;
        }

        Section.emitString(LLVMSourceForm, *FileSourceStr);
      }
    }
  }

  void emitLineTableProloguePayload(const DWARFDebugLine::Prologue &P,
                                    SectionDescriptor &Section) {
    // minimum_instruction_length (ubyte).
    Section.emitIntVal(P.MinInstLength, 1);
    if (P.FormParams.Version >= 4) {
      // maximum_operations_per_instruction (ubyte).
      Section.emitIntVal(P.MaxOpsPerInst, 1);
    }
    // default_is_stmt (ubyte).
    Section.emitIntVal(P.DefaultIsStmt, 1);
    // line_base (sbyte).
    Section.emitIntVal(P.LineBase, 1);
    // line_range (ubyte).
    Section.emitIntVal(P.LineRange, 1);
    // opcode_base (ubyte).
    Section.emitIntVal(P.OpcodeBase, 1);

    // standard_opcode_lengths (array of ubyte).
    for (auto Length : P.StandardOpcodeLengths)
      Section.emitIntVal(Length, 1);

    if (P.FormParams.Version < 5)
      emitLineTablePrologueV2IncludeAndFileTable(P, Section);
    else
      emitLineTablePrologueV5IncludeAndFileTable(P, Section);
  }

  void emitLineTableRows(const DWARFDebugLine::LineTable &LineTable,
                         SectionDescriptor &Section) {

    MCDwarfLineTableParams Params;
    Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
    Params.DWARF2LineBase = LineTable.Prologue.LineBase;
    Params.DWARF2LineRange = LineTable.Prologue.LineRange;

    SmallString<128> EncodingBuffer;

    if (LineTable.Rows.empty()) {
      // We only have the dummy entry, dsymutil emits an entry with a 0
      // address in that case.
      MCDwarfLineAddr::encode(*MC, Params, std::numeric_limits<int64_t>::max(),
                              0, EncodingBuffer);
      Section.OS.write(EncodingBuffer.c_str(), EncodingBuffer.size());
      return;
    }

    // Line table state machine fields
    unsigned FileNum = 1;
    unsigned LastLine = 1;
    unsigned Column = 0;
    unsigned IsStatement = 1;
    unsigned Isa = 0;
    uint64_t Address = -1ULL;

    unsigned RowsSinceLastSequence = 0;

    for (const DWARFDebugLine::Row &Row : LineTable.Rows) {
      int64_t AddressDelta;
      if (Address == -1ULL) {
        Section.emitIntVal(dwarf::DW_LNS_extended_op, 1);
        encodeULEB128(Section.getFormParams().AddrSize + 1, Section.OS);
        Section.emitIntVal(dwarf::DW_LNE_set_address, 1);
        Section.emitIntVal(Row.Address.Address,
                           Section.getFormParams().AddrSize);
        AddressDelta = 0;
      } else {
        AddressDelta =
            (Row.Address.Address - Address) / LineTable.Prologue.MinInstLength;
      }

      // FIXME: code copied and transformed from
      // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share this
      // code, but the current compatibility requirement with classic dsymutil
      // makes it hard. Revisit that once this requirement is dropped.

      if (FileNum != Row.File) {
        FileNum = Row.File;
        Section.emitIntVal(dwarf::DW_LNS_set_file, 1);
        encodeULEB128(FileNum, Section.OS);
      }
      if (Column != Row.Column) {
        Column = Row.Column;
        Section.emitIntVal(dwarf::DW_LNS_set_column, 1);
        encodeULEB128(Column, Section.OS);
      }

      // FIXME: We should handle the discriminator here, but dsymutil doesn't
      // consider it, thus ignore it for now.

      if (Isa != Row.Isa) {
        Isa = Row.Isa;
        Section.emitIntVal(dwarf::DW_LNS_set_isa, 1);
        encodeULEB128(Isa, Section.OS);
      }
      if (IsStatement != Row.IsStmt) {
        IsStatement = Row.IsStmt;
        Section.emitIntVal(dwarf::DW_LNS_negate_stmt, 1);
      }
      if (Row.BasicBlock)
        Section.emitIntVal(dwarf::DW_LNS_set_basic_block, 1);

      if (Row.PrologueEnd)
        Section.emitIntVal(dwarf::DW_LNS_set_prologue_end, 1);

      if (Row.EpilogueBegin)
        Section.emitIntVal(dwarf::DW_LNS_set_epilogue_begin, 1);

      int64_t LineDelta = int64_t(Row.Line) - LastLine;
      if (!Row.EndSequence) {
        MCDwarfLineAddr::encode(*MC, Params, LineDelta, AddressDelta,
                                EncodingBuffer);
        Section.OS.write(EncodingBuffer.c_str(), EncodingBuffer.size());
        EncodingBuffer.resize(0);
        Address = Row.Address.Address;
        LastLine = Row.Line;
        RowsSinceLastSequence++;
      } else {
        if (LineDelta) {
          Section.emitIntVal(dwarf::DW_LNS_advance_line, 1);
          encodeSLEB128(LineDelta, Section.OS);
        }
        if (AddressDelta) {
          Section.emitIntVal(dwarf::DW_LNS_advance_pc, 1);
          encodeULEB128(AddressDelta, Section.OS);
        }
        MCDwarfLineAddr::encode(*MC, Params,
                                std::numeric_limits<int64_t>::max(), 0,
                                EncodingBuffer);
        Section.OS.write(EncodingBuffer.c_str(), EncodingBuffer.size());
        EncodingBuffer.resize(0);
        Address = -1ULL;
        LastLine = FileNum = IsStatement = 1;
        RowsSinceLastSequence = Column = Isa = 0;
      }
    }

    if (RowsSinceLastSequence) {
      MCDwarfLineAddr::encode(*MC, Params, std::numeric_limits<int64_t>::max(),
                              0, EncodingBuffer);
      Section.OS.write(EncodingBuffer.c_str(), EncodingBuffer.size());
      EncodingBuffer.resize(0);
    }
  }

  Triple TheTriple;
  DwarfUnit &U;

  std::unique_ptr<MCRegisterInfo> MRI;
  std::unique_ptr<MCAsmInfo> MAI;
  std::unique_ptr<MCContext> MC;
  std::unique_ptr<MCSubtargetInfo> MSTI;
};

} // end of namespace parallel
} // end of namespace dwarf_linker
} // end of namespace llvm

#endif // LLVM_LIB_DWARFLINKER_PARALLEL_DEBUGLINESECTIONEMITTER_H