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                    uint64_t EndPrologueOffset,
194                    DWARFDebugLine::ContentTypeTracker *ContentTypes) {
195   ContentDescriptors Descriptors;
196   int FormatCount = DebugLineData.getU8(OffsetPtr);
197   bool HasPath = false;
198   for (int I = 0; I != FormatCount; ++I) {
199     ContentDescriptor Descriptor;
200     Descriptor.Type =
201       dwarf::LineNumberEntryFormat(DebugLineData.getULEB128(OffsetPtr));
202     Descriptor.Form = dwarf::Form(DebugLineData.getULEB128(OffsetPtr));
203     if (Descriptor.Type == dwarf::DW_LNCT_path)
204       HasPath = true;
205     if (ContentTypes)
206       ContentTypes->trackContentType(Descriptor.Type);
207     Descriptors.push_back(Descriptor);
208   }
209 
210   if (!HasPath)
211     return createStringError(errc::invalid_argument,
212                              "failed to parse entry content descriptions"
213                              " because no path was found");
214   return Descriptors;
215 }
216 
217 static Error
218 parseV5DirFileTables(const DWARFDataExtractor &DebugLineData,
219                      uint64_t *OffsetPtr, uint64_t EndPrologueOffset,
220                      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, EndPrologueOffset, 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 = parseV5EntryFormat(
255       DebugLineData, OffsetPtr, EndPrologueOffset, &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 = parseV5DirFileTables(
353             DebugLineData, OffsetPtr, EndPrologueOffset, 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         if (DebugLineData.getAddressSize() == 0)
613           DebugLineData.setAddressSize(Len - 1);
614         else if (DebugLineData.getAddressSize() != Len - 1) {
615           return createStringError(errc::invalid_argument,
616                              "mismatching address size at offset 0x%8.8" PRIx64
617                              " expected 0x%2.2" PRIx8 " found 0x%2.2" PRIx64,
618                              ExtOffset, DebugLineData.getAddressSize(),
619                              Len - 1);
620         }
621         State.Row.Address.Address = DebugLineData.getRelocatedAddress(
622             OffsetPtr, &State.Row.Address.SectionIndex);
623         if (OS)
624           *OS << format(" (0x%16.16" PRIx64 ")", State.Row.Address.Address);
625         break;
626 
627       case DW_LNE_define_file:
628         // Takes 4 arguments. The first is a null terminated string containing
629         // a source file name. The second is an unsigned LEB128 number
630         // representing the directory index of the directory in which the file
631         // was found. The third is an unsigned LEB128 number representing the
632         // time of last modification of the file. The fourth is an unsigned
633         // LEB128 number representing the length in bytes of the file. The time
634         // and length fields may contain LEB128(0) if the information is not
635         // available.
636         //
637         // The directory index represents an entry in the include_directories
638         // section of the statement program prologue. The index is LEB128(0)
639         // if the file was found in the current directory of the compilation,
640         // LEB128(1) if it was found in the first directory in the
641         // include_directories section, and so on. The directory index is
642         // ignored for file names that represent full path names.
643         //
644         // The files are numbered, starting at 1, in the order in which they
645         // appear; the names in the prologue come before names defined by
646         // the DW_LNE_define_file instruction. These numbers are used in the
647         // the file register of the state machine.
648         {
649           FileNameEntry FileEntry;
650           const char *Name = DebugLineData.getCStr(OffsetPtr);
651           FileEntry.Name =
652               DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, Name);
653           FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr);
654           FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr);
655           FileEntry.Length = DebugLineData.getULEB128(OffsetPtr);
656           Prologue.FileNames.push_back(FileEntry);
657           if (OS)
658             *OS << " (" << Name << ", dir=" << FileEntry.DirIdx << ", mod_time="
659                 << format("(0x%16.16" PRIx64 ")", FileEntry.ModTime)
660                 << ", length=" << FileEntry.Length << ")";
661         }
662         break;
663 
664       case DW_LNE_set_discriminator:
665         State.Row.Discriminator = DebugLineData.getULEB128(OffsetPtr);
666         if (OS)
667           *OS << " (" << State.Row.Discriminator << ")";
668         break;
669 
670       default:
671         if (OS)
672           *OS << format("Unrecognized extended op 0x%02.02" PRIx8, SubOpcode)
673               << format(" length %" PRIx64, Len);
674         // Len doesn't include the zero opcode byte or the length itself, but
675         // it does include the sub_opcode, so we have to adjust for that.
676         (*OffsetPtr) += Len - 1;
677         break;
678       }
679       // Make sure the stated and parsed lengths are the same.
680       // Otherwise we have an unparseable line-number program.
681       if (*OffsetPtr - ExtOffset != Len)
682         return createStringError(errc::illegal_byte_sequence,
683                            "unexpected line op length at offset 0x%8.8" PRIx64
684                            " expected 0x%2.2" PRIx64 " found 0x%2.2" PRIx64,
685                            ExtOffset, Len, *OffsetPtr - ExtOffset);
686     } else if (Opcode < Prologue.OpcodeBase) {
687       if (OS)
688         *OS << LNStandardString(Opcode);
689       switch (Opcode) {
690       // Standard Opcodes
691       case DW_LNS_copy:
692         // Takes no arguments. Append a row to the matrix using the
693         // current values of the state-machine registers.
694         if (OS) {
695           *OS << "\n";
696           OS->indent(12);
697           State.Row.dump(*OS);
698           *OS << "\n";
699         }
700         State.appendRowToMatrix();
701         break;
702 
703       case DW_LNS_advance_pc:
704         // Takes a single unsigned LEB128 operand, multiplies it by the
705         // min_inst_length field of the prologue, and adds the
706         // result to the address register of the state machine.
707         {
708           uint64_t AddrOffset =
709               DebugLineData.getULEB128(OffsetPtr) * Prologue.MinInstLength;
710           State.Row.Address.Address += AddrOffset;
711           if (OS)
712             *OS << " (" << AddrOffset << ")";
713         }
714         break;
715 
716       case DW_LNS_advance_line:
717         // Takes a single signed LEB128 operand and adds that value to
718         // the line register of the state machine.
719         State.Row.Line += DebugLineData.getSLEB128(OffsetPtr);
720         if (OS)
721           *OS << " (" << State.Row.Line << ")";
722         break;
723 
724       case DW_LNS_set_file:
725         // Takes a single unsigned LEB128 operand and stores it in the file
726         // register of the state machine.
727         State.Row.File = DebugLineData.getULEB128(OffsetPtr);
728         if (OS)
729           *OS << " (" << State.Row.File << ")";
730         break;
731 
732       case DW_LNS_set_column:
733         // Takes a single unsigned LEB128 operand and stores it in the
734         // column register of the state machine.
735         State.Row.Column = DebugLineData.getULEB128(OffsetPtr);
736         if (OS)
737           *OS << " (" << State.Row.Column << ")";
738         break;
739 
740       case DW_LNS_negate_stmt:
741         // Takes no arguments. Set the is_stmt register of the state
742         // machine to the logical negation of its current value.
743         State.Row.IsStmt = !State.Row.IsStmt;
744         break;
745 
746       case DW_LNS_set_basic_block:
747         // Takes no arguments. Set the basic_block register of the
748         // state machine to true
749         State.Row.BasicBlock = true;
750         break;
751 
752       case DW_LNS_const_add_pc:
753         // Takes no arguments. Add to the address register of the state
754         // machine the address increment value corresponding to special
755         // opcode 255. The motivation for DW_LNS_const_add_pc is this:
756         // when the statement program needs to advance the address by a
757         // small amount, it can use a single special opcode, which occupies
758         // a single byte. When it needs to advance the address by up to
759         // twice the range of the last special opcode, it can use
760         // DW_LNS_const_add_pc followed by a special opcode, for a total
761         // of two bytes. Only if it needs to advance the address by more
762         // than twice that range will it need to use both DW_LNS_advance_pc
763         // and a special opcode, requiring three or more bytes.
764         {
765           uint8_t AdjustOpcode = 255 - Prologue.OpcodeBase;
766           uint64_t AddrOffset =
767               (AdjustOpcode / Prologue.LineRange) * Prologue.MinInstLength;
768           State.Row.Address.Address += AddrOffset;
769           if (OS)
770             *OS
771                 << format(" (0x%16.16" PRIx64 ")", AddrOffset);
772         }
773         break;
774 
775       case DW_LNS_fixed_advance_pc:
776         // Takes a single uhalf operand. Add to the address register of
777         // the state machine the value of the (unencoded) operand. This
778         // is the only extended opcode that takes an argument that is not
779         // a variable length number. The motivation for DW_LNS_fixed_advance_pc
780         // is this: existing assemblers cannot emit DW_LNS_advance_pc or
781         // special opcodes because they cannot encode LEB128 numbers or
782         // judge when the computation of a special opcode overflows and
783         // requires the use of DW_LNS_advance_pc. Such assemblers, however,
784         // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
785         {
786           uint16_t PCOffset = DebugLineData.getRelocatedValue(2, OffsetPtr);
787           State.Row.Address.Address += PCOffset;
788           if (OS)
789             *OS
790                 << format(" (0x%4.4" PRIx16 ")", PCOffset);
791         }
792         break;
793 
794       case DW_LNS_set_prologue_end:
795         // Takes no arguments. Set the prologue_end register of the
796         // state machine to true
797         State.Row.PrologueEnd = true;
798         break;
799 
800       case DW_LNS_set_epilogue_begin:
801         // Takes no arguments. Set the basic_block register of the
802         // state machine to true
803         State.Row.EpilogueBegin = true;
804         break;
805 
806       case DW_LNS_set_isa:
807         // Takes a single unsigned LEB128 operand and stores it in the
808         // column register of the state machine.
809         State.Row.Isa = DebugLineData.getULEB128(OffsetPtr);
810         if (OS)
811           *OS << " (" << (uint64_t)State.Row.Isa << ")";
812         break;
813 
814       default:
815         // Handle any unknown standard opcodes here. We know the lengths
816         // of such opcodes because they are specified in the prologue
817         // as a multiple of LEB128 operands for each opcode.
818         {
819           assert(Opcode - 1U < Prologue.StandardOpcodeLengths.size());
820           uint8_t OpcodeLength = Prologue.StandardOpcodeLengths[Opcode - 1];
821           for (uint8_t I = 0; I < OpcodeLength; ++I) {
822             uint64_t Value = DebugLineData.getULEB128(OffsetPtr);
823             if (OS)
824               *OS << format("Skipping ULEB128 value: 0x%16.16" PRIx64 ")\n",
825                             Value);
826           }
827         }
828         break;
829       }
830     } else {
831       // Special Opcodes
832 
833       // A special opcode value is chosen based on the amount that needs
834       // to be added to the line and address registers. The maximum line
835       // increment for a special opcode is the value of the line_base
836       // field in the header, plus the value of the line_range field,
837       // minus 1 (line base + line range - 1). If the desired line
838       // increment is greater than the maximum line increment, a standard
839       // opcode must be used instead of a special opcode. The "address
840       // advance" is calculated by dividing the desired address increment
841       // by the minimum_instruction_length field from the header. The
842       // special opcode is then calculated using the following formula:
843       //
844       //  opcode = (desired line increment - line_base) +
845       //           (line_range * address advance) + opcode_base
846       //
847       // If the resulting opcode is greater than 255, a standard opcode
848       // must be used instead.
849       //
850       // To decode a special opcode, subtract the opcode_base from the
851       // opcode itself to give the adjusted opcode. The amount to
852       // increment the address register is the result of the adjusted
853       // opcode divided by the line_range multiplied by the
854       // minimum_instruction_length field from the header. That is:
855       //
856       //  address increment = (adjusted opcode / line_range) *
857       //                      minimum_instruction_length
858       //
859       // The amount to increment the line register is the line_base plus
860       // the result of the adjusted opcode modulo the line_range. That is:
861       //
862       // line increment = line_base + (adjusted opcode % line_range)
863 
864       uint8_t AdjustOpcode = Opcode - Prologue.OpcodeBase;
865       uint64_t AddrOffset =
866           (AdjustOpcode / Prologue.LineRange) * Prologue.MinInstLength;
867       int32_t LineOffset =
868           Prologue.LineBase + (AdjustOpcode % Prologue.LineRange);
869       State.Row.Line += LineOffset;
870       State.Row.Address.Address += AddrOffset;
871 
872       if (OS) {
873         *OS << "address += " << AddrOffset << ",  line += " << LineOffset
874             << "\n";
875         OS->indent(12);
876         State.Row.dump(*OS);
877       }
878 
879       State.appendRowToMatrix();
880     }
881     if(OS)
882       *OS << "\n";
883   }
884 
885   if (!State.Sequence.Empty)
886     RecoverableErrorCallback(
887         createStringError(errc::illegal_byte_sequence,
888                     "last sequence in debug line table is not terminated!"));
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