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