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