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 
28 using namespace llvm;
29 using namespace dwarf;
30 
31 using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
32 
33 namespace {
34 
35 struct ContentDescriptor {
36   dwarf::LineNumberEntryFormat Type;
37   dwarf::Form Form;
38 };
39 
40 using ContentDescriptors = SmallVector<ContentDescriptor, 4>;
41 
42 } // end anonmyous namespace
43 
44 void 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 
66 DWARFDebugLine::Prologue::Prologue() { clear(); }
67 
68 bool 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 
77 const llvm::DWARFDebugLine::FileNameEntry &
78 DWARFDebugLine::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 
88 void 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 
100 void 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.
156 static void
157 parseV2DirFileTables(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.
191 static llvm::Expected<ContentDescriptors>
192 parseV5EntryFormat(const DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr,
193                    uint64_t EndPrologueOffset,
194                    DWARFDebugLine::ContentTypeTracker *ContentTypes) {
195   ContentDescriptors Descriptors;
196   int FormatCount = DebugLineData.getU8(OffsetPtr);
197   bool HasPath = false;
198   for (int I = 0; I != FormatCount; ++I) {
199     if (*OffsetPtr >= EndPrologueOffset)
200       return createStringError(
201           errc::invalid_argument,
202           "failed to parse entry content descriptions at offset "
203           "0x%8.8" PRIx64
204           " because offset extends beyond the prologue end at offset "
205           "0x%8.8" PRIx64,
206           *OffsetPtr, EndPrologueOffset);
207     ContentDescriptor Descriptor;
208     Descriptor.Type =
209       dwarf::LineNumberEntryFormat(DebugLineData.getULEB128(OffsetPtr));
210     Descriptor.Form = dwarf::Form(DebugLineData.getULEB128(OffsetPtr));
211     if (Descriptor.Type == dwarf::DW_LNCT_path)
212       HasPath = true;
213     if (ContentTypes)
214       ContentTypes->trackContentType(Descriptor.Type);
215     Descriptors.push_back(Descriptor);
216   }
217 
218   if (!HasPath)
219     return createStringError(errc::invalid_argument,
220                              "failed to parse entry content descriptions"
221                              " because no path was found");
222   return Descriptors;
223 }
224 
225 static Error
226 parseV5DirFileTables(const DWARFDataExtractor &DebugLineData,
227                      uint64_t *OffsetPtr, uint64_t EndPrologueOffset,
228                      const dwarf::FormParams &FormParams,
229                      const DWARFContext &Ctx, const DWARFUnit *U,
230                      DWARFDebugLine::ContentTypeTracker &ContentTypes,
231                      std::vector<DWARFFormValue> &IncludeDirectories,
232                      std::vector<DWARFDebugLine::FileNameEntry> &FileNames) {
233   // Get the directory entry description.
234   llvm::Expected<ContentDescriptors> DirDescriptors =
235       parseV5EntryFormat(DebugLineData, OffsetPtr, EndPrologueOffset, nullptr);
236   if (!DirDescriptors)
237     return DirDescriptors.takeError();
238 
239   // Get the directory entries, according to the format described above.
240   int DirEntryCount = DebugLineData.getU8(OffsetPtr);
241   for (int I = 0; I != DirEntryCount; ++I) {
242     if (*OffsetPtr >= EndPrologueOffset)
243       return createStringError(
244           errc::invalid_argument,
245           "failed to parse directory entry at offset "
246           "0x%8.8" PRIx64
247           " because offset extends beyond the prologue end at offset "
248           "0x%8.8" PRIx64,
249           *OffsetPtr, EndPrologueOffset);
250     for (auto Descriptor : *DirDescriptors) {
251       DWARFFormValue Value(Descriptor.Form);
252       switch (Descriptor.Type) {
253       case DW_LNCT_path:
254         if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U))
255           return createStringError(errc::invalid_argument,
256                                    "failed to parse directory entry because "
257                                    "extracting the form value failed.");
258         IncludeDirectories.push_back(Value);
259         break;
260       default:
261         if (!Value.skipValue(DebugLineData, OffsetPtr, FormParams))
262           return createStringError(errc::invalid_argument,
263                                    "failed to parse directory entry because "
264                                    "skipping the form value failed.");
265       }
266     }
267   }
268 
269   // Get the file entry description.
270   llvm::Expected<ContentDescriptors> FileDescriptors = parseV5EntryFormat(
271       DebugLineData, OffsetPtr, EndPrologueOffset, &ContentTypes);
272   if (!FileDescriptors)
273     return FileDescriptors.takeError();
274 
275   // Get the file entries, according to the format described above.
276   int FileEntryCount = DebugLineData.getU8(OffsetPtr);
277   for (int I = 0; I != FileEntryCount; ++I) {
278     if (*OffsetPtr >= EndPrologueOffset)
279       return createStringError(
280           errc::invalid_argument,
281           "failed to parse file entry at offset "
282           "0x%8.8" PRIx64
283           " because offset extends beyond the prologue end at offset "
284           "0x%8.8" PRIx64,
285           *OffsetPtr, EndPrologueOffset);
286     DWARFDebugLine::FileNameEntry FileEntry;
287     for (auto Descriptor : *FileDescriptors) {
288       DWARFFormValue Value(Descriptor.Form);
289       if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U))
290         return createStringError(errc::invalid_argument,
291                                  "failed to parse file entry because "
292                                  "extracting the form value failed.");
293       switch (Descriptor.Type) {
294       case DW_LNCT_path:
295         FileEntry.Name = Value;
296         break;
297       case DW_LNCT_LLVM_source:
298         FileEntry.Source = Value;
299         break;
300       case DW_LNCT_directory_index:
301         FileEntry.DirIdx = Value.getAsUnsignedConstant().getValue();
302         break;
303       case DW_LNCT_timestamp:
304         FileEntry.ModTime = Value.getAsUnsignedConstant().getValue();
305         break;
306       case DW_LNCT_size:
307         FileEntry.Length = Value.getAsUnsignedConstant().getValue();
308         break;
309       case DW_LNCT_MD5:
310         if (!Value.getAsBlock() || Value.getAsBlock().getValue().size() != 16)
311           return createStringError(
312               errc::invalid_argument,
313               "failed to parse file entry because the MD5 hash is invalid");
314         std::uninitialized_copy_n(Value.getAsBlock().getValue().begin(), 16,
315                                   FileEntry.Checksum.Bytes.begin());
316         break;
317       default:
318         break;
319       }
320     }
321     FileNames.push_back(FileEntry);
322   }
323   return Error::success();
324 }
325 
326 Error DWARFDebugLine::Prologue::parse(const DWARFDataExtractor &DebugLineData,
327                                       uint64_t *OffsetPtr,
328                                       const DWARFContext &Ctx,
329                                       const DWARFUnit *U) {
330   const uint64_t PrologueOffset = *OffsetPtr;
331 
332   clear();
333   TotalLength = DebugLineData.getRelocatedValue(4, OffsetPtr);
334   if (TotalLength == dwarf::DW_LENGTH_DWARF64) {
335     FormParams.Format = dwarf::DWARF64;
336     TotalLength = DebugLineData.getU64(OffsetPtr);
337   } else if (TotalLength >= dwarf::DW_LENGTH_lo_reserved) {
338     return createStringError(errc::invalid_argument,
339         "parsing line table prologue at offset 0x%8.8" PRIx64
340         " unsupported reserved unit length found of value 0x%8.8" PRIx64,
341         PrologueOffset, TotalLength);
342   }
343   FormParams.Version = DebugLineData.getU16(OffsetPtr);
344   if (getVersion() < 2)
345     return createStringError(errc::not_supported,
346                        "parsing line table prologue at offset 0x%8.8" PRIx64
347                        " found unsupported version 0x%2.2" PRIx16,
348                        PrologueOffset, getVersion());
349 
350   if (getVersion() >= 5) {
351     FormParams.AddrSize = DebugLineData.getU8(OffsetPtr);
352     assert((DebugLineData.getAddressSize() == 0 ||
353             DebugLineData.getAddressSize() == getAddressSize()) &&
354            "Line table header and data extractor disagree");
355     SegSelectorSize = DebugLineData.getU8(OffsetPtr);
356   }
357 
358   PrologueLength =
359       DebugLineData.getRelocatedValue(sizeofPrologueLength(), OffsetPtr);
360   const uint64_t EndPrologueOffset = PrologueLength + *OffsetPtr;
361   MinInstLength = DebugLineData.getU8(OffsetPtr);
362   if (getVersion() >= 4)
363     MaxOpsPerInst = DebugLineData.getU8(OffsetPtr);
364   DefaultIsStmt = DebugLineData.getU8(OffsetPtr);
365   LineBase = DebugLineData.getU8(OffsetPtr);
366   LineRange = DebugLineData.getU8(OffsetPtr);
367   OpcodeBase = DebugLineData.getU8(OffsetPtr);
368 
369   StandardOpcodeLengths.reserve(OpcodeBase - 1);
370   for (uint32_t I = 1; I < OpcodeBase; ++I) {
371     uint8_t OpLen = DebugLineData.getU8(OffsetPtr);
372     StandardOpcodeLengths.push_back(OpLen);
373   }
374 
375   if (getVersion() >= 5) {
376     if (Error e = parseV5DirFileTables(
377             DebugLineData, OffsetPtr, EndPrologueOffset, FormParams, Ctx, U,
378             ContentTypes, IncludeDirectories, FileNames)) {
379       return joinErrors(
380           createStringError(
381               errc::invalid_argument,
382               "parsing line table prologue at 0x%8.8" PRIx64
383               " found an invalid directory or file table description at"
384               " 0x%8.8" PRIx64,
385               PrologueOffset, *OffsetPtr),
386           std::move(e));
387     }
388   } else
389     parseV2DirFileTables(DebugLineData, OffsetPtr, EndPrologueOffset,
390                          ContentTypes, IncludeDirectories, FileNames);
391 
392   if (*OffsetPtr != EndPrologueOffset)
393     return createStringError(errc::invalid_argument,
394                        "parsing line table prologue at 0x%8.8" PRIx64
395                        " should have ended at 0x%8.8" PRIx64
396                        " but it ended at 0x%8.8" PRIx64,
397                        PrologueOffset, EndPrologueOffset, *OffsetPtr);
398   return Error::success();
399 }
400 
401 DWARFDebugLine::Row::Row(bool DefaultIsStmt) { reset(DefaultIsStmt); }
402 
403 void DWARFDebugLine::Row::postAppend() {
404   Discriminator = 0;
405   BasicBlock = false;
406   PrologueEnd = false;
407   EpilogueBegin = false;
408 }
409 
410 void DWARFDebugLine::Row::reset(bool DefaultIsStmt) {
411   Address.Address = 0;
412   Address.SectionIndex = object::SectionedAddress::UndefSection;
413   Line = 1;
414   Column = 0;
415   File = 1;
416   Isa = 0;
417   Discriminator = 0;
418   IsStmt = DefaultIsStmt;
419   BasicBlock = false;
420   EndSequence = false;
421   PrologueEnd = false;
422   EpilogueBegin = false;
423 }
424 
425 void DWARFDebugLine::Row::dumpTableHeader(raw_ostream &OS) {
426   OS << "Address            Line   Column File   ISA Discriminator Flags\n"
427      << "------------------ ------ ------ ------ --- ------------- "
428         "-------------\n";
429 }
430 
431 void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
432   OS << format("0x%16.16" PRIx64 " %6u %6u", Address.Address, Line, Column)
433      << format(" %6u %3u %13u ", File, Isa, Discriminator)
434      << (IsStmt ? " is_stmt" : "") << (BasicBlock ? " basic_block" : "")
435      << (PrologueEnd ? " prologue_end" : "")
436      << (EpilogueBegin ? " epilogue_begin" : "")
437      << (EndSequence ? " end_sequence" : "") << '\n';
438 }
439 
440 DWARFDebugLine::Sequence::Sequence() { reset(); }
441 
442 void DWARFDebugLine::Sequence::reset() {
443   LowPC = 0;
444   HighPC = 0;
445   SectionIndex = object::SectionedAddress::UndefSection;
446   FirstRowIndex = 0;
447   LastRowIndex = 0;
448   Empty = true;
449 }
450 
451 DWARFDebugLine::LineTable::LineTable() { clear(); }
452 
453 void DWARFDebugLine::LineTable::dump(raw_ostream &OS,
454                                      DIDumpOptions DumpOptions) const {
455   Prologue.dump(OS, DumpOptions);
456 
457   if (!Rows.empty()) {
458     OS << '\n';
459     Row::dumpTableHeader(OS);
460     for (const Row &R : Rows) {
461       R.dump(OS);
462     }
463   }
464 
465   // Terminate the table with a final blank line to clearly delineate it from
466   // later dumps.
467   OS << '\n';
468 }
469 
470 void DWARFDebugLine::LineTable::clear() {
471   Prologue.clear();
472   Rows.clear();
473   Sequences.clear();
474 }
475 
476 DWARFDebugLine::ParsingState::ParsingState(struct LineTable *LT)
477     : LineTable(LT) {
478   resetRowAndSequence();
479 }
480 
481 void DWARFDebugLine::ParsingState::resetRowAndSequence() {
482   Row.reset(LineTable->Prologue.DefaultIsStmt);
483   Sequence.reset();
484 }
485 
486 void DWARFDebugLine::ParsingState::appendRowToMatrix() {
487   unsigned RowNumber = LineTable->Rows.size();
488   if (Sequence.Empty) {
489     // Record the beginning of instruction sequence.
490     Sequence.Empty = false;
491     Sequence.LowPC = Row.Address.Address;
492     Sequence.FirstRowIndex = RowNumber;
493   }
494   LineTable->appendRow(Row);
495   if (Row.EndSequence) {
496     // Record the end of instruction sequence.
497     Sequence.HighPC = Row.Address.Address;
498     Sequence.LastRowIndex = RowNumber + 1;
499     Sequence.SectionIndex = Row.Address.SectionIndex;
500     if (Sequence.isValid())
501       LineTable->appendSequence(Sequence);
502     Sequence.reset();
503   }
504   Row.postAppend();
505 }
506 
507 const DWARFDebugLine::LineTable *
508 DWARFDebugLine::getLineTable(uint64_t Offset) const {
509   LineTableConstIter Pos = LineTableMap.find(Offset);
510   if (Pos != LineTableMap.end())
511     return &Pos->second;
512   return nullptr;
513 }
514 
515 Expected<const DWARFDebugLine::LineTable *> DWARFDebugLine::getOrParseLineTable(
516     DWARFDataExtractor &DebugLineData, uint64_t Offset, const DWARFContext &Ctx,
517     const DWARFUnit *U, std::function<void(Error)> RecoverableErrorCallback) {
518   if (!DebugLineData.isValidOffset(Offset))
519     return createStringError(errc::invalid_argument, "offset 0x%8.8" PRIx64
520                        " is not a valid debug line section offset",
521                        Offset);
522 
523   std::pair<LineTableIter, bool> Pos =
524       LineTableMap.insert(LineTableMapTy::value_type(Offset, LineTable()));
525   LineTable *LT = &Pos.first->second;
526   if (Pos.second) {
527     if (Error Err =
528             LT->parse(DebugLineData, &Offset, Ctx, U, RecoverableErrorCallback))
529       return std::move(Err);
530     return LT;
531   }
532   return LT;
533 }
534 
535 Error DWARFDebugLine::LineTable::parse(
536     DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr,
537     const DWARFContext &Ctx, const DWARFUnit *U,
538     std::function<void(Error)> RecoverableErrorCallback, raw_ostream *OS) {
539   const uint64_t DebugLineOffset = *OffsetPtr;
540 
541   clear();
542 
543   Error PrologueErr = Prologue.parse(DebugLineData, OffsetPtr, Ctx, U);
544 
545   if (OS) {
546     // The presence of OS signals verbose dumping.
547     DIDumpOptions DumpOptions;
548     DumpOptions.Verbose = true;
549     Prologue.dump(*OS, DumpOptions);
550   }
551 
552   if (PrologueErr)
553     return PrologueErr;
554 
555   const uint64_t EndOffset =
556       DebugLineOffset + Prologue.TotalLength + Prologue.sizeofTotalLength();
557 
558   // See if we should tell the data extractor the address size.
559   if (DebugLineData.getAddressSize() == 0)
560     DebugLineData.setAddressSize(Prologue.getAddressSize());
561   else
562     assert(Prologue.getAddressSize() == 0 ||
563            Prologue.getAddressSize() == DebugLineData.getAddressSize());
564 
565   ParsingState State(this);
566 
567   while (*OffsetPtr < EndOffset) {
568     if (OS)
569       *OS << format("0x%08.08" PRIx64 ": ", *OffsetPtr);
570 
571     uint8_t Opcode = DebugLineData.getU8(OffsetPtr);
572 
573     if (OS)
574       *OS << format("%02.02" PRIx8 " ", Opcode);
575 
576     if (Opcode == 0) {
577       // Extended Opcodes always start with a zero opcode followed by
578       // a uleb128 length so you can skip ones you don't know about
579       uint64_t Len = DebugLineData.getULEB128(OffsetPtr);
580       uint64_t ExtOffset = *OffsetPtr;
581 
582       // Tolerate zero-length; assume length is correct and soldier on.
583       if (Len == 0) {
584         if (OS)
585           *OS << "Badly formed extended line op (length 0)\n";
586         continue;
587       }
588 
589       uint8_t SubOpcode = DebugLineData.getU8(OffsetPtr);
590       if (OS)
591         *OS << LNExtendedString(SubOpcode);
592       switch (SubOpcode) {
593       case DW_LNE_end_sequence:
594         // Set the end_sequence register of the state machine to true and
595         // append a row to the matrix using the current values of the
596         // state-machine registers. Then reset the registers to the initial
597         // values specified above. Every statement program sequence must end
598         // with a DW_LNE_end_sequence instruction which creates a row whose
599         // address is that of the byte after the last target machine instruction
600         // of the sequence.
601         State.Row.EndSequence = true;
602         if (OS) {
603           *OS << "\n";
604           OS->indent(12);
605           State.Row.dump(*OS);
606         }
607         State.appendRowToMatrix();
608         State.resetRowAndSequence();
609         break;
610 
611       case DW_LNE_set_address:
612         // Takes a single relocatable address as an operand. The size of the
613         // operand is the size appropriate to hold an address on the target
614         // machine. Set the address register to the value given by the
615         // relocatable address. All of the other statement program opcodes
616         // that affect the address register add a delta to it. This instruction
617         // stores a relocatable value into it instead.
618         //
619         // Make sure the extractor knows the address size.  If not, infer it
620         // from the size of the operand.
621         if (DebugLineData.getAddressSize() == 0)
622           DebugLineData.setAddressSize(Len - 1);
623         else if (DebugLineData.getAddressSize() != Len - 1) {
624           return createStringError(errc::invalid_argument,
625                              "mismatching address size at offset 0x%8.8" PRIx64
626                              " expected 0x%2.2" PRIx8 " found 0x%2.2" PRIx64,
627                              ExtOffset, DebugLineData.getAddressSize(),
628                              Len - 1);
629         }
630         State.Row.Address.Address = DebugLineData.getRelocatedAddress(
631             OffsetPtr, &State.Row.Address.SectionIndex);
632         if (OS)
633           *OS << format(" (0x%16.16" PRIx64 ")", State.Row.Address.Address);
634         break;
635 
636       case DW_LNE_define_file:
637         // Takes 4 arguments. The first is a null terminated string containing
638         // a source file name. The second is an unsigned LEB128 number
639         // representing the directory index of the directory in which the file
640         // was found. The third is an unsigned LEB128 number representing the
641         // time of last modification of the file. The fourth is an unsigned
642         // LEB128 number representing the length in bytes of the file. The time
643         // and length fields may contain LEB128(0) if the information is not
644         // available.
645         //
646         // The directory index represents an entry in the include_directories
647         // section of the statement program prologue. The index is LEB128(0)
648         // if the file was found in the current directory of the compilation,
649         // LEB128(1) if it was found in the first directory in the
650         // include_directories section, and so on. The directory index is
651         // ignored for file names that represent full path names.
652         //
653         // The files are numbered, starting at 1, in the order in which they
654         // appear; the names in the prologue come before names defined by
655         // the DW_LNE_define_file instruction. These numbers are used in the
656         // the file register of the state machine.
657         {
658           FileNameEntry FileEntry;
659           const char *Name = DebugLineData.getCStr(OffsetPtr);
660           FileEntry.Name =
661               DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, Name);
662           FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr);
663           FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr);
664           FileEntry.Length = DebugLineData.getULEB128(OffsetPtr);
665           Prologue.FileNames.push_back(FileEntry);
666           if (OS)
667             *OS << " (" << Name << ", dir=" << FileEntry.DirIdx << ", mod_time="
668                 << format("(0x%16.16" PRIx64 ")", FileEntry.ModTime)
669                 << ", length=" << FileEntry.Length << ")";
670         }
671         break;
672 
673       case DW_LNE_set_discriminator:
674         State.Row.Discriminator = DebugLineData.getULEB128(OffsetPtr);
675         if (OS)
676           *OS << " (" << State.Row.Discriminator << ")";
677         break;
678 
679       default:
680         if (OS)
681           *OS << format("Unrecognized extended op 0x%02.02" PRIx8, SubOpcode)
682               << format(" length %" PRIx64, Len);
683         // Len doesn't include the zero opcode byte or the length itself, but
684         // it does include the sub_opcode, so we have to adjust for that.
685         (*OffsetPtr) += Len - 1;
686         break;
687       }
688       // Make sure the stated and parsed lengths are the same.
689       // Otherwise we have an unparseable line-number program.
690       if (*OffsetPtr - ExtOffset != Len)
691         return createStringError(errc::illegal_byte_sequence,
692                            "unexpected line op length at offset 0x%8.8" PRIx64
693                            " expected 0x%2.2" PRIx64 " found 0x%2.2" PRIx64,
694                            ExtOffset, Len, *OffsetPtr - ExtOffset);
695     } else if (Opcode < Prologue.OpcodeBase) {
696       if (OS)
697         *OS << LNStandardString(Opcode);
698       switch (Opcode) {
699       // Standard Opcodes
700       case DW_LNS_copy:
701         // Takes no arguments. Append a row to the matrix using the
702         // current values of the state-machine registers.
703         if (OS) {
704           *OS << "\n";
705           OS->indent(12);
706           State.Row.dump(*OS);
707           *OS << "\n";
708         }
709         State.appendRowToMatrix();
710         break;
711 
712       case DW_LNS_advance_pc:
713         // Takes a single unsigned LEB128 operand, multiplies it by the
714         // min_inst_length field of the prologue, and adds the
715         // result to the address register of the state machine.
716         {
717           uint64_t AddrOffset =
718               DebugLineData.getULEB128(OffsetPtr) * Prologue.MinInstLength;
719           State.Row.Address.Address += AddrOffset;
720           if (OS)
721             *OS << " (" << AddrOffset << ")";
722         }
723         break;
724 
725       case DW_LNS_advance_line:
726         // Takes a single signed LEB128 operand and adds that value to
727         // the line register of the state machine.
728         State.Row.Line += DebugLineData.getSLEB128(OffsetPtr);
729         if (OS)
730           *OS << " (" << State.Row.Line << ")";
731         break;
732 
733       case DW_LNS_set_file:
734         // Takes a single unsigned LEB128 operand and stores it in the file
735         // register of the state machine.
736         State.Row.File = DebugLineData.getULEB128(OffsetPtr);
737         if (OS)
738           *OS << " (" << State.Row.File << ")";
739         break;
740 
741       case DW_LNS_set_column:
742         // Takes a single unsigned LEB128 operand and stores it in the
743         // column register of the state machine.
744         State.Row.Column = DebugLineData.getULEB128(OffsetPtr);
745         if (OS)
746           *OS << " (" << State.Row.Column << ")";
747         break;
748 
749       case DW_LNS_negate_stmt:
750         // Takes no arguments. Set the is_stmt register of the state
751         // machine to the logical negation of its current value.
752         State.Row.IsStmt = !State.Row.IsStmt;
753         break;
754 
755       case DW_LNS_set_basic_block:
756         // Takes no arguments. Set the basic_block register of the
757         // state machine to true
758         State.Row.BasicBlock = true;
759         break;
760 
761       case DW_LNS_const_add_pc:
762         // Takes no arguments. Add to the address register of the state
763         // machine the address increment value corresponding to special
764         // opcode 255. The motivation for DW_LNS_const_add_pc is this:
765         // when the statement program needs to advance the address by a
766         // small amount, it can use a single special opcode, which occupies
767         // a single byte. When it needs to advance the address by up to
768         // twice the range of the last special opcode, it can use
769         // DW_LNS_const_add_pc followed by a special opcode, for a total
770         // of two bytes. Only if it needs to advance the address by more
771         // than twice that range will it need to use both DW_LNS_advance_pc
772         // and a special opcode, requiring three or more bytes.
773         {
774           uint8_t AdjustOpcode = 255 - Prologue.OpcodeBase;
775           uint64_t AddrOffset =
776               (AdjustOpcode / Prologue.LineRange) * Prologue.MinInstLength;
777           State.Row.Address.Address += AddrOffset;
778           if (OS)
779             *OS
780                 << format(" (0x%16.16" PRIx64 ")", AddrOffset);
781         }
782         break;
783 
784       case DW_LNS_fixed_advance_pc:
785         // Takes a single uhalf operand. Add to the address register of
786         // the state machine the value of the (unencoded) operand. This
787         // is the only extended opcode that takes an argument that is not
788         // a variable length number. The motivation for DW_LNS_fixed_advance_pc
789         // is this: existing assemblers cannot emit DW_LNS_advance_pc or
790         // special opcodes because they cannot encode LEB128 numbers or
791         // judge when the computation of a special opcode overflows and
792         // requires the use of DW_LNS_advance_pc. Such assemblers, however,
793         // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
794         {
795           uint16_t PCOffset = DebugLineData.getRelocatedValue(2, OffsetPtr);
796           State.Row.Address.Address += PCOffset;
797           if (OS)
798             *OS
799                 << format(" (0x%4.4" PRIx16 ")", PCOffset);
800         }
801         break;
802 
803       case DW_LNS_set_prologue_end:
804         // Takes no arguments. Set the prologue_end register of the
805         // state machine to true
806         State.Row.PrologueEnd = true;
807         break;
808 
809       case DW_LNS_set_epilogue_begin:
810         // Takes no arguments. Set the basic_block register of the
811         // state machine to true
812         State.Row.EpilogueBegin = true;
813         break;
814 
815       case DW_LNS_set_isa:
816         // Takes a single unsigned LEB128 operand and stores it in the
817         // column register of the state machine.
818         State.Row.Isa = DebugLineData.getULEB128(OffsetPtr);
819         if (OS)
820           *OS << " (" << (uint64_t)State.Row.Isa << ")";
821         break;
822 
823       default:
824         // Handle any unknown standard opcodes here. We know the lengths
825         // of such opcodes because they are specified in the prologue
826         // as a multiple of LEB128 operands for each opcode.
827         {
828           assert(Opcode - 1U < Prologue.StandardOpcodeLengths.size());
829           uint8_t OpcodeLength = Prologue.StandardOpcodeLengths[Opcode - 1];
830           for (uint8_t I = 0; I < OpcodeLength; ++I) {
831             uint64_t Value = DebugLineData.getULEB128(OffsetPtr);
832             if (OS)
833               *OS << format("Skipping ULEB128 value: 0x%16.16" PRIx64 ")\n",
834                             Value);
835           }
836         }
837         break;
838       }
839     } else {
840       // Special Opcodes
841 
842       // A special opcode value is chosen based on the amount that needs
843       // to be added to the line and address registers. The maximum line
844       // increment for a special opcode is the value of the line_base
845       // field in the header, plus the value of the line_range field,
846       // minus 1 (line base + line range - 1). If the desired line
847       // increment is greater than the maximum line increment, a standard
848       // opcode must be used instead of a special opcode. The "address
849       // advance" is calculated by dividing the desired address increment
850       // by the minimum_instruction_length field from the header. The
851       // special opcode is then calculated using the following formula:
852       //
853       //  opcode = (desired line increment - line_base) +
854       //           (line_range * address advance) + opcode_base
855       //
856       // If the resulting opcode is greater than 255, a standard opcode
857       // must be used instead.
858       //
859       // To decode a special opcode, subtract the opcode_base from the
860       // opcode itself to give the adjusted opcode. The amount to
861       // increment the address register is the result of the adjusted
862       // opcode divided by the line_range multiplied by the
863       // minimum_instruction_length field from the header. That is:
864       //
865       //  address increment = (adjusted opcode / line_range) *
866       //                      minimum_instruction_length
867       //
868       // The amount to increment the line register is the line_base plus
869       // the result of the adjusted opcode modulo the line_range. That is:
870       //
871       // line increment = line_base + (adjusted opcode % line_range)
872 
873       uint8_t AdjustOpcode = Opcode - Prologue.OpcodeBase;
874       uint64_t AddrOffset =
875           (AdjustOpcode / Prologue.LineRange) * Prologue.MinInstLength;
876       int32_t LineOffset =
877           Prologue.LineBase + (AdjustOpcode % Prologue.LineRange);
878       State.Row.Line += LineOffset;
879       State.Row.Address.Address += AddrOffset;
880 
881       if (OS) {
882         *OS << "address += " << AddrOffset << ",  line += " << LineOffset
883             << "\n";
884         OS->indent(12);
885         State.Row.dump(*OS);
886       }
887 
888       State.appendRowToMatrix();
889     }
890     if(OS)
891       *OS << "\n";
892   }
893 
894   if (!State.Sequence.Empty)
895     RecoverableErrorCallback(
896         createStringError(errc::illegal_byte_sequence,
897                     "last sequence in debug line table is not terminated!"));
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 
913 uint32_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 
937 uint32_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 
952 uint32_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 
965 bool 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 
981 bool 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 
1029 Optional<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 
1039 static 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 
1047 bool 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   StringRef FileName = Entry.Name.getAsCString().getValue();
1054   if (Kind != FileLineInfoKind::AbsoluteFilePath ||
1055       isPathAbsoluteOnWindowsOrPosix(FileName)) {
1056     Result = FileName;
1057     return true;
1058   }
1059 
1060   SmallString<16> FilePath;
1061   StringRef IncludeDir;
1062   // Be defensive about the contents of Entry.
1063   if (getVersion() >= 5) {
1064     if (Entry.DirIdx < IncludeDirectories.size())
1065       IncludeDir = IncludeDirectories[Entry.DirIdx].getAsCString().getValue();
1066   } else {
1067     if (0 < Entry.DirIdx && Entry.DirIdx <= IncludeDirectories.size())
1068       IncludeDir =
1069           IncludeDirectories[Entry.DirIdx - 1].getAsCString().getValue();
1070 
1071     // We may still need to append compilation directory of compile unit.
1072     // We know that FileName is not absolute, the only way to have an
1073     // absolute path at this point would be if IncludeDir is absolute.
1074     if (!CompDir.empty() && !isPathAbsoluteOnWindowsOrPosix(IncludeDir))
1075       sys::path::append(FilePath, Style, CompDir);
1076   }
1077 
1078   // sys::path::append skips empty strings.
1079   sys::path::append(FilePath, Style, IncludeDir, FileName);
1080   Result = FilePath.str();
1081   return true;
1082 }
1083 
1084 bool DWARFDebugLine::LineTable::getFileLineInfoForAddress(
1085     object::SectionedAddress Address, const char *CompDir,
1086     FileLineInfoKind Kind, DILineInfo &Result) const {
1087   // Get the index of row we're looking for in the line table.
1088   uint32_t RowIndex = lookupAddress(Address);
1089   if (RowIndex == -1U)
1090     return false;
1091   // Take file number and line/column from the row.
1092   const auto &Row = Rows[RowIndex];
1093   if (!getFileNameByIndex(Row.File, CompDir, Kind, Result.FileName))
1094     return false;
1095   Result.Line = Row.Line;
1096   Result.Column = Row.Column;
1097   Result.Discriminator = Row.Discriminator;
1098   Result.Source = getSourceByIndex(Row.File, Kind);
1099   return true;
1100 }
1101 
1102 // We want to supply the Unit associated with a .debug_line[.dwo] table when
1103 // we dump it, if possible, but still dump the table even if there isn't a Unit.
1104 // Therefore, collect up handles on all the Units that point into the
1105 // line-table section.
1106 static DWARFDebugLine::SectionParser::LineToUnitMap
1107 buildLineToUnitMap(DWARFDebugLine::SectionParser::cu_range CUs,
1108                    DWARFDebugLine::SectionParser::tu_range TUs) {
1109   DWARFDebugLine::SectionParser::LineToUnitMap LineToUnit;
1110   for (const auto &CU : CUs)
1111     if (auto CUDIE = CU->getUnitDIE())
1112       if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list)))
1113         LineToUnit.insert(std::make_pair(*StmtOffset, &*CU));
1114   for (const auto &TU : TUs)
1115     if (auto TUDIE = TU->getUnitDIE())
1116       if (auto StmtOffset = toSectionOffset(TUDIE.find(DW_AT_stmt_list)))
1117         LineToUnit.insert(std::make_pair(*StmtOffset, &*TU));
1118   return LineToUnit;
1119 }
1120 
1121 DWARFDebugLine::SectionParser::SectionParser(DWARFDataExtractor &Data,
1122                                              const DWARFContext &C,
1123                                              cu_range CUs, tu_range TUs)
1124     : DebugLineData(Data), Context(C) {
1125   LineToUnit = buildLineToUnitMap(CUs, TUs);
1126   if (!DebugLineData.isValidOffset(Offset))
1127     Done = true;
1128 }
1129 
1130 bool DWARFDebugLine::Prologue::totalLengthIsValid() const {
1131   return TotalLength == dwarf::DW_LENGTH_DWARF64 ||
1132          TotalLength < dwarf::DW_LENGTH_lo_reserved;
1133 }
1134 
1135 DWARFDebugLine::LineTable DWARFDebugLine::SectionParser::parseNext(
1136     function_ref<void(Error)> RecoverableErrorCallback,
1137     function_ref<void(Error)> UnrecoverableErrorCallback, raw_ostream *OS) {
1138   assert(DebugLineData.isValidOffset(Offset) &&
1139          "parsing should have terminated");
1140   DWARFUnit *U = prepareToParse(Offset);
1141   uint64_t OldOffset = Offset;
1142   LineTable LT;
1143   if (Error Err = LT.parse(DebugLineData, &Offset, Context, U,
1144                            RecoverableErrorCallback, OS))
1145     UnrecoverableErrorCallback(std::move(Err));
1146   moveToNextTable(OldOffset, LT.Prologue);
1147   return LT;
1148 }
1149 
1150 void DWARFDebugLine::SectionParser::skip(
1151     function_ref<void(Error)> ErrorCallback) {
1152   assert(DebugLineData.isValidOffset(Offset) &&
1153          "parsing should have terminated");
1154   DWARFUnit *U = prepareToParse(Offset);
1155   uint64_t OldOffset = Offset;
1156   LineTable LT;
1157   if (Error Err = LT.Prologue.parse(DebugLineData, &Offset, Context, U))
1158     ErrorCallback(std::move(Err));
1159   moveToNextTable(OldOffset, LT.Prologue);
1160 }
1161 
1162 DWARFUnit *DWARFDebugLine::SectionParser::prepareToParse(uint64_t Offset) {
1163   DWARFUnit *U = nullptr;
1164   auto It = LineToUnit.find(Offset);
1165   if (It != LineToUnit.end())
1166     U = It->second;
1167   DebugLineData.setAddressSize(U ? U->getAddressByteSize() : 0);
1168   return U;
1169 }
1170 
1171 void DWARFDebugLine::SectionParser::moveToNextTable(uint64_t OldOffset,
1172                                                     const Prologue &P) {
1173   // If the length field is not valid, we don't know where the next table is, so
1174   // cannot continue to parse. Mark the parser as done, and leave the Offset
1175   // value as it currently is. This will be the end of the bad length field.
1176   if (!P.totalLengthIsValid()) {
1177     Done = true;
1178     return;
1179   }
1180 
1181   Offset = OldOffset + P.TotalLength + P.sizeofTotalLength();
1182   if (!DebugLineData.isValidOffset(Offset)) {
1183     Done = true;
1184   }
1185 }
1186