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