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