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   bool Terminated = false;
173   while (*OffsetPtr < EndPrologueOffset) {
174     StringRef S = DebugLineData.getCStrRef(OffsetPtr);
175     if (S.empty()) {
176       Terminated = true;
177       break;
178     }
179     DWARFFormValue Dir =
180         DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, S.data());
181     IncludeDirectories.push_back(Dir);
182   }
183 
184   if (!Terminated)
185     return createStringError(errc::invalid_argument,
186                              "include directories table was not null "
187                              "terminated before the end of the prologue");
188 
189   Terminated = false;
190   while (*OffsetPtr < EndPrologueOffset) {
191     StringRef Name = DebugLineData.getCStrRef(OffsetPtr);
192     if (Name.empty()) {
193       Terminated = true;
194       break;
195     }
196     DWARFDebugLine::FileNameEntry FileEntry;
197     FileEntry.Name =
198         DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, Name.data());
199     FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr);
200     FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr);
201     FileEntry.Length = DebugLineData.getULEB128(OffsetPtr);
202     FileNames.push_back(FileEntry);
203   }
204 
205   ContentTypes.HasModTime = true;
206   ContentTypes.HasLength = true;
207 
208   if (!Terminated)
209     return createStringError(errc::invalid_argument,
210                              "file names table was not null terminated before "
211                              "the end of the prologue");
212 
213   return Error::success();
214 }
215 
216 // Parse v5 directory/file entry content descriptions.
217 // Returns the descriptors, or an error if we did not find a path or ran off
218 // the end of the prologue.
219 static llvm::Expected<ContentDescriptors>
220 parseV5EntryFormat(const DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr,
221                    DWARFDebugLine::ContentTypeTracker *ContentTypes) {
222   ContentDescriptors Descriptors;
223   int FormatCount = DebugLineData.getU8(OffsetPtr);
224   bool HasPath = false;
225   for (int I = 0; I != FormatCount; ++I) {
226     ContentDescriptor Descriptor;
227     Descriptor.Type =
228       dwarf::LineNumberEntryFormat(DebugLineData.getULEB128(OffsetPtr));
229     Descriptor.Form = dwarf::Form(DebugLineData.getULEB128(OffsetPtr));
230     if (Descriptor.Type == dwarf::DW_LNCT_path)
231       HasPath = true;
232     if (ContentTypes)
233       ContentTypes->trackContentType(Descriptor.Type);
234     Descriptors.push_back(Descriptor);
235   }
236 
237   if (!HasPath)
238     return createStringError(errc::invalid_argument,
239                              "failed to parse entry content descriptions"
240                              " because no path was found");
241   return Descriptors;
242 }
243 
244 static Error
245 parseV5DirFileTables(const DWARFDataExtractor &DebugLineData,
246                      uint64_t *OffsetPtr, const dwarf::FormParams &FormParams,
247                      const DWARFContext &Ctx, const DWARFUnit *U,
248                      DWARFDebugLine::ContentTypeTracker &ContentTypes,
249                      std::vector<DWARFFormValue> &IncludeDirectories,
250                      std::vector<DWARFDebugLine::FileNameEntry> &FileNames) {
251   // Get the directory entry description.
252   llvm::Expected<ContentDescriptors> DirDescriptors =
253       parseV5EntryFormat(DebugLineData, OffsetPtr, nullptr);
254   if (!DirDescriptors)
255     return DirDescriptors.takeError();
256 
257   // Get the directory entries, according to the format described above.
258   int DirEntryCount = DebugLineData.getU8(OffsetPtr);
259   for (int I = 0; I != DirEntryCount; ++I) {
260     for (auto Descriptor : *DirDescriptors) {
261       DWARFFormValue Value(Descriptor.Form);
262       switch (Descriptor.Type) {
263       case DW_LNCT_path:
264         if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U))
265           return createStringError(errc::invalid_argument,
266                                    "failed to parse directory entry because "
267                                    "extracting the form value failed.");
268         IncludeDirectories.push_back(Value);
269         break;
270       default:
271         if (!Value.skipValue(DebugLineData, OffsetPtr, FormParams))
272           return createStringError(errc::invalid_argument,
273                                    "failed to parse directory entry because "
274                                    "skipping the form value failed.");
275       }
276     }
277   }
278 
279   // Get the file entry description.
280   llvm::Expected<ContentDescriptors> FileDescriptors =
281       parseV5EntryFormat(DebugLineData, OffsetPtr, &ContentTypes);
282   if (!FileDescriptors)
283     return FileDescriptors.takeError();
284 
285   // Get the file entries, according to the format described above.
286   int FileEntryCount = DebugLineData.getU8(OffsetPtr);
287   for (int I = 0; I != FileEntryCount; ++I) {
288     DWARFDebugLine::FileNameEntry FileEntry;
289     for (auto Descriptor : *FileDescriptors) {
290       DWARFFormValue Value(Descriptor.Form);
291       if (!Value.extractValue(DebugLineData, OffsetPtr, FormParams, &Ctx, U))
292         return createStringError(errc::invalid_argument,
293                                  "failed to parse file entry because "
294                                  "extracting the form value failed.");
295       switch (Descriptor.Type) {
296       case DW_LNCT_path:
297         FileEntry.Name = Value;
298         break;
299       case DW_LNCT_LLVM_source:
300         FileEntry.Source = Value;
301         break;
302       case DW_LNCT_directory_index:
303         FileEntry.DirIdx = Value.getAsUnsignedConstant().getValue();
304         break;
305       case DW_LNCT_timestamp:
306         FileEntry.ModTime = Value.getAsUnsignedConstant().getValue();
307         break;
308       case DW_LNCT_size:
309         FileEntry.Length = Value.getAsUnsignedConstant().getValue();
310         break;
311       case DW_LNCT_MD5:
312         if (!Value.getAsBlock() || Value.getAsBlock().getValue().size() != 16)
313           return createStringError(
314               errc::invalid_argument,
315               "failed to parse file entry because the MD5 hash is invalid");
316         std::uninitialized_copy_n(Value.getAsBlock().getValue().begin(), 16,
317                                   FileEntry.Checksum.Bytes.begin());
318         break;
319       default:
320         break;
321       }
322     }
323     FileNames.push_back(FileEntry);
324   }
325   return Error::success();
326 }
327 
328 uint64_t DWARFDebugLine::Prologue::getLength() const {
329   uint64_t Length = PrologueLength + sizeofTotalLength() +
330                     sizeof(getVersion()) + sizeofPrologueLength();
331   if (getVersion() >= 5)
332     Length += 2; // Address + Segment selector sizes.
333   return Length;
334 }
335 
336 Error DWARFDebugLine::Prologue::parse(
337     const DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr,
338     function_ref<void(Error)> RecoverableErrorHandler, const DWARFContext &Ctx,
339     const DWARFUnit *U) {
340   const uint64_t PrologueOffset = *OffsetPtr;
341 
342   clear();
343   Error Err = Error::success();
344   std::tie(TotalLength, FormParams.Format) =
345       DebugLineData.getInitialLength(OffsetPtr, &Err);
346   if (Err)
347     return createStringError(
348         errc::invalid_argument,
349         "parsing line table prologue at offset 0x%8.8" PRIx64 ": %s",
350         PrologueOffset, toString(std::move(Err)).c_str());
351 
352   FormParams.Version = DebugLineData.getU16(OffsetPtr);
353   if (!versionIsSupported(getVersion()))
354     // Treat this error as unrecoverable - we cannot be sure what any of
355     // the data represents including the length field, so cannot skip it or make
356     // any reasonable assumptions.
357     return createStringError(
358         errc::not_supported,
359         "parsing line table prologue at offset 0x%8.8" PRIx64
360         ": unsupported version %" PRIu16,
361         PrologueOffset, getVersion());
362 
363   if (getVersion() >= 5) {
364     FormParams.AddrSize = DebugLineData.getU8(OffsetPtr);
365     assert((DebugLineData.getAddressSize() == 0 ||
366             DebugLineData.getAddressSize() == getAddressSize()) &&
367            "Line table header and data extractor disagree");
368     SegSelectorSize = DebugLineData.getU8(OffsetPtr);
369   }
370 
371   PrologueLength =
372       DebugLineData.getRelocatedValue(sizeofPrologueLength(), OffsetPtr);
373   const uint64_t EndPrologueOffset = PrologueLength + *OffsetPtr;
374   MinInstLength = DebugLineData.getU8(OffsetPtr);
375   if (getVersion() >= 4)
376     MaxOpsPerInst = DebugLineData.getU8(OffsetPtr);
377   DefaultIsStmt = DebugLineData.getU8(OffsetPtr);
378   LineBase = DebugLineData.getU8(OffsetPtr);
379   LineRange = DebugLineData.getU8(OffsetPtr);
380   OpcodeBase = DebugLineData.getU8(OffsetPtr);
381 
382   if (OpcodeBase == 0) {
383     // If the opcode base is 0, we cannot read the standard opcode lengths (of
384     // which there are supposed to be one fewer than the opcode base). Assume
385     // there are no standard opcodes and continue parsing.
386     RecoverableErrorHandler(createStringError(
387         errc::invalid_argument,
388         "parsing line table prologue at offset 0x%8.8" PRIx64
389         " found opcode base of 0. Assuming no standard opcodes",
390         PrologueOffset));
391   } else {
392     StandardOpcodeLengths.reserve(OpcodeBase - 1);
393     for (uint32_t I = 1; I < OpcodeBase; ++I) {
394       uint8_t OpLen = DebugLineData.getU8(OffsetPtr);
395       StandardOpcodeLengths.push_back(OpLen);
396     }
397   }
398 
399   auto ReportInvalidDirFileTable = [&](Error E) {
400     RecoverableErrorHandler(joinErrors(
401         createStringError(
402             errc::invalid_argument,
403             "parsing line table prologue at 0x%8.8" PRIx64
404             " found an invalid directory or file table description at"
405             " 0x%8.8" PRIx64,
406             PrologueOffset, *OffsetPtr),
407         std::move(E)));
408     // Skip to the end of the prologue, since the chances are that the parser
409     // did not read the whole table. This prevents the length check below from
410     // executing.
411     if (*OffsetPtr < EndPrologueOffset)
412       *OffsetPtr = EndPrologueOffset;
413   };
414   if (getVersion() >= 5) {
415     if (Error E =
416             parseV5DirFileTables(DebugLineData, OffsetPtr, FormParams, Ctx, U,
417                                  ContentTypes, IncludeDirectories, FileNames))
418       ReportInvalidDirFileTable(std::move(E));
419   } else if (Error E = parseV2DirFileTables(DebugLineData, OffsetPtr,
420                                             EndPrologueOffset, ContentTypes,
421                                             IncludeDirectories, FileNames))
422     ReportInvalidDirFileTable(std::move(E));
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   while (*OffsetPtr < EndOffset) {
733     if (OS)
734       *OS << format("0x%08.08" PRIx64 ": ", *OffsetPtr);
735 
736     uint64_t OpcodeOffset = *OffsetPtr;
737     uint8_t Opcode = DebugLineData.getU8(OffsetPtr);
738 
739     if (OS)
740       *OS << format("%02.02" PRIx8 " ", Opcode);
741 
742     if (Opcode == 0) {
743       // Extended Opcodes always start with a zero opcode followed by
744       // a uleb128 length so you can skip ones you don't know about
745       uint64_t Len = DebugLineData.getULEB128(OffsetPtr);
746       uint64_t ExtOffset = *OffsetPtr;
747 
748       // Tolerate zero-length; assume length is correct and soldier on.
749       if (Len == 0) {
750         if (OS)
751           *OS << "Badly formed extended line op (length 0)\n";
752         continue;
753       }
754 
755       uint8_t SubOpcode = DebugLineData.getU8(OffsetPtr);
756       if (OS)
757         *OS << LNExtendedString(SubOpcode);
758       switch (SubOpcode) {
759       case DW_LNE_end_sequence:
760         // Set the end_sequence register of the state machine to true and
761         // append a row to the matrix using the current values of the
762         // state-machine registers. Then reset the registers to the initial
763         // values specified above. Every statement program sequence must end
764         // with a DW_LNE_end_sequence instruction which creates a row whose
765         // address is that of the byte after the last target machine instruction
766         // of the sequence.
767         State.Row.EndSequence = true;
768         if (OS) {
769           *OS << "\n";
770           OS->indent(12);
771           State.Row.dump(*OS);
772         }
773         State.appendRowToMatrix();
774         State.resetRowAndSequence();
775         break;
776 
777       case DW_LNE_set_address:
778         // Takes a single relocatable address as an operand. The size of the
779         // operand is the size appropriate to hold an address on the target
780         // machine. Set the address register to the value given by the
781         // relocatable address. All of the other statement program opcodes
782         // that affect the address register add a delta to it. This instruction
783         // stores a relocatable value into it instead.
784         //
785         // Make sure the extractor knows the address size.  If not, infer it
786         // from the size of the operand.
787         {
788           uint8_t ExtractorAddressSize = DebugLineData.getAddressSize();
789           uint64_t OpcodeAddressSize = Len - 1;
790           if (ExtractorAddressSize != OpcodeAddressSize &&
791               ExtractorAddressSize != 0)
792             RecoverableErrorHandler(createStringError(
793                 errc::invalid_argument,
794                 "mismatching address size at offset 0x%8.8" PRIx64
795                 " expected 0x%2.2" PRIx8 " found 0x%2.2" PRIx64,
796                 ExtOffset, ExtractorAddressSize, Len - 1));
797 
798           // Assume that the line table is correct and temporarily override the
799           // address size. If the size is unsupported, give up trying to read
800           // the address and continue to the next opcode.
801           if (OpcodeAddressSize != 1 && OpcodeAddressSize != 2 &&
802               OpcodeAddressSize != 4 && OpcodeAddressSize != 8) {
803             RecoverableErrorHandler(createStringError(
804                 errc::invalid_argument,
805                 "address size 0x%2.2" PRIx64
806                 " of DW_LNE_set_address opcode at offset 0x%8.8" PRIx64
807                 " is unsupported",
808                 OpcodeAddressSize, ExtOffset));
809             *OffsetPtr += OpcodeAddressSize;
810           } else {
811             DebugLineData.setAddressSize(OpcodeAddressSize);
812             State.Row.Address.Address = DebugLineData.getRelocatedAddress(
813                 OffsetPtr, &State.Row.Address.SectionIndex);
814 
815             // Restore the address size if the extractor already had it.
816             if (ExtractorAddressSize != 0)
817               DebugLineData.setAddressSize(ExtractorAddressSize);
818           }
819 
820           if (OS)
821             *OS << format(" (0x%16.16" PRIx64 ")", State.Row.Address.Address);
822         }
823         break;
824 
825       case DW_LNE_define_file:
826         // Takes 4 arguments. The first is a null terminated string containing
827         // a source file name. The second is an unsigned LEB128 number
828         // representing the directory index of the directory in which the file
829         // was found. The third is an unsigned LEB128 number representing the
830         // time of last modification of the file. The fourth is an unsigned
831         // LEB128 number representing the length in bytes of the file. The time
832         // and length fields may contain LEB128(0) if the information is not
833         // available.
834         //
835         // The directory index represents an entry in the include_directories
836         // section of the statement program prologue. The index is LEB128(0)
837         // if the file was found in the current directory of the compilation,
838         // LEB128(1) if it was found in the first directory in the
839         // include_directories section, and so on. The directory index is
840         // ignored for file names that represent full path names.
841         //
842         // The files are numbered, starting at 1, in the order in which they
843         // appear; the names in the prologue come before names defined by
844         // the DW_LNE_define_file instruction. These numbers are used in the
845         // the file register of the state machine.
846         {
847           FileNameEntry FileEntry;
848           const char *Name = DebugLineData.getCStr(OffsetPtr);
849           FileEntry.Name =
850               DWARFFormValue::createFromPValue(dwarf::DW_FORM_string, Name);
851           FileEntry.DirIdx = DebugLineData.getULEB128(OffsetPtr);
852           FileEntry.ModTime = DebugLineData.getULEB128(OffsetPtr);
853           FileEntry.Length = DebugLineData.getULEB128(OffsetPtr);
854           Prologue.FileNames.push_back(FileEntry);
855           if (OS)
856             *OS << " (" << Name << ", dir=" << FileEntry.DirIdx << ", mod_time="
857                 << format("(0x%16.16" PRIx64 ")", FileEntry.ModTime)
858                 << ", length=" << FileEntry.Length << ")";
859         }
860         break;
861 
862       case DW_LNE_set_discriminator:
863         State.Row.Discriminator = DebugLineData.getULEB128(OffsetPtr);
864         if (OS)
865           *OS << " (" << State.Row.Discriminator << ")";
866         break;
867 
868       default:
869         if (OS)
870           *OS << format("Unrecognized extended op 0x%02.02" PRIx8, SubOpcode)
871               << format(" length %" PRIx64, Len);
872         // Len doesn't include the zero opcode byte or the length itself, but
873         // it does include the sub_opcode, so we have to adjust for that.
874         (*OffsetPtr) += Len - 1;
875         break;
876       }
877       // Make sure the length as recorded in the table and the standard length
878       // for the opcode match. If they don't, continue from the end as claimed
879       // by the table.
880       uint64_t End = ExtOffset + Len;
881       if (*OffsetPtr != End) {
882         RecoverableErrorHandler(createStringError(
883             errc::illegal_byte_sequence,
884             "unexpected line op length at offset 0x%8.8" PRIx64
885             " expected 0x%2.2" PRIx64 " found 0x%2.2" PRIx64,
886             ExtOffset, Len, *OffsetPtr - ExtOffset));
887         *OffsetPtr = End;
888       }
889     } else if (Opcode < Prologue.OpcodeBase) {
890       if (OS)
891         *OS << LNStandardString(Opcode);
892       switch (Opcode) {
893       // Standard Opcodes
894       case DW_LNS_copy:
895         // Takes no arguments. Append a row to the matrix using the
896         // current values of the state-machine registers.
897         if (OS) {
898           *OS << "\n";
899           OS->indent(12);
900           State.Row.dump(*OS);
901           *OS << "\n";
902         }
903         State.appendRowToMatrix();
904         break;
905 
906       case DW_LNS_advance_pc:
907         // Takes a single unsigned LEB128 operand, multiplies it by the
908         // min_inst_length field of the prologue, and adds the
909         // result to the address register of the state machine.
910         {
911           uint64_t AddrOffset = State.advanceAddr(
912               DebugLineData.getULEB128(OffsetPtr), Opcode, OpcodeOffset);
913           if (OS)
914             *OS << " (" << AddrOffset << ")";
915         }
916         break;
917 
918       case DW_LNS_advance_line:
919         // Takes a single signed LEB128 operand and adds that value to
920         // the line register of the state machine.
921         State.Row.Line += DebugLineData.getSLEB128(OffsetPtr);
922         if (OS)
923           *OS << " (" << State.Row.Line << ")";
924         break;
925 
926       case DW_LNS_set_file:
927         // Takes a single unsigned LEB128 operand and stores it in the file
928         // register of the state machine.
929         State.Row.File = DebugLineData.getULEB128(OffsetPtr);
930         if (OS)
931           *OS << " (" << State.Row.File << ")";
932         break;
933 
934       case DW_LNS_set_column:
935         // Takes a single unsigned LEB128 operand and stores it in the
936         // column register of the state machine.
937         State.Row.Column = DebugLineData.getULEB128(OffsetPtr);
938         if (OS)
939           *OS << " (" << State.Row.Column << ")";
940         break;
941 
942       case DW_LNS_negate_stmt:
943         // Takes no arguments. Set the is_stmt register of the state
944         // machine to the logical negation of its current value.
945         State.Row.IsStmt = !State.Row.IsStmt;
946         break;
947 
948       case DW_LNS_set_basic_block:
949         // Takes no arguments. Set the basic_block register of the
950         // state machine to true
951         State.Row.BasicBlock = true;
952         break;
953 
954       case DW_LNS_const_add_pc:
955         // Takes no arguments. Add to the address register of the state
956         // machine the address increment value corresponding to special
957         // opcode 255. The motivation for DW_LNS_const_add_pc is this:
958         // when the statement program needs to advance the address by a
959         // small amount, it can use a single special opcode, which occupies
960         // a single byte. When it needs to advance the address by up to
961         // twice the range of the last special opcode, it can use
962         // DW_LNS_const_add_pc followed by a special opcode, for a total
963         // of two bytes. Only if it needs to advance the address by more
964         // than twice that range will it need to use both DW_LNS_advance_pc
965         // and a special opcode, requiring three or more bytes.
966         {
967           uint64_t AddrOffset =
968               State.advanceAddrForOpcode(Opcode, OpcodeOffset).AddrDelta;
969           if (OS)
970             *OS << format(" (0x%16.16" PRIx64 ")", AddrOffset);
971         }
972         break;
973 
974       case DW_LNS_fixed_advance_pc:
975         // Takes a single uhalf operand. Add to the address register of
976         // the state machine the value of the (unencoded) operand. This
977         // is the only extended opcode that takes an argument that is not
978         // a variable length number. The motivation for DW_LNS_fixed_advance_pc
979         // is this: existing assemblers cannot emit DW_LNS_advance_pc or
980         // special opcodes because they cannot encode LEB128 numbers or
981         // judge when the computation of a special opcode overflows and
982         // requires the use of DW_LNS_advance_pc. Such assemblers, however,
983         // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
984         {
985           uint16_t PCOffset = DebugLineData.getRelocatedValue(2, OffsetPtr);
986           State.Row.Address.Address += PCOffset;
987           if (OS)
988             *OS
989                 << format(" (0x%4.4" PRIx16 ")", PCOffset);
990         }
991         break;
992 
993       case DW_LNS_set_prologue_end:
994         // Takes no arguments. Set the prologue_end register of the
995         // state machine to true
996         State.Row.PrologueEnd = true;
997         break;
998 
999       case DW_LNS_set_epilogue_begin:
1000         // Takes no arguments. Set the basic_block register of the
1001         // state machine to true
1002         State.Row.EpilogueBegin = true;
1003         break;
1004 
1005       case DW_LNS_set_isa:
1006         // Takes a single unsigned LEB128 operand and stores it in the
1007         // column register of the state machine.
1008         State.Row.Isa = DebugLineData.getULEB128(OffsetPtr);
1009         if (OS)
1010           *OS << " (" << (uint64_t)State.Row.Isa << ")";
1011         break;
1012 
1013       default:
1014         // Handle any unknown standard opcodes here. We know the lengths
1015         // of such opcodes because they are specified in the prologue
1016         // as a multiple of LEB128 operands for each opcode.
1017         {
1018           assert(Opcode - 1U < Prologue.StandardOpcodeLengths.size());
1019           uint8_t OpcodeLength = Prologue.StandardOpcodeLengths[Opcode - 1];
1020           for (uint8_t I = 0; I < OpcodeLength; ++I) {
1021             uint64_t Value = DebugLineData.getULEB128(OffsetPtr);
1022             if (OS)
1023               *OS << format("Skipping ULEB128 value: 0x%16.16" PRIx64 ")\n",
1024                             Value);
1025           }
1026         }
1027         break;
1028       }
1029     } else {
1030       // Special Opcodes.
1031       ParsingState::AddrAndLineDelta Delta =
1032           State.handleSpecialOpcode(Opcode, OpcodeOffset);
1033 
1034       if (OS) {
1035         *OS << "address += " << Delta.Address << ",  line += " << Delta.Line
1036             << "\n";
1037         OS->indent(12);
1038         State.Row.dump(*OS);
1039       }
1040 
1041       State.appendRowToMatrix();
1042     }
1043     if(OS)
1044       *OS << "\n";
1045   }
1046 
1047   if (!State.Sequence.Empty)
1048     RecoverableErrorHandler(createStringError(
1049         errc::illegal_byte_sequence,
1050         "last sequence in debug line table at offset 0x%8.8" PRIx64
1051         " is not terminated",
1052         DebugLineOffset));
1053 
1054   // Sort all sequences so that address lookup will work faster.
1055   if (!Sequences.empty()) {
1056     llvm::sort(Sequences, Sequence::orderByHighPC);
1057     // Note: actually, instruction address ranges of sequences should not
1058     // overlap (in shared objects and executables). If they do, the address
1059     // lookup would still work, though, but result would be ambiguous.
1060     // We don't report warning in this case. For example,
1061     // sometimes .so compiled from multiple object files contains a few
1062     // rudimentary sequences for address ranges [0x0, 0xsomething).
1063   }
1064 
1065   return Error::success();
1066 }
1067 
1068 uint32_t DWARFDebugLine::LineTable::findRowInSeq(
1069     const DWARFDebugLine::Sequence &Seq,
1070     object::SectionedAddress Address) const {
1071   if (!Seq.containsPC(Address))
1072     return UnknownRowIndex;
1073   assert(Seq.SectionIndex == Address.SectionIndex);
1074   // In some cases, e.g. first instruction in a function, the compiler generates
1075   // two entries, both with the same address. We want the last one.
1076   //
1077   // In general we want a non-empty range: the last row whose address is less
1078   // than or equal to Address. This can be computed as upper_bound - 1.
1079   DWARFDebugLine::Row Row;
1080   Row.Address = Address;
1081   RowIter FirstRow = Rows.begin() + Seq.FirstRowIndex;
1082   RowIter LastRow = Rows.begin() + Seq.LastRowIndex;
1083   assert(FirstRow->Address.Address <= Row.Address.Address &&
1084          Row.Address.Address < LastRow[-1].Address.Address);
1085   RowIter RowPos = std::upper_bound(FirstRow + 1, LastRow - 1, Row,
1086                                     DWARFDebugLine::Row::orderByAddress) -
1087                    1;
1088   assert(Seq.SectionIndex == RowPos->Address.SectionIndex);
1089   return RowPos - Rows.begin();
1090 }
1091 
1092 uint32_t DWARFDebugLine::LineTable::lookupAddress(
1093     object::SectionedAddress Address) const {
1094 
1095   // Search for relocatable addresses
1096   uint32_t Result = lookupAddressImpl(Address);
1097 
1098   if (Result != UnknownRowIndex ||
1099       Address.SectionIndex == object::SectionedAddress::UndefSection)
1100     return Result;
1101 
1102   // Search for absolute addresses
1103   Address.SectionIndex = object::SectionedAddress::UndefSection;
1104   return lookupAddressImpl(Address);
1105 }
1106 
1107 uint32_t DWARFDebugLine::LineTable::lookupAddressImpl(
1108     object::SectionedAddress Address) const {
1109   // First, find an instruction sequence containing the given address.
1110   DWARFDebugLine::Sequence Sequence;
1111   Sequence.SectionIndex = Address.SectionIndex;
1112   Sequence.HighPC = Address.Address;
1113   SequenceIter It = llvm::upper_bound(Sequences, Sequence,
1114                                       DWARFDebugLine::Sequence::orderByHighPC);
1115   if (It == Sequences.end() || It->SectionIndex != Address.SectionIndex)
1116     return UnknownRowIndex;
1117   return findRowInSeq(*It, Address);
1118 }
1119 
1120 bool DWARFDebugLine::LineTable::lookupAddressRange(
1121     object::SectionedAddress Address, uint64_t Size,
1122     std::vector<uint32_t> &Result) const {
1123 
1124   // Search for relocatable addresses
1125   if (lookupAddressRangeImpl(Address, Size, Result))
1126     return true;
1127 
1128   if (Address.SectionIndex == object::SectionedAddress::UndefSection)
1129     return false;
1130 
1131   // Search for absolute addresses
1132   Address.SectionIndex = object::SectionedAddress::UndefSection;
1133   return lookupAddressRangeImpl(Address, Size, Result);
1134 }
1135 
1136 bool DWARFDebugLine::LineTable::lookupAddressRangeImpl(
1137     object::SectionedAddress Address, uint64_t Size,
1138     std::vector<uint32_t> &Result) const {
1139   if (Sequences.empty())
1140     return false;
1141   uint64_t EndAddr = Address.Address + Size;
1142   // First, find an instruction sequence containing the given address.
1143   DWARFDebugLine::Sequence Sequence;
1144   Sequence.SectionIndex = Address.SectionIndex;
1145   Sequence.HighPC = Address.Address;
1146   SequenceIter LastSeq = Sequences.end();
1147   SequenceIter SeqPos = llvm::upper_bound(
1148       Sequences, Sequence, DWARFDebugLine::Sequence::orderByHighPC);
1149   if (SeqPos == LastSeq || !SeqPos->containsPC(Address))
1150     return false;
1151 
1152   SequenceIter StartPos = SeqPos;
1153 
1154   // Add the rows from the first sequence to the vector, starting with the
1155   // index we just calculated
1156 
1157   while (SeqPos != LastSeq && SeqPos->LowPC < EndAddr) {
1158     const DWARFDebugLine::Sequence &CurSeq = *SeqPos;
1159     // For the first sequence, we need to find which row in the sequence is the
1160     // first in our range.
1161     uint32_t FirstRowIndex = CurSeq.FirstRowIndex;
1162     if (SeqPos == StartPos)
1163       FirstRowIndex = findRowInSeq(CurSeq, Address);
1164 
1165     // Figure out the last row in the range.
1166     uint32_t LastRowIndex =
1167         findRowInSeq(CurSeq, {EndAddr - 1, Address.SectionIndex});
1168     if (LastRowIndex == UnknownRowIndex)
1169       LastRowIndex = CurSeq.LastRowIndex - 1;
1170 
1171     assert(FirstRowIndex != UnknownRowIndex);
1172     assert(LastRowIndex != UnknownRowIndex);
1173 
1174     for (uint32_t I = FirstRowIndex; I <= LastRowIndex; ++I) {
1175       Result.push_back(I);
1176     }
1177 
1178     ++SeqPos;
1179   }
1180 
1181   return true;
1182 }
1183 
1184 Optional<StringRef> DWARFDebugLine::LineTable::getSourceByIndex(uint64_t FileIndex,
1185                                                                 FileLineInfoKind Kind) const {
1186   if (Kind == FileLineInfoKind::None || !Prologue.hasFileAtIndex(FileIndex))
1187     return None;
1188   const FileNameEntry &Entry = Prologue.getFileNameEntry(FileIndex);
1189   if (Optional<const char *> source = Entry.Source.getAsCString())
1190     return StringRef(*source);
1191   return None;
1192 }
1193 
1194 static bool isPathAbsoluteOnWindowsOrPosix(const Twine &Path) {
1195   // Debug info can contain paths from any OS, not necessarily
1196   // an OS we're currently running on. Moreover different compilation units can
1197   // be compiled on different operating systems and linked together later.
1198   return sys::path::is_absolute(Path, sys::path::Style::posix) ||
1199          sys::path::is_absolute(Path, sys::path::Style::windows);
1200 }
1201 
1202 bool DWARFDebugLine::Prologue::getFileNameByIndex(
1203     uint64_t FileIndex, StringRef CompDir, FileLineInfoKind Kind,
1204     std::string &Result, sys::path::Style Style) const {
1205   if (Kind == FileLineInfoKind::None || !hasFileAtIndex(FileIndex))
1206     return false;
1207   const FileNameEntry &Entry = getFileNameEntry(FileIndex);
1208   Optional<const char *> Name = Entry.Name.getAsCString();
1209   if (!Name)
1210     return false;
1211   StringRef FileName = *Name;
1212   if (Kind == FileLineInfoKind::Default ||
1213       isPathAbsoluteOnWindowsOrPosix(FileName)) {
1214     Result = std::string(FileName);
1215     return true;
1216   }
1217 
1218   SmallString<16> FilePath;
1219   StringRef IncludeDir;
1220   // Be defensive about the contents of Entry.
1221   if (getVersion() >= 5) {
1222     if (Entry.DirIdx < IncludeDirectories.size())
1223       IncludeDir = IncludeDirectories[Entry.DirIdx].getAsCString().getValue();
1224   } else {
1225     if (0 < Entry.DirIdx && Entry.DirIdx <= IncludeDirectories.size())
1226       IncludeDir =
1227           IncludeDirectories[Entry.DirIdx - 1].getAsCString().getValue();
1228   }
1229   // For absolute paths only, include the compilation directory of compile unit.
1230   // We know that FileName is not absolute, the only way to have an absolute
1231   // path at this point would be if IncludeDir is absolute.
1232   if (Kind == FileLineInfoKind::AbsoluteFilePath && !CompDir.empty() &&
1233       !isPathAbsoluteOnWindowsOrPosix(IncludeDir))
1234     sys::path::append(FilePath, Style, CompDir);
1235 
1236   assert((Kind == FileLineInfoKind::AbsoluteFilePath ||
1237           Kind == FileLineInfoKind::RelativeFilePath) &&
1238          "invalid FileLineInfo Kind");
1239 
1240   // sys::path::append skips empty strings.
1241   sys::path::append(FilePath, Style, IncludeDir, FileName);
1242   Result = std::string(FilePath.str());
1243   return true;
1244 }
1245 
1246 bool DWARFDebugLine::LineTable::getFileLineInfoForAddress(
1247     object::SectionedAddress Address, const char *CompDir,
1248     FileLineInfoKind Kind, DILineInfo &Result) const {
1249   // Get the index of row we're looking for in the line table.
1250   uint32_t RowIndex = lookupAddress(Address);
1251   if (RowIndex == -1U)
1252     return false;
1253   // Take file number and line/column from the row.
1254   const auto &Row = Rows[RowIndex];
1255   if (!getFileNameByIndex(Row.File, CompDir, Kind, Result.FileName))
1256     return false;
1257   Result.Line = Row.Line;
1258   Result.Column = Row.Column;
1259   Result.Discriminator = Row.Discriminator;
1260   Result.Source = getSourceByIndex(Row.File, Kind);
1261   return true;
1262 }
1263 
1264 // We want to supply the Unit associated with a .debug_line[.dwo] table when
1265 // we dump it, if possible, but still dump the table even if there isn't a Unit.
1266 // Therefore, collect up handles on all the Units that point into the
1267 // line-table section.
1268 static DWARFDebugLine::SectionParser::LineToUnitMap
1269 buildLineToUnitMap(DWARFDebugLine::SectionParser::cu_range CUs,
1270                    DWARFDebugLine::SectionParser::tu_range TUs) {
1271   DWARFDebugLine::SectionParser::LineToUnitMap LineToUnit;
1272   for (const auto &CU : CUs)
1273     if (auto CUDIE = CU->getUnitDIE())
1274       if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list)))
1275         LineToUnit.insert(std::make_pair(*StmtOffset, &*CU));
1276   for (const auto &TU : TUs)
1277     if (auto TUDIE = TU->getUnitDIE())
1278       if (auto StmtOffset = toSectionOffset(TUDIE.find(DW_AT_stmt_list)))
1279         LineToUnit.insert(std::make_pair(*StmtOffset, &*TU));
1280   return LineToUnit;
1281 }
1282 
1283 DWARFDebugLine::SectionParser::SectionParser(DWARFDataExtractor &Data,
1284                                              const DWARFContext &C,
1285                                              cu_range CUs, tu_range TUs)
1286     : DebugLineData(Data), Context(C) {
1287   LineToUnit = buildLineToUnitMap(CUs, TUs);
1288   if (!DebugLineData.isValidOffset(Offset))
1289     Done = true;
1290 }
1291 
1292 bool DWARFDebugLine::Prologue::totalLengthIsValid() const {
1293   return TotalLength != 0u;
1294 }
1295 
1296 DWARFDebugLine::LineTable DWARFDebugLine::SectionParser::parseNext(
1297     function_ref<void(Error)> RecoverableErrorHandler,
1298     function_ref<void(Error)> UnrecoverableErrorHandler, raw_ostream *OS) {
1299   assert(DebugLineData.isValidOffset(Offset) &&
1300          "parsing should have terminated");
1301   DWARFUnit *U = prepareToParse(Offset);
1302   uint64_t OldOffset = Offset;
1303   LineTable LT;
1304   if (Error Err = LT.parse(DebugLineData, &Offset, Context, U,
1305                            RecoverableErrorHandler, OS))
1306     UnrecoverableErrorHandler(std::move(Err));
1307   moveToNextTable(OldOffset, LT.Prologue);
1308   return LT;
1309 }
1310 
1311 void DWARFDebugLine::SectionParser::skip(
1312     function_ref<void(Error)> RecoverableErrorHandler,
1313     function_ref<void(Error)> UnrecoverableErrorHandler) {
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.Prologue.parse(DebugLineData, &Offset,
1320                                     RecoverableErrorHandler, Context, U))
1321     UnrecoverableErrorHandler(std::move(Err));
1322   moveToNextTable(OldOffset, LT.Prologue);
1323 }
1324 
1325 DWARFUnit *DWARFDebugLine::SectionParser::prepareToParse(uint64_t Offset) {
1326   DWARFUnit *U = nullptr;
1327   auto It = LineToUnit.find(Offset);
1328   if (It != LineToUnit.end())
1329     U = It->second;
1330   DebugLineData.setAddressSize(U ? U->getAddressByteSize() : 0);
1331   return U;
1332 }
1333 
1334 void DWARFDebugLine::SectionParser::moveToNextTable(uint64_t OldOffset,
1335                                                     const Prologue &P) {
1336   // If the length field is not valid, we don't know where the next table is, so
1337   // cannot continue to parse. Mark the parser as done, and leave the Offset
1338   // value as it currently is. This will be the end of the bad length field.
1339   if (!P.totalLengthIsValid()) {
1340     Done = true;
1341     return;
1342   }
1343 
1344   Offset = OldOffset + P.TotalLength + P.sizeofTotalLength();
1345   if (!DebugLineData.isValidOffset(Offset)) {
1346     Done = true;
1347   }
1348 }
1349