DWARFDebugLine.cpp revision 360784
1//===- DWARFDebugLine.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/DebugInfo/DWARF/DWARFDebugLine.h"
10#include "llvm/ADT/Optional.h"
11#include "llvm/ADT/SmallString.h"
12#include "llvm/ADT/SmallVector.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/BinaryFormat/Dwarf.h"
15#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
16#include "llvm/DebugInfo/DWARF/DWARFRelocMap.h"
17#include "llvm/Support/Errc.h"
18#include "llvm/Support/Format.h"
19#include "llvm/Support/WithColor.h"
20#include "llvm/Support/raw_ostream.h"
21#include <algorithm>
22#include <cassert>
23#include <cinttypes>
24#include <cstdint>
25#include <cstdio>
26#include <utility>
27
28using namespace llvm;
29using namespace dwarf;
30
31using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
32
33namespace {
34
35struct ContentDescriptor {
36  dwarf::LineNumberEntryFormat Type;
37  dwarf::Form Form;
38};
39
40using ContentDescriptors = SmallVector<ContentDescriptor, 4>;
41
42} // end anonymous namespace
43
44void DWARFDebugLine::ContentTypeTracker::trackContentType(
45    dwarf::LineNumberEntryFormat ContentType) {
46  switch (ContentType) {
47  case dwarf::DW_LNCT_timestamp:
48    HasModTime = true;
49    break;
50  case dwarf::DW_LNCT_size:
51    HasLength = true;
52    break;
53  case dwarf::DW_LNCT_MD5:
54    HasMD5 = true;
55    break;
56  case dwarf::DW_LNCT_LLVM_source:
57    HasSource = true;
58    break;
59  default:
60    // We only care about values we consider optional, and new values may be
61    // added in the vendor extension range, so we do not match exhaustively.
62    break;
63  }
64}
65
66DWARFDebugLine::Prologue::Prologue() { clear(); }
67
68bool DWARFDebugLine::Prologue::hasFileAtIndex(uint64_t FileIndex) const {
69  uint16_t DwarfVersion = getVersion();
70  assert(DwarfVersion != 0 &&
71         "line table prologue has no dwarf version information");
72  if (DwarfVersion >= 5)
73    return FileIndex < FileNames.size();
74  return FileIndex != 0 && FileIndex <= FileNames.size();
75}
76
77const llvm::DWARFDebugLine::FileNameEntry &
78DWARFDebugLine::Prologue::getFileNameEntry(uint64_t Index) const {
79  uint16_t DwarfVersion = getVersion();
80  assert(DwarfVersion != 0 &&
81         "line table prologue has no dwarf version information");
82  // In DWARF v5 the file names are 0-indexed.
83  if (DwarfVersion >= 5)
84    return FileNames[Index];
85  return FileNames[Index - 1];
86}
87
88void DWARFDebugLine::Prologue::clear() {
89  TotalLength = PrologueLength = 0;
90  SegSelectorSize = 0;
91  MinInstLength = MaxOpsPerInst = DefaultIsStmt = LineBase = LineRange = 0;
92  OpcodeBase = 0;
93  FormParams = dwarf::FormParams({0, 0, DWARF32});
94  ContentTypes = ContentTypeTracker();
95  StandardOpcodeLengths.clear();
96  IncludeDirectories.clear();
97  FileNames.clear();
98}
99
100void DWARFDebugLine::Prologue::dump(raw_ostream &OS,
101                                    DIDumpOptions DumpOptions) const {
102  OS << "Line table prologue:\n"
103     << format("    total_length: 0x%8.8" PRIx64 "\n", TotalLength)
104     << format("         version: %u\n", getVersion());
105  if (getVersion() >= 5)
106    OS << format("    address_size: %u\n", getAddressSize())
107       << format(" seg_select_size: %u\n", SegSelectorSize);
108  OS << format(" prologue_length: 0x%8.8" PRIx64 "\n", PrologueLength)
109     << format(" min_inst_length: %u\n", MinInstLength)
110     << format(getVersion() >= 4 ? "max_ops_per_inst: %u\n" : "", MaxOpsPerInst)
111     << format(" default_is_stmt: %u\n", DefaultIsStmt)
112     << format("       line_base: %i\n", LineBase)
113     << format("      line_range: %u\n", LineRange)
114     << format("     opcode_base: %u\n", OpcodeBase);
115
116  for (uint32_t I = 0; I != StandardOpcodeLengths.size(); ++I)
117    OS << format("standard_opcode_lengths[%s] = %u\n",
118                 LNStandardString(I + 1).data(), StandardOpcodeLengths[I]);
119
120  if (!IncludeDirectories.empty()) {
121    // DWARF v5 starts directory indexes at 0.
122    uint32_t DirBase = getVersion() >= 5 ? 0 : 1;
123    for (uint32_t I = 0; I != IncludeDirectories.size(); ++I) {
124      OS << format("include_directories[%3u] = ", I + DirBase);
125      IncludeDirectories[I].dump(OS, DumpOptions);
126      OS << '\n';
127    }
128  }
129
130  if (!FileNames.empty()) {
131    // DWARF v5 starts file indexes at 0.
132    uint32_t FileBase = getVersion() >= 5 ? 0 : 1;
133    for (uint32_t I = 0; I != FileNames.size(); ++I) {
134      const FileNameEntry &FileEntry = FileNames[I];
135      OS <<   format("file_names[%3u]:\n", I + FileBase);
136      OS <<          "           name: ";
137      FileEntry.Name.dump(OS, DumpOptions);
138      OS << '\n'
139         <<   format("      dir_index: %" PRIu64 "\n", FileEntry.DirIdx);
140      if (ContentTypes.HasMD5)
141        OS <<        "   md5_checksum: " << FileEntry.Checksum.digest() << '\n';
142      if (ContentTypes.HasModTime)
143        OS << format("       mod_time: 0x%8.8" PRIx64 "\n", FileEntry.ModTime);
144      if (ContentTypes.HasLength)
145        OS << format("         length: 0x%8.8" PRIx64 "\n", FileEntry.Length);
146      if (ContentTypes.HasSource) {
147        OS <<        "         source: ";
148        FileEntry.Source.dump(OS, DumpOptions);
149        OS << '\n';
150      }
151    }
152  }
153}
154
155// Parse v2-v4 directory and file tables.
156static void
157parseV2DirFileTables(const DWARFDataExtractor &DebugLineData,
158                     uint64_t *OffsetPtr, uint64_t EndPrologueOffset,
159                     DWARFDebugLine::ContentTypeTracker &ContentTypes,
160                     std::vector<DWARFFormValue> &IncludeDirectories,
161                     std::vector<DWARFDebugLine::FileNameEntry> &FileNames) {
162  while (*OffsetPtr < EndPrologueOffset) {
163    StringRef S = DebugLineData.getCStrRef(OffsetPtr);
164    if (S.empty())
165      break;
166    DWARFFormValue Dir =
167        DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, S.data());
168    IncludeDirectories.push_back(Dir);
169  }
170
171  while (*OffsetPtr < EndPrologueOffset) {
172    StringRef Name = DebugLineData.getCStrRef(OffsetPtr);
173    if (Name.empty())
174      break;
175    DWARFDebugLine::FileNameEntry FileEntry;
176    FileEntry.Name =
177        DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, Name.data());
178    FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr);
179    FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr);
180    FileEntry.Length = DebugLineData.getULEB128(OffsetPtr);
181    FileNames.push_back(FileEntry);
182  }
183
184  ContentTypes.HasModTime = true;
185  ContentTypes.HasLength = true;
186}
187
188// Parse v5 directory/file entry content descriptions.
189// Returns the descriptors, or an error if we did not find a path or ran off
190// the end of the prologue.
191static llvm::Expected<ContentDescriptors>
192parseV5EntryFormat(const DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr,
193                   DWARFDebugLine::ContentTypeTracker *ContentTypes) {
194  ContentDescriptors Descriptors;
195  int FormatCount = DebugLineData.getU8(OffsetPtr);
196  bool HasPath = false;
197  for (int I = 0; I != FormatCount; ++I) {
198    ContentDescriptor Descriptor;
199    Descriptor.Type =
200      dwarf::LineNumberEntryFormat(DebugLineData.getULEB128(OffsetPtr));
201    Descriptor.Form = dwarf::Form(DebugLineData.getULEB128(OffsetPtr));
202    if (Descriptor.Type == dwarf::DW_LNCT_path)
203      HasPath = true;
204    if (ContentTypes)
205      ContentTypes->trackContentType(Descriptor.Type);
206    Descriptors.push_back(Descriptor);
207  }
208
209  if (!HasPath)
210    return createStringError(errc::invalid_argument,
211                             "failed to parse entry content descriptions"
212                             " because no path was found");
213  return Descriptors;
214}
215
216static Error
217parseV5DirFileTables(const DWARFDataExtractor &DebugLineData,
218                     uint64_t *OffsetPtr, const dwarf::FormParams &FormParams,
219                     const DWARFContext &Ctx, const DWARFUnit *U,
220                     DWARFDebugLine::ContentTypeTracker &ContentTypes,
221                     std::vector<DWARFFormValue> &IncludeDirectories,
222                     std::vector<DWARFDebugLine::FileNameEntry> &FileNames) {
223  // Get the directory entry description.
224  llvm::Expected<ContentDescriptors> DirDescriptors =
225      parseV5EntryFormat(DebugLineData, OffsetPtr, nullptr);
226  if (!DirDescriptors)
227    return DirDescriptors.takeError();
228
229  // Get the directory entries, according to the format described above.
230  int DirEntryCount = DebugLineData.getU8(OffsetPtr);
231  for (int I = 0; I != DirEntryCount; ++I) {
232    for (auto Descriptor : *DirDescriptors) {
233      DWARFFormValue Value(Descriptor.Form);
234      switch (Descriptor.Type) {
235      case DW_LNCT_path:
236        if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U))
237          return createStringError(errc::invalid_argument,
238                                   "failed to parse directory entry because "
239                                   "extracting the form value failed.");
240        IncludeDirectories.push_back(Value);
241        break;
242      default:
243        if (!Value.skipValue(DebugLineData, OffsetPtr, FormParams))
244          return createStringError(errc::invalid_argument,
245                                   "failed to parse directory entry because "
246                                   "skipping the form value failed.");
247      }
248    }
249  }
250
251  // Get the file entry description.
252  llvm::Expected<ContentDescriptors> FileDescriptors =
253      parseV5EntryFormat(DebugLineData, OffsetPtr, &ContentTypes);
254  if (!FileDescriptors)
255    return FileDescriptors.takeError();
256
257  // Get the file entries, according to the format described above.
258  int FileEntryCount = DebugLineData.getU8(OffsetPtr);
259  for (int I = 0; I != FileEntryCount; ++I) {
260    DWARFDebugLine::FileNameEntry FileEntry;
261    for (auto Descriptor : *FileDescriptors) {
262      DWARFFormValue Value(Descriptor.Form);
263      if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U))
264        return createStringError(errc::invalid_argument,
265                                 "failed to parse file entry because "
266                                 "extracting the form value failed.");
267      switch (Descriptor.Type) {
268      case DW_LNCT_path:
269        FileEntry.Name = Value;
270        break;
271      case DW_LNCT_LLVM_source:
272        FileEntry.Source = Value;
273        break;
274      case DW_LNCT_directory_index:
275        FileEntry.DirIdx = Value.getAsUnsignedConstant().getValue();
276        break;
277      case DW_LNCT_timestamp:
278        FileEntry.ModTime = Value.getAsUnsignedConstant().getValue();
279        break;
280      case DW_LNCT_size:
281        FileEntry.Length = Value.getAsUnsignedConstant().getValue();
282        break;
283      case DW_LNCT_MD5:
284        if (!Value.getAsBlock() || Value.getAsBlock().getValue().size() != 16)
285          return createStringError(
286              errc::invalid_argument,
287              "failed to parse file entry because the MD5 hash is invalid");
288        std::uninitialized_copy_n(Value.getAsBlock().getValue().begin(), 16,
289                                  FileEntry.Checksum.Bytes.begin());
290        break;
291      default:
292        break;
293      }
294    }
295    FileNames.push_back(FileEntry);
296  }
297  return Error::success();
298}
299
300Error DWARFDebugLine::Prologue::parse(const DWARFDataExtractor &DebugLineData,
301                                      uint64_t *OffsetPtr,
302                                      const DWARFContext &Ctx,
303                                      const DWARFUnit *U) {
304  const uint64_t PrologueOffset = *OffsetPtr;
305
306  clear();
307  TotalLength = DebugLineData.getRelocatedValue(4, OffsetPtr);
308  if (TotalLength == dwarf::DW_LENGTH_DWARF64) {
309    FormParams.Format = dwarf::DWARF64;
310    TotalLength = DebugLineData.getU64(OffsetPtr);
311  } else if (TotalLength >= dwarf::DW_LENGTH_lo_reserved) {
312    return createStringError(errc::invalid_argument,
313        "parsing line table prologue at offset 0x%8.8" PRIx64
314        " unsupported reserved unit length found of value 0x%8.8" PRIx64,
315        PrologueOffset, TotalLength);
316  }
317  FormParams.Version = DebugLineData.getU16(OffsetPtr);
318  if (getVersion() < 2)
319    return createStringError(errc::not_supported,
320                       "parsing line table prologue at offset 0x%8.8" PRIx64
321                       " found unsupported version 0x%2.2" PRIx16,
322                       PrologueOffset, getVersion());
323
324  if (getVersion() >= 5) {
325    FormParams.AddrSize = DebugLineData.getU8(OffsetPtr);
326    assert((DebugLineData.getAddressSize() == 0 ||
327            DebugLineData.getAddressSize() == getAddressSize()) &&
328           "Line table header and data extractor disagree");
329    SegSelectorSize = DebugLineData.getU8(OffsetPtr);
330  }
331
332  PrologueLength =
333      DebugLineData.getRelocatedValue(sizeofPrologueLength(), OffsetPtr);
334  const uint64_t EndPrologueOffset = PrologueLength + *OffsetPtr;
335  MinInstLength = DebugLineData.getU8(OffsetPtr);
336  if (getVersion() >= 4)
337    MaxOpsPerInst = DebugLineData.getU8(OffsetPtr);
338  DefaultIsStmt = DebugLineData.getU8(OffsetPtr);
339  LineBase = DebugLineData.getU8(OffsetPtr);
340  LineRange = DebugLineData.getU8(OffsetPtr);
341  OpcodeBase = DebugLineData.getU8(OffsetPtr);
342
343  StandardOpcodeLengths.reserve(OpcodeBase - 1);
344  for (uint32_t I = 1; I < OpcodeBase; ++I) {
345    uint8_t OpLen = DebugLineData.getU8(OffsetPtr);
346    StandardOpcodeLengths.push_back(OpLen);
347  }
348
349  if (getVersion() >= 5) {
350    if (Error E =
351            parseV5DirFileTables(DebugLineData, OffsetPtr, FormParams, Ctx, U,
352                                 ContentTypes, IncludeDirectories, FileNames)) {
353      return joinErrors(
354          createStringError(
355              errc::invalid_argument,
356              "parsing line table prologue at 0x%8.8" PRIx64
357              " found an invalid directory or file table description at"
358              " 0x%8.8" PRIx64,
359              PrologueOffset, *OffsetPtr),
360          std::move(E));
361    }
362  } else
363    parseV2DirFileTables(DebugLineData, OffsetPtr, EndPrologueOffset,
364                         ContentTypes, IncludeDirectories, FileNames);
365
366  if (*OffsetPtr != EndPrologueOffset)
367    return createStringError(errc::invalid_argument,
368                       "parsing line table prologue at 0x%8.8" PRIx64
369                       " should have ended at 0x%8.8" PRIx64
370                       " but it ended at 0x%8.8" PRIx64,
371                       PrologueOffset, EndPrologueOffset, *OffsetPtr);
372  return Error::success();
373}
374
375DWARFDebugLine::Row::Row(bool DefaultIsStmt) { reset(DefaultIsStmt); }
376
377void DWARFDebugLine::Row::postAppend() {
378  Discriminator = 0;
379  BasicBlock = false;
380  PrologueEnd = false;
381  EpilogueBegin = false;
382}
383
384void DWARFDebugLine::Row::reset(bool DefaultIsStmt) {
385  Address.Address = 0;
386  Address.SectionIndex = object::SectionedAddress::UndefSection;
387  Line = 1;
388  Column = 0;
389  File = 1;
390  Isa = 0;
391  Discriminator = 0;
392  IsStmt = DefaultIsStmt;
393  BasicBlock = false;
394  EndSequence = false;
395  PrologueEnd = false;
396  EpilogueBegin = false;
397}
398
399void DWARFDebugLine::Row::dumpTableHeader(raw_ostream &OS) {
400  OS << "Address            Line   Column File   ISA Discriminator Flags\n"
401     << "------------------ ------ ------ ------ --- ------------- "
402        "-------------\n";
403}
404
405void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
406  OS << format("0x%16.16" PRIx64 " %6u %6u", Address.Address, Line, Column)
407     << format(" %6u %3u %13u ", File, Isa, Discriminator)
408     << (IsStmt ? " is_stmt" : "") << (BasicBlock ? " basic_block" : "")
409     << (PrologueEnd ? " prologue_end" : "")
410     << (EpilogueBegin ? " epilogue_begin" : "")
411     << (EndSequence ? " end_sequence" : "") << '\n';
412}
413
414DWARFDebugLine::Sequence::Sequence() { reset(); }
415
416void DWARFDebugLine::Sequence::reset() {
417  LowPC = 0;
418  HighPC = 0;
419  SectionIndex = object::SectionedAddress::UndefSection;
420  FirstRowIndex = 0;
421  LastRowIndex = 0;
422  Empty = true;
423}
424
425DWARFDebugLine::LineTable::LineTable() { clear(); }
426
427void DWARFDebugLine::LineTable::dump(raw_ostream &OS,
428                                     DIDumpOptions DumpOptions) const {
429  Prologue.dump(OS, DumpOptions);
430
431  if (!Rows.empty()) {
432    OS << '\n';
433    Row::dumpTableHeader(OS);
434    for (const Row &R : Rows) {
435      R.dump(OS);
436    }
437  }
438
439  // Terminate the table with a final blank line to clearly delineate it from
440  // later dumps.
441  OS << '\n';
442}
443
444void DWARFDebugLine::LineTable::clear() {
445  Prologue.clear();
446  Rows.clear();
447  Sequences.clear();
448}
449
450DWARFDebugLine::ParsingState::ParsingState(struct LineTable *LT)
451    : LineTable(LT) {
452  resetRowAndSequence();
453}
454
455void DWARFDebugLine::ParsingState::resetRowAndSequence() {
456  Row.reset(LineTable->Prologue.DefaultIsStmt);
457  Sequence.reset();
458}
459
460void DWARFDebugLine::ParsingState::appendRowToMatrix() {
461  unsigned RowNumber = LineTable->Rows.size();
462  if (Sequence.Empty) {
463    // Record the beginning of instruction sequence.
464    Sequence.Empty = false;
465    Sequence.LowPC = Row.Address.Address;
466    Sequence.FirstRowIndex = RowNumber;
467  }
468  LineTable->appendRow(Row);
469  if (Row.EndSequence) {
470    // Record the end of instruction sequence.
471    Sequence.HighPC = Row.Address.Address;
472    Sequence.LastRowIndex = RowNumber + 1;
473    Sequence.SectionIndex = Row.Address.SectionIndex;
474    if (Sequence.isValid())
475      LineTable->appendSequence(Sequence);
476    Sequence.reset();
477  }
478  Row.postAppend();
479}
480
481const DWARFDebugLine::LineTable *
482DWARFDebugLine::getLineTable(uint64_t Offset) const {
483  LineTableConstIter Pos = LineTableMap.find(Offset);
484  if (Pos != LineTableMap.end())
485    return &Pos->second;
486  return nullptr;
487}
488
489Expected<const DWARFDebugLine::LineTable *> DWARFDebugLine::getOrParseLineTable(
490    DWARFDataExtractor &DebugLineData, uint64_t Offset, const DWARFContext &Ctx,
491    const DWARFUnit *U, function_ref<void(Error)> RecoverableErrorCallback) {
492  if (!DebugLineData.isValidOffset(Offset))
493    return createStringError(errc::invalid_argument, "offset 0x%8.8" PRIx64
494                       " is not a valid debug line section offset",
495                       Offset);
496
497  std::pair<LineTableIter, bool> Pos =
498      LineTableMap.insert(LineTableMapTy::value_type(Offset, LineTable()));
499  LineTable *LT = &Pos.first->second;
500  if (Pos.second) {
501    if (Error Err =
502            LT->parse(DebugLineData, &Offset, Ctx, U, RecoverableErrorCallback))
503      return std::move(Err);
504    return LT;
505  }
506  return LT;
507}
508
509Error DWARFDebugLine::LineTable::parse(
510    DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr,
511    const DWARFContext &Ctx, const DWARFUnit *U,
512    function_ref<void(Error)> RecoverableErrorCallback, raw_ostream *OS) {
513  const uint64_t DebugLineOffset = *OffsetPtr;
514
515  clear();
516
517  Error PrologueErr = Prologue.parse(DebugLineData, OffsetPtr, Ctx, U);
518
519  if (OS) {
520    // The presence of OS signals verbose dumping.
521    DIDumpOptions DumpOptions;
522    DumpOptions.Verbose = true;
523    Prologue.dump(*OS, DumpOptions);
524  }
525
526  if (PrologueErr)
527    return PrologueErr;
528
529  uint64_t ProgramLength = Prologue.TotalLength + Prologue.sizeofTotalLength();
530  if (!DebugLineData.isValidOffsetForDataOfSize(DebugLineOffset,
531                                                ProgramLength)) {
532    assert(DebugLineData.size() > DebugLineOffset &&
533           "prologue parsing should handle invalid offset");
534    uint64_t BytesRemaining = DebugLineData.size() - DebugLineOffset;
535    RecoverableErrorCallback(
536        createStringError(errc::invalid_argument,
537                          "line table program with offset 0x%8.8" PRIx64
538                          " has length 0x%8.8" PRIx64 " but only 0x%8.8" PRIx64
539                          " bytes are available",
540                          DebugLineOffset, ProgramLength, BytesRemaining));
541    // Continue by capping the length at the number of remaining bytes.
542    ProgramLength = BytesRemaining;
543  }
544
545  const uint64_t EndOffset = DebugLineOffset + ProgramLength;
546
547  // See if we should tell the data extractor the address size.
548  if (DebugLineData.getAddressSize() == 0)
549    DebugLineData.setAddressSize(Prologue.getAddressSize());
550  else
551    assert(Prologue.getAddressSize() == 0 ||
552           Prologue.getAddressSize() == DebugLineData.getAddressSize());
553
554  ParsingState State(this);
555
556  while (*OffsetPtr < EndOffset) {
557    if (OS)
558      *OS << format("0x%08.08" PRIx64 ": ", *OffsetPtr);
559
560    uint8_t Opcode = DebugLineData.getU8(OffsetPtr);
561
562    if (OS)
563      *OS << format("%02.02" PRIx8 " ", Opcode);
564
565    if (Opcode == 0) {
566      // Extended Opcodes always start with a zero opcode followed by
567      // a uleb128 length so you can skip ones you don't know about
568      uint64_t Len = DebugLineData.getULEB128(OffsetPtr);
569      uint64_t ExtOffset = *OffsetPtr;
570
571      // Tolerate zero-length; assume length is correct and soldier on.
572      if (Len == 0) {
573        if (OS)
574          *OS << "Badly formed extended line op (length 0)\n";
575        continue;
576      }
577
578      uint8_t SubOpcode = DebugLineData.getU8(OffsetPtr);
579      if (OS)
580        *OS << LNExtendedString(SubOpcode);
581      switch (SubOpcode) {
582      case DW_LNE_end_sequence:
583        // Set the end_sequence register of the state machine to true and
584        // append a row to the matrix using the current values of the
585        // state-machine registers. Then reset the registers to the initial
586        // values specified above. Every statement program sequence must end
587        // with a DW_LNE_end_sequence instruction which creates a row whose
588        // address is that of the byte after the last target machine instruction
589        // of the sequence.
590        State.Row.EndSequence = true;
591        if (OS) {
592          *OS << "\n";
593          OS->indent(12);
594          State.Row.dump(*OS);
595        }
596        State.appendRowToMatrix();
597        State.resetRowAndSequence();
598        break;
599
600      case DW_LNE_set_address:
601        // Takes a single relocatable address as an operand. The size of the
602        // operand is the size appropriate to hold an address on the target
603        // machine. Set the address register to the value given by the
604        // relocatable address. All of the other statement program opcodes
605        // that affect the address register add a delta to it. This instruction
606        // stores a relocatable value into it instead.
607        //
608        // Make sure the extractor knows the address size.  If not, infer it
609        // from the size of the operand.
610        {
611          uint8_t ExtractorAddressSize = DebugLineData.getAddressSize();
612          if (ExtractorAddressSize != Len - 1 && ExtractorAddressSize != 0)
613            RecoverableErrorCallback(createStringError(
614                errc::invalid_argument,
615                "mismatching address size at offset 0x%8.8" PRIx64
616                " expected 0x%2.2" PRIx8 " found 0x%2.2" PRIx64,
617                ExtOffset, ExtractorAddressSize, Len - 1));
618
619          // Assume that the line table is correct and temporarily override the
620          // address size.
621          DebugLineData.setAddressSize(Len - 1);
622          State.Row.Address.Address = DebugLineData.getRelocatedAddress(
623              OffsetPtr, &State.Row.Address.SectionIndex);
624
625          // Restore the address size if the extractor already had it.
626          if (ExtractorAddressSize != 0)
627            DebugLineData.setAddressSize(ExtractorAddressSize);
628
629          if (OS)
630            *OS << format(" (0x%16.16" PRIx64 ")", State.Row.Address.Address);
631        }
632        break;
633
634      case DW_LNE_define_file:
635        // Takes 4 arguments. The first is a null terminated string containing
636        // a source file name. The second is an unsigned LEB128 number
637        // representing the directory index of the directory in which the file
638        // was found. The third is an unsigned LEB128 number representing the
639        // time of last modification of the file. The fourth is an unsigned
640        // LEB128 number representing the length in bytes of the file. The time
641        // and length fields may contain LEB128(0) if the information is not
642        // available.
643        //
644        // The directory index represents an entry in the include_directories
645        // section of the statement program prologue. The index is LEB128(0)
646        // if the file was found in the current directory of the compilation,
647        // LEB128(1) if it was found in the first directory in the
648        // include_directories section, and so on. The directory index is
649        // ignored for file names that represent full path names.
650        //
651        // The files are numbered, starting at 1, in the order in which they
652        // appear; the names in the prologue come before names defined by
653        // the DW_LNE_define_file instruction. These numbers are used in the
654        // the file register of the state machine.
655        {
656          FileNameEntry FileEntry;
657          const char *Name = DebugLineData.getCStr(OffsetPtr);
658          FileEntry.Name =
659              DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, Name);
660          FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr);
661          FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr);
662          FileEntry.Length = DebugLineData.getULEB128(OffsetPtr);
663          Prologue.FileNames.push_back(FileEntry);
664          if (OS)
665            *OS << " (" << Name << ", dir=" << FileEntry.DirIdx << ", mod_time="
666                << format("(0x%16.16" PRIx64 ")", FileEntry.ModTime)
667                << ", length=" << FileEntry.Length << ")";
668        }
669        break;
670
671      case DW_LNE_set_discriminator:
672        State.Row.Discriminator = DebugLineData.getULEB128(OffsetPtr);
673        if (OS)
674          *OS << " (" << State.Row.Discriminator << ")";
675        break;
676
677      default:
678        if (OS)
679          *OS << format("Unrecognized extended op 0x%02.02" PRIx8, SubOpcode)
680              << format(" length %" PRIx64, Len);
681        // Len doesn't include the zero opcode byte or the length itself, but
682        // it does include the sub_opcode, so we have to adjust for that.
683        (*OffsetPtr) += Len - 1;
684        break;
685      }
686      // Make sure the stated and parsed lengths are the same.
687      // Otherwise we have an unparseable line-number program.
688      if (*OffsetPtr - ExtOffset != Len)
689        return createStringError(errc::illegal_byte_sequence,
690                           "unexpected line op length at offset 0x%8.8" PRIx64
691                           " expected 0x%2.2" PRIx64 " found 0x%2.2" PRIx64,
692                           ExtOffset, Len, *OffsetPtr - ExtOffset);
693    } else if (Opcode < Prologue.OpcodeBase) {
694      if (OS)
695        *OS << LNStandardString(Opcode);
696      switch (Opcode) {
697      // Standard Opcodes
698      case DW_LNS_copy:
699        // Takes no arguments. Append a row to the matrix using the
700        // current values of the state-machine registers.
701        if (OS) {
702          *OS << "\n";
703          OS->indent(12);
704          State.Row.dump(*OS);
705          *OS << "\n";
706        }
707        State.appendRowToMatrix();
708        break;
709
710      case DW_LNS_advance_pc:
711        // Takes a single unsigned LEB128 operand, multiplies it by the
712        // min_inst_length field of the prologue, and adds the
713        // result to the address register of the state machine.
714        {
715          uint64_t AddrOffset =
716              DebugLineData.getULEB128(OffsetPtr) * Prologue.MinInstLength;
717          State.Row.Address.Address += AddrOffset;
718          if (OS)
719            *OS << " (" << AddrOffset << ")";
720        }
721        break;
722
723      case DW_LNS_advance_line:
724        // Takes a single signed LEB128 operand and adds that value to
725        // the line register of the state machine.
726        State.Row.Line += DebugLineData.getSLEB128(OffsetPtr);
727        if (OS)
728          *OS << " (" << State.Row.Line << ")";
729        break;
730
731      case DW_LNS_set_file:
732        // Takes a single unsigned LEB128 operand and stores it in the file
733        // register of the state machine.
734        State.Row.File = DebugLineData.getULEB128(OffsetPtr);
735        if (OS)
736          *OS << " (" << State.Row.File << ")";
737        break;
738
739      case DW_LNS_set_column:
740        // Takes a single unsigned LEB128 operand and stores it in the
741        // column register of the state machine.
742        State.Row.Column = DebugLineData.getULEB128(OffsetPtr);
743        if (OS)
744          *OS << " (" << State.Row.Column << ")";
745        break;
746
747      case DW_LNS_negate_stmt:
748        // Takes no arguments. Set the is_stmt register of the state
749        // machine to the logical negation of its current value.
750        State.Row.IsStmt = !State.Row.IsStmt;
751        break;
752
753      case DW_LNS_set_basic_block:
754        // Takes no arguments. Set the basic_block register of the
755        // state machine to true
756        State.Row.BasicBlock = true;
757        break;
758
759      case DW_LNS_const_add_pc:
760        // Takes no arguments. Add to the address register of the state
761        // machine the address increment value corresponding to special
762        // opcode 255. The motivation for DW_LNS_const_add_pc is this:
763        // when the statement program needs to advance the address by a
764        // small amount, it can use a single special opcode, which occupies
765        // a single byte. When it needs to advance the address by up to
766        // twice the range of the last special opcode, it can use
767        // DW_LNS_const_add_pc followed by a special opcode, for a total
768        // of two bytes. Only if it needs to advance the address by more
769        // than twice that range will it need to use both DW_LNS_advance_pc
770        // and a special opcode, requiring three or more bytes.
771        {
772          uint8_t AdjustOpcode = 255 - Prologue.OpcodeBase;
773          uint64_t AddrOffset =
774              (AdjustOpcode / Prologue.LineRange) * Prologue.MinInstLength;
775          State.Row.Address.Address += AddrOffset;
776          if (OS)
777            *OS
778                << format(" (0x%16.16" PRIx64 ")", AddrOffset);
779        }
780        break;
781
782      case DW_LNS_fixed_advance_pc:
783        // Takes a single uhalf operand. Add to the address register of
784        // the state machine the value of the (unencoded) operand. This
785        // is the only extended opcode that takes an argument that is not
786        // a variable length number. The motivation for DW_LNS_fixed_advance_pc
787        // is this: existing assemblers cannot emit DW_LNS_advance_pc or
788        // special opcodes because they cannot encode LEB128 numbers or
789        // judge when the computation of a special opcode overflows and
790        // requires the use of DW_LNS_advance_pc. Such assemblers, however,
791        // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
792        {
793          uint16_t PCOffset = DebugLineData.getRelocatedValue(2, OffsetPtr);
794          State.Row.Address.Address += PCOffset;
795          if (OS)
796            *OS
797                << format(" (0x%4.4" PRIx16 ")", PCOffset);
798        }
799        break;
800
801      case DW_LNS_set_prologue_end:
802        // Takes no arguments. Set the prologue_end register of the
803        // state machine to true
804        State.Row.PrologueEnd = true;
805        break;
806
807      case DW_LNS_set_epilogue_begin:
808        // Takes no arguments. Set the basic_block register of the
809        // state machine to true
810        State.Row.EpilogueBegin = true;
811        break;
812
813      case DW_LNS_set_isa:
814        // Takes a single unsigned LEB128 operand and stores it in the
815        // column register of the state machine.
816        State.Row.Isa = DebugLineData.getULEB128(OffsetPtr);
817        if (OS)
818          *OS << " (" << (uint64_t)State.Row.Isa << ")";
819        break;
820
821      default:
822        // Handle any unknown standard opcodes here. We know the lengths
823        // of such opcodes because they are specified in the prologue
824        // as a multiple of LEB128 operands for each opcode.
825        {
826          assert(Opcode - 1U < Prologue.StandardOpcodeLengths.size());
827          uint8_t OpcodeLength = Prologue.StandardOpcodeLengths[Opcode - 1];
828          for (uint8_t I = 0; I < OpcodeLength; ++I) {
829            uint64_t Value = DebugLineData.getULEB128(OffsetPtr);
830            if (OS)
831              *OS << format("Skipping ULEB128 value: 0x%16.16" PRIx64 ")\n",
832                            Value);
833          }
834        }
835        break;
836      }
837    } else {
838      // Special Opcodes
839
840      // A special opcode value is chosen based on the amount that needs
841      // to be added to the line and address registers. The maximum line
842      // increment for a special opcode is the value of the line_base
843      // field in the header, plus the value of the line_range field,
844      // minus 1 (line base + line range - 1). If the desired line
845      // increment is greater than the maximum line increment, a standard
846      // opcode must be used instead of a special opcode. The "address
847      // advance" is calculated by dividing the desired address increment
848      // by the minimum_instruction_length field from the header. The
849      // special opcode is then calculated using the following formula:
850      //
851      //  opcode = (desired line increment - line_base) +
852      //           (line_range * address advance) + opcode_base
853      //
854      // If the resulting opcode is greater than 255, a standard opcode
855      // must be used instead.
856      //
857      // To decode a special opcode, subtract the opcode_base from the
858      // opcode itself to give the adjusted opcode. The amount to
859      // increment the address register is the result of the adjusted
860      // opcode divided by the line_range multiplied by the
861      // minimum_instruction_length field from the header. That is:
862      //
863      //  address increment = (adjusted opcode / line_range) *
864      //                      minimum_instruction_length
865      //
866      // The amount to increment the line register is the line_base plus
867      // the result of the adjusted opcode modulo the line_range. That is:
868      //
869      // line increment = line_base + (adjusted opcode % line_range)
870
871      uint8_t AdjustOpcode = Opcode - Prologue.OpcodeBase;
872      uint64_t AddrOffset =
873          (AdjustOpcode / Prologue.LineRange) * Prologue.MinInstLength;
874      int32_t LineOffset =
875          Prologue.LineBase + (AdjustOpcode % Prologue.LineRange);
876      State.Row.Line += LineOffset;
877      State.Row.Address.Address += AddrOffset;
878
879      if (OS) {
880        *OS << "address += " << AddrOffset << ",  line += " << LineOffset
881            << "\n";
882        OS->indent(12);
883        State.Row.dump(*OS);
884      }
885
886      State.appendRowToMatrix();
887    }
888    if(OS)
889      *OS << "\n";
890  }
891
892  if (!State.Sequence.Empty)
893    RecoverableErrorCallback(createStringError(
894        errc::illegal_byte_sequence,
895        "last sequence in debug line table at offset 0x%8.8" PRIx64
896        " is not terminated",
897        DebugLineOffset));
898
899  // Sort all sequences so that address lookup will work faster.
900  if (!Sequences.empty()) {
901    llvm::sort(Sequences, Sequence::orderByHighPC);
902    // Note: actually, instruction address ranges of sequences should not
903    // overlap (in shared objects and executables). If they do, the address
904    // lookup would still work, though, but result would be ambiguous.
905    // We don't report warning in this case. For example,
906    // sometimes .so compiled from multiple object files contains a few
907    // rudimentary sequences for address ranges [0x0, 0xsomething).
908  }
909
910  return Error::success();
911}
912
913uint32_t DWARFDebugLine::LineTable::findRowInSeq(
914    const DWARFDebugLine::Sequence &Seq,
915    object::SectionedAddress Address) const {
916  if (!Seq.containsPC(Address))
917    return UnknownRowIndex;
918  assert(Seq.SectionIndex == Address.SectionIndex);
919  // In some cases, e.g. first instruction in a function, the compiler generates
920  // two entries, both with the same address. We want the last one.
921  //
922  // In general we want a non-empty range: the last row whose address is less
923  // than or equal to Address. This can be computed as upper_bound - 1.
924  DWARFDebugLine::Row Row;
925  Row.Address = Address;
926  RowIter FirstRow = Rows.begin() + Seq.FirstRowIndex;
927  RowIter LastRow = Rows.begin() + Seq.LastRowIndex;
928  assert(FirstRow->Address.Address <= Row.Address.Address &&
929         Row.Address.Address < LastRow[-1].Address.Address);
930  RowIter RowPos = std::upper_bound(FirstRow + 1, LastRow - 1, Row,
931                                    DWARFDebugLine::Row::orderByAddress) -
932                   1;
933  assert(Seq.SectionIndex == RowPos->Address.SectionIndex);
934  return RowPos - Rows.begin();
935}
936
937uint32_t DWARFDebugLine::LineTable::lookupAddress(
938    object::SectionedAddress Address) const {
939
940  // Search for relocatable addresses
941  uint32_t Result = lookupAddressImpl(Address);
942
943  if (Result != UnknownRowIndex ||
944      Address.SectionIndex == object::SectionedAddress::UndefSection)
945    return Result;
946
947  // Search for absolute addresses
948  Address.SectionIndex = object::SectionedAddress::UndefSection;
949  return lookupAddressImpl(Address);
950}
951
952uint32_t DWARFDebugLine::LineTable::lookupAddressImpl(
953    object::SectionedAddress Address) const {
954  // First, find an instruction sequence containing the given address.
955  DWARFDebugLine::Sequence Sequence;
956  Sequence.SectionIndex = Address.SectionIndex;
957  Sequence.HighPC = Address.Address;
958  SequenceIter It = llvm::upper_bound(Sequences, Sequence,
959                                      DWARFDebugLine::Sequence::orderByHighPC);
960  if (It == Sequences.end() || It->SectionIndex != Address.SectionIndex)
961    return UnknownRowIndex;
962  return findRowInSeq(*It, Address);
963}
964
965bool DWARFDebugLine::LineTable::lookupAddressRange(
966    object::SectionedAddress Address, uint64_t Size,
967    std::vector<uint32_t> &Result) const {
968
969  // Search for relocatable addresses
970  if (lookupAddressRangeImpl(Address, Size, Result))
971    return true;
972
973  if (Address.SectionIndex == object::SectionedAddress::UndefSection)
974    return false;
975
976  // Search for absolute addresses
977  Address.SectionIndex = object::SectionedAddress::UndefSection;
978  return lookupAddressRangeImpl(Address, Size, Result);
979}
980
981bool DWARFDebugLine::LineTable::lookupAddressRangeImpl(
982    object::SectionedAddress Address, uint64_t Size,
983    std::vector<uint32_t> &Result) const {
984  if (Sequences.empty())
985    return false;
986  uint64_t EndAddr = Address.Address + Size;
987  // First, find an instruction sequence containing the given address.
988  DWARFDebugLine::Sequence Sequence;
989  Sequence.SectionIndex = Address.SectionIndex;
990  Sequence.HighPC = Address.Address;
991  SequenceIter LastSeq = Sequences.end();
992  SequenceIter SeqPos = llvm::upper_bound(
993      Sequences, Sequence, DWARFDebugLine::Sequence::orderByHighPC);
994  if (SeqPos == LastSeq || !SeqPos->containsPC(Address))
995    return false;
996
997  SequenceIter StartPos = SeqPos;
998
999  // Add the rows from the first sequence to the vector, starting with the
1000  // index we just calculated
1001
1002  while (SeqPos != LastSeq && SeqPos->LowPC < EndAddr) {
1003    const DWARFDebugLine::Sequence &CurSeq = *SeqPos;
1004    // For the first sequence, we need to find which row in the sequence is the
1005    // first in our range.
1006    uint32_t FirstRowIndex = CurSeq.FirstRowIndex;
1007    if (SeqPos == StartPos)
1008      FirstRowIndex = findRowInSeq(CurSeq, Address);
1009
1010    // Figure out the last row in the range.
1011    uint32_t LastRowIndex =
1012        findRowInSeq(CurSeq, {EndAddr - 1, Address.SectionIndex});
1013    if (LastRowIndex == UnknownRowIndex)
1014      LastRowIndex = CurSeq.LastRowIndex - 1;
1015
1016    assert(FirstRowIndex != UnknownRowIndex);
1017    assert(LastRowIndex != UnknownRowIndex);
1018
1019    for (uint32_t I = FirstRowIndex; I <= LastRowIndex; ++I) {
1020      Result.push_back(I);
1021    }
1022
1023    ++SeqPos;
1024  }
1025
1026  return true;
1027}
1028
1029Optional<StringRef> DWARFDebugLine::LineTable::getSourceByIndex(uint64_t FileIndex,
1030                                                                FileLineInfoKind Kind) const {
1031  if (Kind == FileLineInfoKind::None || !Prologue.hasFileAtIndex(FileIndex))
1032    return None;
1033  const FileNameEntry &Entry = Prologue.getFileNameEntry(FileIndex);
1034  if (Optional<const char *> source = Entry.Source.getAsCString())
1035    return StringRef(*source);
1036  return None;
1037}
1038
1039static bool isPathAbsoluteOnWindowsOrPosix(const Twine &Path) {
1040  // Debug info can contain paths from any OS, not necessarily
1041  // an OS we're currently running on. Moreover different compilation units can
1042  // be compiled on different operating systems and linked together later.
1043  return sys::path::is_absolute(Path, sys::path::Style::posix) ||
1044         sys::path::is_absolute(Path, sys::path::Style::windows);
1045}
1046
1047bool DWARFDebugLine::Prologue::getFileNameByIndex(
1048    uint64_t FileIndex, StringRef CompDir, FileLineInfoKind Kind,
1049    std::string &Result, sys::path::Style Style) const {
1050  if (Kind == FileLineInfoKind::None || !hasFileAtIndex(FileIndex))
1051    return false;
1052  const FileNameEntry &Entry = getFileNameEntry(FileIndex);
1053  Optional<const char *> Name = Entry.Name.getAsCString();
1054  if (!Name)
1055    return false;
1056  StringRef FileName = *Name;
1057  if (Kind != FileLineInfoKind::AbsoluteFilePath ||
1058      isPathAbsoluteOnWindowsOrPosix(FileName)) {
1059    Result = FileName;
1060    return true;
1061  }
1062
1063  SmallString<16> FilePath;
1064  StringRef IncludeDir;
1065  // Be defensive about the contents of Entry.
1066  if (getVersion() >= 5) {
1067    if (Entry.DirIdx < IncludeDirectories.size())
1068      IncludeDir = IncludeDirectories[Entry.DirIdx].getAsCString().getValue();
1069  } else {
1070    if (0 < Entry.DirIdx && Entry.DirIdx <= IncludeDirectories.size())
1071      IncludeDir =
1072          IncludeDirectories[Entry.DirIdx - 1].getAsCString().getValue();
1073
1074    // We may still need to append compilation directory of compile unit.
1075    // We know that FileName is not absolute, the only way to have an
1076    // absolute path at this point would be if IncludeDir is absolute.
1077    if (!CompDir.empty() && !isPathAbsoluteOnWindowsOrPosix(IncludeDir))
1078      sys::path::append(FilePath, Style, CompDir);
1079  }
1080
1081  // sys::path::append skips empty strings.
1082  sys::path::append(FilePath, Style, IncludeDir, FileName);
1083  Result = FilePath.str();
1084  return true;
1085}
1086
1087bool DWARFDebugLine::LineTable::getFileLineInfoForAddress(
1088    object::SectionedAddress Address, const char *CompDir,
1089    FileLineInfoKind Kind, DILineInfo &Result) const {
1090  // Get the index of row we're looking for in the line table.
1091  uint32_t RowIndex = lookupAddress(Address);
1092  if (RowIndex == -1U)
1093    return false;
1094  // Take file number and line/column from the row.
1095  const auto &Row = Rows[RowIndex];
1096  if (!getFileNameByIndex(Row.File, CompDir, Kind, Result.FileName))
1097    return false;
1098  Result.Line = Row.Line;
1099  Result.Column = Row.Column;
1100  Result.Discriminator = Row.Discriminator;
1101  Result.Source = getSourceByIndex(Row.File, Kind);
1102  return true;
1103}
1104
1105// We want to supply the Unit associated with a .debug_line[.dwo] table when
1106// we dump it, if possible, but still dump the table even if there isn't a Unit.
1107// Therefore, collect up handles on all the Units that point into the
1108// line-table section.
1109static DWARFDebugLine::SectionParser::LineToUnitMap
1110buildLineToUnitMap(DWARFDebugLine::SectionParser::cu_range CUs,
1111                   DWARFDebugLine::SectionParser::tu_range TUs) {
1112  DWARFDebugLine::SectionParser::LineToUnitMap LineToUnit;
1113  for (const auto &CU : CUs)
1114    if (auto CUDIE = CU->getUnitDIE())
1115      if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list)))
1116        LineToUnit.insert(std::make_pair(*StmtOffset, &*CU));
1117  for (const auto &TU : TUs)
1118    if (auto TUDIE = TU->getUnitDIE())
1119      if (auto StmtOffset = toSectionOffset(TUDIE.find(DW_AT_stmt_list)))
1120        LineToUnit.insert(std::make_pair(*StmtOffset, &*TU));
1121  return LineToUnit;
1122}
1123
1124DWARFDebugLine::SectionParser::SectionParser(DWARFDataExtractor &Data,
1125                                             const DWARFContext &C,
1126                                             cu_range CUs, tu_range TUs)
1127    : DebugLineData(Data), Context(C) {
1128  LineToUnit = buildLineToUnitMap(CUs, TUs);
1129  if (!DebugLineData.isValidOffset(Offset))
1130    Done = true;
1131}
1132
1133bool DWARFDebugLine::Prologue::totalLengthIsValid() const {
1134  return TotalLength == dwarf::DW_LENGTH_DWARF64 ||
1135         TotalLength < dwarf::DW_LENGTH_lo_reserved;
1136}
1137
1138DWARFDebugLine::LineTable DWARFDebugLine::SectionParser::parseNext(
1139    function_ref<void(Error)> RecoverableErrorCallback,
1140    function_ref<void(Error)> UnrecoverableErrorCallback, raw_ostream *OS) {
1141  assert(DebugLineData.isValidOffset(Offset) &&
1142         "parsing should have terminated");
1143  DWARFUnit *U = prepareToParse(Offset);
1144  uint64_t OldOffset = Offset;
1145  LineTable LT;
1146  if (Error Err = LT.parse(DebugLineData, &Offset, Context, U,
1147                           RecoverableErrorCallback, OS))
1148    UnrecoverableErrorCallback(std::move(Err));
1149  moveToNextTable(OldOffset, LT.Prologue);
1150  return LT;
1151}
1152
1153void DWARFDebugLine::SectionParser::skip(
1154    function_ref<void(Error)> ErrorCallback) {
1155  assert(DebugLineData.isValidOffset(Offset) &&
1156         "parsing should have terminated");
1157  DWARFUnit *U = prepareToParse(Offset);
1158  uint64_t OldOffset = Offset;
1159  LineTable LT;
1160  if (Error Err = LT.Prologue.parse(DebugLineData, &Offset, Context, U))
1161    ErrorCallback(std::move(Err));
1162  moveToNextTable(OldOffset, LT.Prologue);
1163}
1164
1165DWARFUnit *DWARFDebugLine::SectionParser::prepareToParse(uint64_t Offset) {
1166  DWARFUnit *U = nullptr;
1167  auto It = LineToUnit.find(Offset);
1168  if (It != LineToUnit.end())
1169    U = It->second;
1170  DebugLineData.setAddressSize(U ? U->getAddressByteSize() : 0);
1171  return U;
1172}
1173
1174void DWARFDebugLine::SectionParser::moveToNextTable(uint64_t OldOffset,
1175                                                    const Prologue &P) {
1176  // If the length field is not valid, we don't know where the next table is, so
1177  // cannot continue to parse. Mark the parser as done, and leave the Offset
1178  // value as it currently is. This will be the end of the bad length field.
1179  if (!P.totalLengthIsValid()) {
1180    Done = true;
1181    return;
1182  }
1183
1184  Offset = OldOffset + P.TotalLength + P.sizeofTotalLength();
1185  if (!DebugLineData.isValidOffset(Offset)) {
1186    Done = true;
1187  }
1188}
1189