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