1 //===- DWARFListTable.h -----------------------------------------*- C++ -*-===//
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 #ifndef LLVM_DEBUGINFO_DWARFLISTTABLE_H
10 #define LLVM_DEBUGINFO_DWARFLISTTABLE_H
11 
12 #include "llvm/BinaryFormat/Dwarf.h"
13 #include "llvm/DebugInfo/DIContext.h"
14 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
15 #include "llvm/Support/Errc.h"
16 #include "llvm/Support/Error.h"
17 #include "llvm/Support/Format.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include <cstdint>
20 #include <map>
21 #include <vector>
22 
23 namespace llvm {
24 
25 /// A base class for DWARF list entries, such as range or location list
26 /// entries.
27 struct DWARFListEntryBase {
28   /// The offset at which the entry is located in the section.
29   uint64_t Offset;
30   /// The DWARF encoding (DW_RLE_* or DW_LLE_*).
31   uint8_t EntryKind;
32   /// The index of the section this entry belongs to.
33   uint64_t SectionIndex;
34 };
35 
36 /// A base class for lists of entries that are extracted from a particular
37 /// section, such as range lists or location lists.
38 template <typename ListEntryType> class DWARFListType {
39   using EntryType = ListEntryType;
40   using ListEntries = std::vector<EntryType>;
41 
42 protected:
43   ListEntries Entries;
44 
45 public:
46   const ListEntries &getEntries() const { return Entries; }
47   bool empty() const { return Entries.empty(); }
48   void clear() { Entries.clear(); }
49   Error extract(DWARFDataExtractor Data, uint64_t HeaderOffset,
50                 uint64_t *OffsetPtr, StringRef SectionName,
51                 StringRef ListStringName);
52 };
53 
54 /// A class representing the header of a list table such as the range list
55 /// table in the .debug_rnglists section.
56 class DWARFListTableHeader {
57   struct Header {
58     /// The total length of the entries for this table, not including the length
59     /// field itself.
60     uint64_t Length = 0;
61     /// The DWARF version number.
62     uint16_t Version;
63     /// The size in bytes of an address on the target architecture. For
64     /// segmented addressing, this is the size of the offset portion of the
65     /// address.
66     uint8_t AddrSize;
67     /// The size in bytes of a segment selector on the target architecture.
68     /// If the target system uses a flat address space, this value is 0.
69     uint8_t SegSize;
70     /// The number of offsets that follow the header before the range lists.
71     uint32_t OffsetEntryCount;
72   };
73 
74   Header HeaderData;
75   /// The table's format, either DWARF32 or DWARF64.
76   dwarf::DwarfFormat Format;
77   /// The offset at which the header (and hence the table) is located within
78   /// its section.
79   uint64_t HeaderOffset;
80   /// The name of the section the list is located in.
81   StringRef SectionName;
82   /// A characterization of the list for dumping purposes, e.g. "range" or
83   /// "location".
84   StringRef ListTypeString;
85 
86 public:
87   DWARFListTableHeader(StringRef SectionName, StringRef ListTypeString)
88       : SectionName(SectionName), ListTypeString(ListTypeString) {}
89 
90   void clear() {
91     HeaderData = {};
92   }
93   uint64_t getHeaderOffset() const { return HeaderOffset; }
94   uint8_t getAddrSize() const { return HeaderData.AddrSize; }
95   uint64_t getLength() const { return HeaderData.Length; }
96   uint16_t getVersion() const { return HeaderData.Version; }
97   StringRef getSectionName() const { return SectionName; }
98   StringRef getListTypeString() const { return ListTypeString; }
99   dwarf::DwarfFormat getFormat() const { return Format; }
100 
101   /// Return the size of the table header including the length but not including
102   /// the offsets.
103   static uint8_t getHeaderSize(dwarf::DwarfFormat Format) {
104     switch (Format) {
105     case dwarf::DwarfFormat::DWARF32:
106       return 12;
107     case dwarf::DwarfFormat::DWARF64:
108       return 20;
109     }
110     llvm_unreachable("Invalid DWARF format (expected DWARF32 or DWARF64");
111   }
112 
113   void dump(DataExtractor Data, raw_ostream &OS,
114             DIDumpOptions DumpOpts = {}) const;
115   Optional<uint64_t> getOffsetEntry(DataExtractor Data, uint32_t Index) const {
116     if (Index > HeaderData.OffsetEntryCount)
117       return None;
118 
119     return getOffsetEntry(Data, getHeaderOffset() + getHeaderSize(Format), Format, Index);
120   }
121 
122   static Optional<uint64_t> getOffsetEntry(DataExtractor Data,
123                                            uint64_t OffsetTableOffset,
124                                            dwarf::DwarfFormat Format,
125                                            uint32_t Index) {
126     uint8_t OffsetByteSize = Format == dwarf::DWARF64 ? 8 : 4;
127     uint64_t Offset = OffsetTableOffset + OffsetByteSize * Index;
128     auto R = Data.getUnsigned(&Offset, OffsetByteSize);
129     return R;
130   }
131 
132   /// Extract the table header and the array of offsets.
133   Error extract(DWARFDataExtractor Data, uint64_t *OffsetPtr);
134 
135   /// Returns the length of the table, including the length field, or 0 if the
136   /// length has not been determined (e.g. because the table has not yet been
137   /// parsed, or there was a problem in parsing).
138   uint64_t length() const;
139 };
140 
141 /// A class representing a table of lists as specified in the DWARF v5
142 /// standard for location lists and range lists. The table consists of a header
143 /// followed by an array of offsets into a DWARF section, followed by zero or
144 /// more list entries. The list entries are kept in a map where the keys are
145 /// the lists' section offsets.
146 template <typename DWARFListType> class DWARFListTableBase {
147   DWARFListTableHeader Header;
148   /// A mapping between file offsets and lists. It is used to find a particular
149   /// list based on an offset (obtained from DW_AT_ranges, for example).
150   std::map<uint64_t, DWARFListType> ListMap;
151   /// This string is displayed as a heading before the list is dumped
152   /// (e.g. "ranges:").
153   StringRef HeaderString;
154 
155 protected:
156   DWARFListTableBase(StringRef SectionName, StringRef HeaderString,
157                      StringRef ListTypeString)
158       : Header(SectionName, ListTypeString), HeaderString(HeaderString) {}
159 
160 public:
161   void clear() {
162     Header.clear();
163     ListMap.clear();
164   }
165   /// Extract the table header and the array of offsets.
166   Error extractHeaderAndOffsets(DWARFDataExtractor Data, uint64_t *OffsetPtr) {
167     return Header.extract(Data, OffsetPtr);
168   }
169   /// Extract an entire table, including all list entries.
170   Error extract(DWARFDataExtractor Data, uint64_t *OffsetPtr);
171   /// Look up a list based on a given offset. Extract it and enter it into the
172   /// list map if necessary.
173   Expected<DWARFListType> findList(DWARFDataExtractor Data, uint64_t Offset);
174 
175   uint64_t getHeaderOffset() const { return Header.getHeaderOffset(); }
176   uint8_t getAddrSize() const { return Header.getAddrSize(); }
177   dwarf::DwarfFormat getFormat() const { return Header.getFormat(); }
178 
179   void dump(DWARFDataExtractor Data, raw_ostream &OS,
180             llvm::function_ref<Optional<object::SectionedAddress>(uint32_t)>
181                 LookupPooledAddress,
182             DIDumpOptions DumpOpts = {}) const;
183 
184   /// Return the contents of the offset entry designated by a given index.
185   Optional<uint64_t> getOffsetEntry(DataExtractor Data, uint32_t Index) const {
186     return Header.getOffsetEntry(Data, Index);
187   }
188   /// Return the size of the table header including the length but not including
189   /// the offsets. This is dependent on the table format, which is unambiguously
190   /// derived from parsing the table.
191   uint8_t getHeaderSize() const {
192     return DWARFListTableHeader::getHeaderSize(getFormat());
193   }
194 
195   uint64_t length() { return Header.length(); }
196 };
197 
198 template <typename DWARFListType>
199 Error DWARFListTableBase<DWARFListType>::extract(DWARFDataExtractor Data,
200                                                  uint64_t *OffsetPtr) {
201   clear();
202   if (Error E = extractHeaderAndOffsets(Data, OffsetPtr))
203     return E;
204 
205   Data.setAddressSize(Header.getAddrSize());
206   Data = DWARFDataExtractor(Data, getHeaderOffset() + Header.length());
207   while (Data.isValidOffset(*OffsetPtr)) {
208     DWARFListType CurrentList;
209     uint64_t Off = *OffsetPtr;
210     if (Error E = CurrentList.extract(Data, getHeaderOffset(), OffsetPtr,
211                                       Header.getSectionName(),
212                                       Header.getListTypeString()))
213       return E;
214     ListMap[Off] = CurrentList;
215   }
216 
217   assert(*OffsetPtr == Data.size() &&
218          "mismatch between expected length of table and length "
219          "of extracted data");
220   return Error::success();
221 }
222 
223 template <typename ListEntryType>
224 Error DWARFListType<ListEntryType>::extract(DWARFDataExtractor Data,
225                                             uint64_t HeaderOffset,
226                                             uint64_t *OffsetPtr,
227                                             StringRef SectionName,
228                                             StringRef ListTypeString) {
229   if (*OffsetPtr < HeaderOffset || *OffsetPtr >= Data.size())
230     return createStringError(errc::invalid_argument,
231                        "invalid %s list offset 0x%" PRIx64,
232                        ListTypeString.data(), *OffsetPtr);
233   Entries.clear();
234   while (Data.isValidOffset(*OffsetPtr)) {
235     ListEntryType Entry;
236     if (Error E = Entry.extract(Data, OffsetPtr))
237       return E;
238     Entries.push_back(Entry);
239     if (Entry.isSentinel())
240       return Error::success();
241   }
242   return createStringError(errc::illegal_byte_sequence,
243                      "no end of list marker detected at end of %s table "
244                      "starting at offset 0x%" PRIx64,
245                      SectionName.data(), HeaderOffset);
246 }
247 
248 template <typename DWARFListType>
249 void DWARFListTableBase<DWARFListType>::dump(
250     DWARFDataExtractor Data, raw_ostream &OS,
251     llvm::function_ref<Optional<object::SectionedAddress>(uint32_t)>
252         LookupPooledAddress,
253     DIDumpOptions DumpOpts) const {
254   Header.dump(Data, OS, DumpOpts);
255   OS << HeaderString << "\n";
256 
257   // Determine the length of the longest encoding string we have in the table,
258   // so we can align the output properly. We only need this in verbose mode.
259   size_t MaxEncodingStringLength = 0;
260   if (DumpOpts.Verbose) {
261     for (const auto &List : ListMap)
262       for (const auto &Entry : List.second.getEntries())
263         MaxEncodingStringLength =
264             std::max(MaxEncodingStringLength,
265                      dwarf::RangeListEncodingString(Entry.EntryKind).size());
266   }
267 
268   uint64_t CurrentBase = 0;
269   for (const auto &List : ListMap)
270     for (const auto &Entry : List.second.getEntries())
271       Entry.dump(OS, getAddrSize(), MaxEncodingStringLength, CurrentBase,
272                  DumpOpts, LookupPooledAddress);
273 }
274 
275 template <typename DWARFListType>
276 Expected<DWARFListType>
277 DWARFListTableBase<DWARFListType>::findList(DWARFDataExtractor Data,
278                                             uint64_t Offset) {
279   // Extract the list from the section and enter it into the list map.
280   DWARFListType List;
281   if (Header.length())
282     Data = DWARFDataExtractor(Data, getHeaderOffset() + Header.length());
283   if (Error E =
284           List.extract(Data, Header.length() ? getHeaderOffset() : 0, &Offset,
285                        Header.getSectionName(), Header.getListTypeString()))
286     return std::move(E);
287   return List;
288 }
289 
290 } // end namespace llvm
291 
292 #endif // LLVM_DEBUGINFO_DWARFLISTTABLE_H
293