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/FormatVariadic.h"
20 #include "llvm/Support/WithColor.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <algorithm>
23 #include <cassert>
24 #include <cinttypes>
25 #include <cstdint>
26 #include <cstdio>
27 #include <utility>
28 
29 using namespace llvm;
30 using namespace dwarf;
31 
32 using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
33 
34 namespace {
35 
36 struct ContentDescriptor {
37   dwarf::LineNumberEntryFormat Type;
38   dwarf::Form Form;
39 };
40 
41 using ContentDescriptors = SmallVector<ContentDescriptor, 4>;
42 
43 } // end anonymous namespace
44 
45 void DWARFDebugLine::ContentTypeTracker::trackContentType(
46     dwarf::LineNumberEntryFormat ContentType) {
47   switch (ContentType) {
48   case dwarf::DW_LNCT_timestamp:
49     HasModTime = true;
50     break;
51   case dwarf::DW_LNCT_size:
52     HasLength = true;
53     break;
54   case dwarf::DW_LNCT_MD5:
55     HasMD5 = true;
56     break;
57   case dwarf::DW_LNCT_LLVM_source:
58     HasSource = true;
59     break;
60   default:
61     // We only care about values we consider optional, and new values may be
62     // added in the vendor extension range, so we do not match exhaustively.
63     break;
64   }
65 }
66 
67 DWARFDebugLine::Prologue::Prologue() { clear(); }
68 
69 bool DWARFDebugLine::Prologue::hasFileAtIndex(uint64_t FileIndex) const {
70   uint16_t DwarfVersion = getVersion();
71   assert(DwarfVersion != 0 &&
72          "line table prologue has no dwarf version information");
73   if (DwarfVersion >= 5)
74     return FileIndex < FileNames.size();
75   return FileIndex != 0 && FileIndex <= FileNames.size();
76 }
77 
78 const llvm::DWARFDebugLine::FileNameEntry &
79 DWARFDebugLine::Prologue::getFileNameEntry(uint64_t Index) const {
80   uint16_t DwarfVersion = getVersion();
81   assert(DwarfVersion != 0 &&
82          "line table prologue has no dwarf version information");
83   // In DWARF v5 the file names are 0-indexed.
84   if (DwarfVersion >= 5)
85     return FileNames[Index];
86   return FileNames[Index - 1];
87 }
88 
89 void DWARFDebugLine::Prologue::clear() {
90   TotalLength = PrologueLength = 0;
91   SegSelectorSize = 0;
92   MinInstLength = MaxOpsPerInst = DefaultIsStmt = LineBase = LineRange = 0;
93   OpcodeBase = 0;
94   FormParams = dwarf::FormParams({0, 0, DWARF32});
95   ContentTypes = ContentTypeTracker();
96   StandardOpcodeLengths.clear();
97   IncludeDirectories.clear();
98   FileNames.clear();
99 }
100 
101 void DWARFDebugLine::Prologue::dump(raw_ostream &OS,
102                                     DIDumpOptions DumpOptions) const {
103   OS << "Line table prologue:\n"
104      << format("    total_length: 0x%8.8" PRIx64 "\n", TotalLength)
105      << format("         version: %u\n", getVersion());
106   if (getVersion() >= 5)
107     OS << format("    address_size: %u\n", getAddressSize())
108        << format(" seg_select_size: %u\n", SegSelectorSize);
109   OS << format(" prologue_length: 0x%8.8" PRIx64 "\n", PrologueLength)
110      << format(" min_inst_length: %u\n", MinInstLength)
111      << format(getVersion() >= 4 ? "max_ops_per_inst: %u\n" : "", MaxOpsPerInst)
112      << format(" default_is_stmt: %u\n", DefaultIsStmt)
113      << format("       line_base: %i\n", LineBase)
114      << format("      line_range: %u\n", LineRange)
115      << format("     opcode_base: %u\n", OpcodeBase);
116 
117   for (uint32_t I = 0; I != StandardOpcodeLengths.size(); ++I)
118     OS << formatv("standard_opcode_lengths[{0}] = {1}\n",
119                   static_cast<dwarf::LineNumberOps>(I + 1),
120                   StandardOpcodeLengths[I]);
121 
122   if (!IncludeDirectories.empty()) {
123     // DWARF v5 starts directory indexes at 0.
124     uint32_t DirBase = getVersion() >= 5 ? 0 : 1;
125     for (uint32_t I = 0; I != IncludeDirectories.size(); ++I) {
126       OS << format("include_directories[%3u] = ", I + DirBase);
127       IncludeDirectories[I].dump(OS, DumpOptions);
128       OS << '\n';
129     }
130   }
131 
132   if (!FileNames.empty()) {
133     // DWARF v5 starts file indexes at 0.
134     uint32_t FileBase = getVersion() >= 5 ? 0 : 1;
135     for (uint32_t I = 0; I != FileNames.size(); ++I) {
136       const FileNameEntry &FileEntry = FileNames[I];
137       OS <<   format("file_names[%3u]:\n", I + FileBase);
138       OS <<          "           name: ";
139       FileEntry.Name.dump(OS, DumpOptions);
140       OS << '\n'
141          <<   format("      dir_index: %" PRIu64 "\n", FileEntry.DirIdx);
142       if (ContentTypes.HasMD5)
143         OS <<        "   md5_checksum: " << FileEntry.Checksum.digest() << '\n';
144       if (ContentTypes.HasModTime)
145         OS << format("       mod_time: 0x%8.8" PRIx64 "\n", FileEntry.ModTime);
146       if (ContentTypes.HasLength)
147         OS << format("         length: 0x%8.8" PRIx64 "\n", FileEntry.Length);
148       if (ContentTypes.HasSource) {
149         OS <<        "         source: ";
150         FileEntry.Source.dump(OS, DumpOptions);
151         OS << '\n';
152       }
153     }
154   }
155 }
156 
157 // Parse v2-v4 directory and file tables.
158 static void
159 parseV2DirFileTables(const DWARFDataExtractor &DebugLineData,
160                      uint64_t *OffsetPtr, uint64_t EndPrologueOffset,
161                      DWARFDebugLine::ContentTypeTracker &ContentTypes,
162                      std::vector<DWARFFormValue> &IncludeDirectories,
163                      std::vector<DWARFDebugLine::FileNameEntry> &FileNames) {
164   while (*OffsetPtr < EndPrologueOffset) {
165     StringRef S = DebugLineData.getCStrRef(OffsetPtr);
166     if (S.empty())
167       break;
168     DWARFFormValue Dir =
169         DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, S.data());
170     IncludeDirectories.push_back(Dir);
171   }
172 
173   while (*OffsetPtr < EndPrologueOffset) {
174     StringRef Name = DebugLineData.getCStrRef(OffsetPtr);
175     if (Name.empty())
176       break;
177     DWARFDebugLine::FileNameEntry FileEntry;
178     FileEntry.Name =
179         DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, Name.data());
180     FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr);
181     FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr);
182     FileEntry.Length = DebugLineData.getULEB128(OffsetPtr);
183     FileNames.push_back(FileEntry);
184   }
185 
186   ContentTypes.HasModTime = true;
187   ContentTypes.HasLength = true;
188 }
189 
190 // Parse v5 directory/file entry content descriptions.
191 // Returns the descriptors, or an error if we did not find a path or ran off
192 // the end of the prologue.
193 static llvm::Expected<ContentDescriptors>
194 parseV5EntryFormat(const DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr,
195                    DWARFDebugLine::ContentTypeTracker *ContentTypes) {
196   ContentDescriptors Descriptors;
197   int FormatCount = DebugLineData.getU8(OffsetPtr);
198   bool HasPath = false;
199   for (int I = 0; I != FormatCount; ++I) {
200     ContentDescriptor Descriptor;
201     Descriptor.Type =
202       dwarf::LineNumberEntryFormat(DebugLineData.getULEB128(OffsetPtr));
203     Descriptor.Form = dwarf::Form(DebugLineData.getULEB128(OffsetPtr));
204     if (Descriptor.Type == dwarf::DW_LNCT_path)
205       HasPath = true;
206     if (ContentTypes)
207       ContentTypes->trackContentType(Descriptor.Type);
208     Descriptors.push_back(Descriptor);
209   }
210 
211   if (!HasPath)
212     return createStringError(errc::invalid_argument,
213                              "failed to parse entry content descriptions"
214                              " because no path was found");
215   return Descriptors;
216 }
217 
218 static Error
219 parseV5DirFileTables(const DWARFDataExtractor &DebugLineData,
220                      uint64_t *OffsetPtr, const dwarf::FormParams &FormParams,
221                      const DWARFContext &Ctx, const DWARFUnit *U,
222                      DWARFDebugLine::ContentTypeTracker &ContentTypes,
223                      std::vector<DWARFFormValue> &IncludeDirectories,
224                      std::vector<DWARFDebugLine::FileNameEntry> &FileNames) {
225   // Get the directory entry description.
226   llvm::Expected<ContentDescriptors> DirDescriptors =
227       parseV5EntryFormat(DebugLineData, OffsetPtr, nullptr);
228   if (!DirDescriptors)
229     return DirDescriptors.takeError();
230 
231   // Get the directory entries, according to the format described above.
232   int DirEntryCount = DebugLineData.getU8(OffsetPtr);
233   for (int I = 0; I != DirEntryCount; ++I) {
234     for (auto Descriptor : *DirDescriptors) {
235       DWARFFormValue Value(Descriptor.Form);
236       switch (Descriptor.Type) {
237       case DW_LNCT_path:
238         if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U))
239           return createStringError(errc::invalid_argument,
240                                    "failed to parse directory entry because "
241                                    "extracting the form value failed.");
242         IncludeDirectories.push_back(Value);
243         break;
244       default:
245         if (!Value.skipValue(DebugLineData, OffsetPtr, FormParams))
246           return createStringError(errc::invalid_argument,
247                                    "failed to parse directory entry because "
248                                    "skipping the form value failed.");
249       }
250     }
251   }
252 
253   // Get the file entry description.
254   llvm::Expected<ContentDescriptors> FileDescriptors =
255       parseV5EntryFormat(DebugLineData, OffsetPtr, &ContentTypes);
256   if (!FileDescriptors)
257     return FileDescriptors.takeError();
258 
259   // Get the file entries, according to the format described above.
260   int FileEntryCount = DebugLineData.getU8(OffsetPtr);
261   for (int I = 0; I != FileEntryCount; ++I) {
262     DWARFDebugLine::FileNameEntry FileEntry;
263     for (auto Descriptor : *FileDescriptors) {
264       DWARFFormValue Value(Descriptor.Form);
265       if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U))
266         return createStringError(errc::invalid_argument,
267                                  "failed to parse file entry because "
268                                  "extracting the form value failed.");
269       switch (Descriptor.Type) {
270       case DW_LNCT_path:
271         FileEntry.Name = Value;
272         break;
273       case DW_LNCT_LLVM_source:
274         FileEntry.Source = Value;
275         break;
276       case DW_LNCT_directory_index:
277         FileEntry.DirIdx = Value.getAsUnsignedConstant().getValue();
278         break;
279       case DW_LNCT_timestamp:
280         FileEntry.ModTime = Value.getAsUnsignedConstant().getValue();
281         break;
282       case DW_LNCT_size:
283         FileEntry.Length = Value.getAsUnsignedConstant().getValue();
284         break;
285       case DW_LNCT_MD5:
286         if (!Value.getAsBlock() || Value.getAsBlock().getValue().size() != 16)
287           return createStringError(
288               errc::invalid_argument,
289               "failed to parse file entry because the MD5 hash is invalid");
290         std::uninitialized_copy_n(Value.getAsBlock().getValue().begin(), 16,
291                                   FileEntry.Checksum.Bytes.begin());
292         break;
293       default:
294         break;
295       }
296     }
297     FileNames.push_back(FileEntry);
298   }
299   return Error::success();
300 }
301 
302 Error DWARFDebugLine::Prologue::parse(const DWARFDataExtractor &DebugLineData,
303                                       uint64_t *OffsetPtr,
304                                       const DWARFContext &Ctx,
305                                       const DWARFUnit *U) {
306   const uint64_t PrologueOffset = *OffsetPtr;
307 
308   clear();
309   TotalLength = DebugLineData.getRelocatedValue(4, OffsetPtr);
310   if (TotalLength == dwarf::DW_LENGTH_DWARF64) {
311     FormParams.Format = dwarf::DWARF64;
312     TotalLength = DebugLineData.getU64(OffsetPtr);
313   } else if (TotalLength >= dwarf::DW_LENGTH_lo_reserved) {
314     return createStringError(errc::invalid_argument,
315         "parsing line table prologue at offset 0x%8.8" PRIx64
316         " unsupported reserved unit length found of value 0x%8.8" PRIx64,
317         PrologueOffset, TotalLength);
318   }
319   FormParams.Version = DebugLineData.getU16(OffsetPtr);
320   if (getVersion() < 2)
321     return createStringError(errc::not_supported,
322                        "parsing line table prologue at offset 0x%8.8" PRIx64
323                        " found unsupported version 0x%2.2" PRIx16,
324                        PrologueOffset, getVersion());
325 
326   if (getVersion() >= 5) {
327     FormParams.AddrSize = DebugLineData.getU8(OffsetPtr);
328     assert((DebugLineData.getAddressSize() == 0 ||
329             DebugLineData.getAddressSize() == getAddressSize()) &&
330            "Line table header and data extractor disagree");
331     SegSelectorSize = DebugLineData.getU8(OffsetPtr);
332   }
333 
334   PrologueLength =
335       DebugLineData.getRelocatedValue(sizeofPrologueLength(), OffsetPtr);
336   const uint64_t EndPrologueOffset = PrologueLength + *OffsetPtr;
337   MinInstLength = DebugLineData.getU8(OffsetPtr);
338   if (getVersion() >= 4)
339     MaxOpsPerInst = DebugLineData.getU8(OffsetPtr);
340   DefaultIsStmt = DebugLineData.getU8(OffsetPtr);
341   LineBase = DebugLineData.getU8(OffsetPtr);
342   LineRange = DebugLineData.getU8(OffsetPtr);
343   OpcodeBase = DebugLineData.getU8(OffsetPtr);
344 
345   StandardOpcodeLengths.reserve(OpcodeBase - 1);
346   for (uint32_t I = 1; I < OpcodeBase; ++I) {
347     uint8_t OpLen = DebugLineData.getU8(OffsetPtr);
348     StandardOpcodeLengths.push_back(OpLen);
349   }
350 
351   if (getVersion() >= 5) {
352     if (Error E =
353             parseV5DirFileTables(DebugLineData, OffsetPtr, FormParams, Ctx, U,
354                                  ContentTypes, IncludeDirectories, FileNames)) {
355       return joinErrors(
356           createStringError(
357               errc::invalid_argument,
358               "parsing line table prologue at 0x%8.8" PRIx64
359               " found an invalid directory or file table description at"
360               " 0x%8.8" PRIx64,
361               PrologueOffset, *OffsetPtr),
362           std::move(E));
363     }
364   } else
365     parseV2DirFileTables(DebugLineData, OffsetPtr, EndPrologueOffset,
366                          ContentTypes, IncludeDirectories, FileNames);
367 
368   if (*OffsetPtr != EndPrologueOffset)
369     return createStringError(errc::invalid_argument,
370                        "parsing line table prologue at 0x%8.8" PRIx64
371                        " should have ended at 0x%8.8" PRIx64
372                        " but it ended at 0x%8.8" PRIx64,
373                        PrologueOffset, EndPrologueOffset, *OffsetPtr);
374   return Error::success();
375 }
376 
377 DWARFDebugLine::Row::Row(bool DefaultIsStmt) { reset(DefaultIsStmt); }
378 
379 void DWARFDebugLine::Row::postAppend() {
380   Discriminator = 0;
381   BasicBlock = false;
382   PrologueEnd = false;
383   EpilogueBegin = false;
384 }
385 
386 void DWARFDebugLine::Row::reset(bool DefaultIsStmt) {
387   Address.Address = 0;
388   Address.SectionIndex = object::SectionedAddress::UndefSection;
389   Line = 1;
390   Column = 0;
391   File = 1;
392   Isa = 0;
393   Discriminator = 0;
394   IsStmt = DefaultIsStmt;
395   BasicBlock = false;
396   EndSequence = false;
397   PrologueEnd = false;
398   EpilogueBegin = false;
399 }
400 
401 void DWARFDebugLine::Row::dumpTableHeader(raw_ostream &OS) {
402   OS << "Address            Line   Column File   ISA Discriminator Flags\n"
403      << "------------------ ------ ------ ------ --- ------------- "
404         "-------------\n";
405 }
406 
407 void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
408   OS << format("0x%16.16" PRIx64 " %6u %6u", Address.Address, Line, Column)
409      << format(" %6u %3u %13u ", File, Isa, Discriminator)
410      << (IsStmt ? " is_stmt" : "") << (BasicBlock ? " basic_block" : "")
411      << (PrologueEnd ? " prologue_end" : "")
412      << (EpilogueBegin ? " epilogue_begin" : "")
413      << (EndSequence ? " end_sequence" : "") << '\n';
414 }
415 
416 DWARFDebugLine::Sequence::Sequence() { reset(); }
417 
418 void DWARFDebugLine::Sequence::reset() {
419   LowPC = 0;
420   HighPC = 0;
421   SectionIndex = object::SectionedAddress::UndefSection;
422   FirstRowIndex = 0;
423   LastRowIndex = 0;
424   Empty = true;
425 }
426 
427 DWARFDebugLine::LineTable::LineTable() { clear(); }
428 
429 void DWARFDebugLine::LineTable::dump(raw_ostream &OS,
430                                      DIDumpOptions DumpOptions) const {
431   Prologue.dump(OS, DumpOptions);
432 
433   if (!Rows.empty()) {
434     OS << '\n';
435     Row::dumpTableHeader(OS);
436     for (const Row &R : Rows) {
437       R.dump(OS);
438     }
439   }
440 
441   // Terminate the table with a final blank line to clearly delineate it from
442   // later dumps.
443   OS << '\n';
444 }
445 
446 void DWARFDebugLine::LineTable::clear() {
447   Prologue.clear();
448   Rows.clear();
449   Sequences.clear();
450 }
451 
452 DWARFDebugLine::ParsingState::ParsingState(struct LineTable *LT)
453     : LineTable(LT) {
454   resetRowAndSequence();
455 }
456 
457 void DWARFDebugLine::ParsingState::resetRowAndSequence() {
458   Row.reset(LineTable->Prologue.DefaultIsStmt);
459   Sequence.reset();
460 }
461 
462 void DWARFDebugLine::ParsingState::appendRowToMatrix() {
463   unsigned RowNumber = LineTable->Rows.size();
464   if (Sequence.Empty) {
465     // Record the beginning of instruction sequence.
466     Sequence.Empty = false;
467     Sequence.LowPC = Row.Address.Address;
468     Sequence.FirstRowIndex = RowNumber;
469   }
470   LineTable->appendRow(Row);
471   if (Row.EndSequence) {
472     // Record the end of instruction sequence.
473     Sequence.HighPC = Row.Address.Address;
474     Sequence.LastRowIndex = RowNumber + 1;
475     Sequence.SectionIndex = Row.Address.SectionIndex;
476     if (Sequence.isValid())
477       LineTable->appendSequence(Sequence);
478     Sequence.reset();
479   }
480   Row.postAppend();
481 }
482 
483 const DWARFDebugLine::LineTable *
484 DWARFDebugLine::getLineTable(uint64_t Offset) const {
485   LineTableConstIter Pos = LineTableMap.find(Offset);
486   if (Pos != LineTableMap.end())
487     return &Pos->second;
488   return nullptr;
489 }
490 
491 Expected<const DWARFDebugLine::LineTable *> DWARFDebugLine::getOrParseLineTable(
492     DWARFDataExtractor &DebugLineData, uint64_t Offset, const DWARFContext &Ctx,
493     const DWARFUnit *U, function_ref<void(Error)> RecoverableErrorCallback) {
494   if (!DebugLineData.isValidOffset(Offset))
495     return createStringError(errc::invalid_argument, "offset 0x%8.8" PRIx64
496                        " is not a valid debug line section offset",
497                        Offset);
498 
499   std::pair<LineTableIter, bool> Pos =
500       LineTableMap.insert(LineTableMapTy::value_type(Offset, LineTable()));
501   LineTable *LT = &Pos.first->second;
502   if (Pos.second) {
503     if (Error Err =
504             LT->parse(DebugLineData, &Offset, Ctx, U, RecoverableErrorCallback))
505       return std::move(Err);
506     return LT;
507   }
508   return LT;
509 }
510 
511 Error DWARFDebugLine::LineTable::parse(
512     DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr,
513     const DWARFContext &Ctx, const DWARFUnit *U,
514     function_ref<void(Error)> RecoverableErrorCallback, raw_ostream *OS) {
515   const uint64_t DebugLineOffset = *OffsetPtr;
516 
517   clear();
518 
519   Error PrologueErr = Prologue.parse(DebugLineData, OffsetPtr, Ctx, U);
520 
521   if (OS) {
522     // The presence of OS signals verbose dumping.
523     DIDumpOptions DumpOptions;
524     DumpOptions.Verbose = true;
525     Prologue.dump(*OS, DumpOptions);
526   }
527 
528   if (PrologueErr)
529     return PrologueErr;
530 
531   uint64_t ProgramLength = Prologue.TotalLength + Prologue.sizeofTotalLength();
532   if (!DebugLineData.isValidOffsetForDataOfSize(DebugLineOffset,
533                                                 ProgramLength)) {
534     assert(DebugLineData.size() > DebugLineOffset &&
535            "prologue parsing should handle invalid offset");
536     uint64_t BytesRemaining = DebugLineData.size() - DebugLineOffset;
537     RecoverableErrorCallback(
538         createStringError(errc::invalid_argument,
539                           "line table program with offset 0x%8.8" PRIx64
540                           " has length 0x%8.8" PRIx64 " but only 0x%8.8" PRIx64
541                           " bytes are available",
542                           DebugLineOffset, ProgramLength, BytesRemaining));
543     // Continue by capping the length at the number of remaining bytes.
544     ProgramLength = BytesRemaining;
545   }
546 
547   const uint64_t EndOffset = DebugLineOffset + ProgramLength;
548 
549   // See if we should tell the data extractor the address size.
550   if (DebugLineData.getAddressSize() == 0)
551     DebugLineData.setAddressSize(Prologue.getAddressSize());
552   else
553     assert(Prologue.getAddressSize() == 0 ||
554            Prologue.getAddressSize() == DebugLineData.getAddressSize());
555 
556   ParsingState State(this);
557 
558   while (*OffsetPtr < EndOffset) {
559     if (OS)
560       *OS << format("0x%08.08" PRIx64 ": ", *OffsetPtr);
561 
562     uint8_t Opcode = DebugLineData.getU8(OffsetPtr);
563 
564     if (OS)
565       *OS << format("%02.02" PRIx8 " ", Opcode);
566 
567     if (Opcode == 0) {
568       // Extended Opcodes always start with a zero opcode followed by
569       // a uleb128 length so you can skip ones you don't know about
570       uint64_t Len = DebugLineData.getULEB128(OffsetPtr);
571       uint64_t ExtOffset = *OffsetPtr;
572 
573       // Tolerate zero-length; assume length is correct and soldier on.
574       if (Len == 0) {
575         if (OS)
576           *OS << "Badly formed extended line op (length 0)\n";
577         continue;
578       }
579 
580       uint8_t SubOpcode = DebugLineData.getU8(OffsetPtr);
581       if (OS)
582         *OS << LNExtendedString(SubOpcode);
583       switch (SubOpcode) {
584       case DW_LNE_end_sequence:
585         // Set the end_sequence register of the state machine to true and
586         // append a row to the matrix using the current values of the
587         // state-machine registers. Then reset the registers to the initial
588         // values specified above. Every statement program sequence must end
589         // with a DW_LNE_end_sequence instruction which creates a row whose
590         // address is that of the byte after the last target machine instruction
591         // of the sequence.
592         State.Row.EndSequence = true;
593         if (OS) {
594           *OS << "\n";
595           OS->indent(12);
596           State.Row.dump(*OS);
597         }
598         State.appendRowToMatrix();
599         State.resetRowAndSequence();
600         break;
601 
602       case DW_LNE_set_address:
603         // Takes a single relocatable address as an operand. The size of the
604         // operand is the size appropriate to hold an address on the target
605         // machine. Set the address register to the value given by the
606         // relocatable address. All of the other statement program opcodes
607         // that affect the address register add a delta to it. This instruction
608         // stores a relocatable value into it instead.
609         //
610         // Make sure the extractor knows the address size.  If not, infer it
611         // from the size of the operand.
612         {
613           uint8_t ExtractorAddressSize = DebugLineData.getAddressSize();
614           if (ExtractorAddressSize != Len - 1 && ExtractorAddressSize != 0)
615             RecoverableErrorCallback(createStringError(
616                 errc::invalid_argument,
617                 "mismatching address size at offset 0x%8.8" PRIx64
618                 " expected 0x%2.2" PRIx8 " found 0x%2.2" PRIx64,
619                 ExtOffset, ExtractorAddressSize, Len - 1));
620 
621           // Assume that the line table is correct and temporarily override the
622           // address size.
623           DebugLineData.setAddressSize(Len - 1);
624           State.Row.Address.Address = DebugLineData.getRelocatedAddress(
625               OffsetPtr, &State.Row.Address.SectionIndex);
626 
627           // Restore the address size if the extractor already had it.
628           if (ExtractorAddressSize != 0)
629             DebugLineData.setAddressSize(ExtractorAddressSize);
630 
631           if (OS)
632             *OS << format(" (0x%16.16" PRIx64 ")", State.Row.Address.Address);
633         }
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(createStringError(
896         errc::illegal_byte_sequence,
897         "last sequence in debug line table at offset 0x%8.8" PRIx64
898         " is not terminated",
899         DebugLineOffset));
900 
901   // Sort all sequences so that address lookup will work faster.
902   if (!Sequences.empty()) {
903     llvm::sort(Sequences, Sequence::orderByHighPC);
904     // Note: actually, instruction address ranges of sequences should not
905     // overlap (in shared objects and executables). If they do, the address
906     // lookup would still work, though, but result would be ambiguous.
907     // We don't report warning in this case. For example,
908     // sometimes .so compiled from multiple object files contains a few
909     // rudimentary sequences for address ranges [0x0, 0xsomething).
910   }
911 
912   return Error::success();
913 }
914 
915 uint32_t DWARFDebugLine::LineTable::findRowInSeq(
916     const DWARFDebugLine::Sequence &Seq,
917     object::SectionedAddress Address) const {
918   if (!Seq.containsPC(Address))
919     return UnknownRowIndex;
920   assert(Seq.SectionIndex == Address.SectionIndex);
921   // In some cases, e.g. first instruction in a function, the compiler generates
922   // two entries, both with the same address. We want the last one.
923   //
924   // In general we want a non-empty range: the last row whose address is less
925   // than or equal to Address. This can be computed as upper_bound - 1.
926   DWARFDebugLine::Row Row;
927   Row.Address = Address;
928   RowIter FirstRow = Rows.begin() + Seq.FirstRowIndex;
929   RowIter LastRow = Rows.begin() + Seq.LastRowIndex;
930   assert(FirstRow->Address.Address <= Row.Address.Address &&
931          Row.Address.Address < LastRow[-1].Address.Address);
932   RowIter RowPos = std::upper_bound(FirstRow + 1, LastRow - 1, Row,
933                                     DWARFDebugLine::Row::orderByAddress) -
934                    1;
935   assert(Seq.SectionIndex == RowPos->Address.SectionIndex);
936   return RowPos - Rows.begin();
937 }
938 
939 uint32_t DWARFDebugLine::LineTable::lookupAddress(
940     object::SectionedAddress Address) const {
941 
942   // Search for relocatable addresses
943   uint32_t Result = lookupAddressImpl(Address);
944 
945   if (Result != UnknownRowIndex ||
946       Address.SectionIndex == object::SectionedAddress::UndefSection)
947     return Result;
948 
949   // Search for absolute addresses
950   Address.SectionIndex = object::SectionedAddress::UndefSection;
951   return lookupAddressImpl(Address);
952 }
953 
954 uint32_t DWARFDebugLine::LineTable::lookupAddressImpl(
955     object::SectionedAddress Address) const {
956   // First, find an instruction sequence containing the given address.
957   DWARFDebugLine::Sequence Sequence;
958   Sequence.SectionIndex = Address.SectionIndex;
959   Sequence.HighPC = Address.Address;
960   SequenceIter It = llvm::upper_bound(Sequences, Sequence,
961                                       DWARFDebugLine::Sequence::orderByHighPC);
962   if (It == Sequences.end() || It->SectionIndex != Address.SectionIndex)
963     return UnknownRowIndex;
964   return findRowInSeq(*It, Address);
965 }
966 
967 bool DWARFDebugLine::LineTable::lookupAddressRange(
968     object::SectionedAddress Address, uint64_t Size,
969     std::vector<uint32_t> &Result) const {
970 
971   // Search for relocatable addresses
972   if (lookupAddressRangeImpl(Address, Size, Result))
973     return true;
974 
975   if (Address.SectionIndex == object::SectionedAddress::UndefSection)
976     return false;
977 
978   // Search for absolute addresses
979   Address.SectionIndex = object::SectionedAddress::UndefSection;
980   return lookupAddressRangeImpl(Address, Size, Result);
981 }
982 
983 bool DWARFDebugLine::LineTable::lookupAddressRangeImpl(
984     object::SectionedAddress Address, uint64_t Size,
985     std::vector<uint32_t> &Result) const {
986   if (Sequences.empty())
987     return false;
988   uint64_t EndAddr = Address.Address + Size;
989   // First, find an instruction sequence containing the given address.
990   DWARFDebugLine::Sequence Sequence;
991   Sequence.SectionIndex = Address.SectionIndex;
992   Sequence.HighPC = Address.Address;
993   SequenceIter LastSeq = Sequences.end();
994   SequenceIter SeqPos = llvm::upper_bound(
995       Sequences, Sequence, DWARFDebugLine::Sequence::orderByHighPC);
996   if (SeqPos == LastSeq || !SeqPos->containsPC(Address))
997     return false;
998 
999   SequenceIter StartPos = SeqPos;
1000 
1001   // Add the rows from the first sequence to the vector, starting with the
1002   // index we just calculated
1003 
1004   while (SeqPos != LastSeq && SeqPos->LowPC < EndAddr) {
1005     const DWARFDebugLine::Sequence &CurSeq = *SeqPos;
1006     // For the first sequence, we need to find which row in the sequence is the
1007     // first in our range.
1008     uint32_t FirstRowIndex = CurSeq.FirstRowIndex;
1009     if (SeqPos == StartPos)
1010       FirstRowIndex = findRowInSeq(CurSeq, Address);
1011 
1012     // Figure out the last row in the range.
1013     uint32_t LastRowIndex =
1014         findRowInSeq(CurSeq, {EndAddr - 1, Address.SectionIndex});
1015     if (LastRowIndex == UnknownRowIndex)
1016       LastRowIndex = CurSeq.LastRowIndex - 1;
1017 
1018     assert(FirstRowIndex != UnknownRowIndex);
1019     assert(LastRowIndex != UnknownRowIndex);
1020 
1021     for (uint32_t I = FirstRowIndex; I <= LastRowIndex; ++I) {
1022       Result.push_back(I);
1023     }
1024 
1025     ++SeqPos;
1026   }
1027 
1028   return true;
1029 }
1030 
1031 Optional<StringRef> DWARFDebugLine::LineTable::getSourceByIndex(uint64_t FileIndex,
1032                                                                 FileLineInfoKind Kind) const {
1033   if (Kind == FileLineInfoKind::None || !Prologue.hasFileAtIndex(FileIndex))
1034     return None;
1035   const FileNameEntry &Entry = Prologue.getFileNameEntry(FileIndex);
1036   if (Optional<const char *> source = Entry.Source.getAsCString())
1037     return StringRef(*source);
1038   return None;
1039 }
1040 
1041 static bool isPathAbsoluteOnWindowsOrPosix(const Twine &Path) {
1042   // Debug info can contain paths from any OS, not necessarily
1043   // an OS we're currently running on. Moreover different compilation units can
1044   // be compiled on different operating systems and linked together later.
1045   return sys::path::is_absolute(Path, sys::path::Style::posix) ||
1046          sys::path::is_absolute(Path, sys::path::Style::windows);
1047 }
1048 
1049 bool DWARFDebugLine::Prologue::getFileNameByIndex(
1050     uint64_t FileIndex, StringRef CompDir, FileLineInfoKind Kind,
1051     std::string &Result, sys::path::Style Style) const {
1052   if (Kind == FileLineInfoKind::None || !hasFileAtIndex(FileIndex))
1053     return false;
1054   const FileNameEntry &Entry = getFileNameEntry(FileIndex);
1055   Optional<const char *> Name = Entry.Name.getAsCString();
1056   if (!Name)
1057     return false;
1058   StringRef FileName = *Name;
1059   if (Kind != FileLineInfoKind::AbsoluteFilePath ||
1060       isPathAbsoluteOnWindowsOrPosix(FileName)) {
1061     Result = FileName;
1062     return true;
1063   }
1064 
1065   SmallString<16> FilePath;
1066   StringRef IncludeDir;
1067   // Be defensive about the contents of Entry.
1068   if (getVersion() >= 5) {
1069     if (Entry.DirIdx < IncludeDirectories.size())
1070       IncludeDir = IncludeDirectories[Entry.DirIdx].getAsCString().getValue();
1071   } else {
1072     if (0 < Entry.DirIdx && Entry.DirIdx <= IncludeDirectories.size())
1073       IncludeDir =
1074           IncludeDirectories[Entry.DirIdx - 1].getAsCString().getValue();
1075 
1076     // We may still need to append compilation directory of compile unit.
1077     // We know that FileName is not absolute, the only way to have an
1078     // absolute path at this point would be if IncludeDir is absolute.
1079     if (!CompDir.empty() && !isPathAbsoluteOnWindowsOrPosix(IncludeDir))
1080       sys::path::append(FilePath, Style, CompDir);
1081   }
1082 
1083   // sys::path::append skips empty strings.
1084   sys::path::append(FilePath, Style, IncludeDir, FileName);
1085   Result = FilePath.str();
1086   return true;
1087 }
1088 
1089 bool DWARFDebugLine::LineTable::getFileLineInfoForAddress(
1090     object::SectionedAddress Address, const char *CompDir,
1091     FileLineInfoKind Kind, DILineInfo &Result) const {
1092   // Get the index of row we're looking for in the line table.
1093   uint32_t RowIndex = lookupAddress(Address);
1094   if (RowIndex == -1U)
1095     return false;
1096   // Take file number and line/column from the row.
1097   const auto &Row = Rows[RowIndex];
1098   if (!getFileNameByIndex(Row.File, CompDir, Kind, Result.FileName))
1099     return false;
1100   Result.Line = Row.Line;
1101   Result.Column = Row.Column;
1102   Result.Discriminator = Row.Discriminator;
1103   Result.Source = getSourceByIndex(Row.File, Kind);
1104   return true;
1105 }
1106 
1107 // We want to supply the Unit associated with a .debug_line[.dwo] table when
1108 // we dump it, if possible, but still dump the table even if there isn't a Unit.
1109 // Therefore, collect up handles on all the Units that point into the
1110 // line-table section.
1111 static DWARFDebugLine::SectionParser::LineToUnitMap
1112 buildLineToUnitMap(DWARFDebugLine::SectionParser::cu_range CUs,
1113                    DWARFDebugLine::SectionParser::tu_range TUs) {
1114   DWARFDebugLine::SectionParser::LineToUnitMap LineToUnit;
1115   for (const auto &CU : CUs)
1116     if (auto CUDIE = CU->getUnitDIE())
1117       if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list)))
1118         LineToUnit.insert(std::make_pair(*StmtOffset, &*CU));
1119   for (const auto &TU : TUs)
1120     if (auto TUDIE = TU->getUnitDIE())
1121       if (auto StmtOffset = toSectionOffset(TUDIE.find(DW_AT_stmt_list)))
1122         LineToUnit.insert(std::make_pair(*StmtOffset, &*TU));
1123   return LineToUnit;
1124 }
1125 
1126 DWARFDebugLine::SectionParser::SectionParser(DWARFDataExtractor &Data,
1127                                              const DWARFContext &C,
1128                                              cu_range CUs, tu_range TUs)
1129     : DebugLineData(Data), Context(C) {
1130   LineToUnit = buildLineToUnitMap(CUs, TUs);
1131   if (!DebugLineData.isValidOffset(Offset))
1132     Done = true;
1133 }
1134 
1135 bool DWARFDebugLine::Prologue::totalLengthIsValid() const {
1136   return TotalLength == dwarf::DW_LENGTH_DWARF64 ||
1137          TotalLength < dwarf::DW_LENGTH_lo_reserved;
1138 }
1139 
1140 DWARFDebugLine::LineTable DWARFDebugLine::SectionParser::parseNext(
1141     function_ref<void(Error)> RecoverableErrorCallback,
1142     function_ref<void(Error)> UnrecoverableErrorCallback, raw_ostream *OS) {
1143   assert(DebugLineData.isValidOffset(Offset) &&
1144          "parsing should have terminated");
1145   DWARFUnit *U = prepareToParse(Offset);
1146   uint64_t OldOffset = Offset;
1147   LineTable LT;
1148   if (Error Err = LT.parse(DebugLineData, &Offset, Context, U,
1149                            RecoverableErrorCallback, OS))
1150     UnrecoverableErrorCallback(std::move(Err));
1151   moveToNextTable(OldOffset, LT.Prologue);
1152   return LT;
1153 }
1154 
1155 void DWARFDebugLine::SectionParser::skip(
1156     function_ref<void(Error)> ErrorCallback) {
1157   assert(DebugLineData.isValidOffset(Offset) &&
1158          "parsing should have terminated");
1159   DWARFUnit *U = prepareToParse(Offset);
1160   uint64_t OldOffset = Offset;
1161   LineTable LT;
1162   if (Error Err = LT.Prologue.parse(DebugLineData, &Offset, Context, U))
1163     ErrorCallback(std::move(Err));
1164   moveToNextTable(OldOffset, LT.Prologue);
1165 }
1166 
1167 DWARFUnit *DWARFDebugLine::SectionParser::prepareToParse(uint64_t Offset) {
1168   DWARFUnit *U = nullptr;
1169   auto It = LineToUnit.find(Offset);
1170   if (It != LineToUnit.end())
1171     U = It->second;
1172   DebugLineData.setAddressSize(U ? U->getAddressByteSize() : 0);
1173   return U;
1174 }
1175 
1176 void DWARFDebugLine::SectionParser::moveToNextTable(uint64_t OldOffset,
1177                                                     const Prologue &P) {
1178   // If the length field is not valid, we don't know where the next table is, so
1179   // cannot continue to parse. Mark the parser as done, and leave the Offset
1180   // value as it currently is. This will be the end of the bad length field.
1181   if (!P.totalLengthIsValid()) {
1182     Done = true;
1183     return;
1184   }
1185 
1186   Offset = OldOffset + P.TotalLength + P.sizeofTotalLength();
1187   if (!DebugLineData.isValidOffset(Offset)) {
1188     Done = true;
1189   }
1190 }
1191