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