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