blob: fdb71958cc6f97dbbc2f8aa017e28f195146cd38 [file] [log] [blame]
Greg Claytonb8c162b2017-05-03 16:02:29 +00001//===- DWARFVerifier.cpp --------------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Greg Claytonb8c162b2017-05-03 16:02:29 +00009#include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
Pavel Labath79cd9422018-03-22 14:50:44 +000010#include "llvm/ADT/SmallSet.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000011#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
12#include "llvm/DebugInfo/DWARF/DWARFContext.h"
13#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
14#include "llvm/DebugInfo/DWARF/DWARFDie.h"
George Rimar144e4c52017-10-27 10:42:04 +000015#include "llvm/DebugInfo/DWARF/DWARFExpression.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000016#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
17#include "llvm/DebugInfo/DWARF/DWARFSection.h"
Pavel Labath906b7772018-03-16 10:02:16 +000018#include "llvm/Support/DJB.h"
George Rimar144e4c52017-10-27 10:42:04 +000019#include "llvm/Support/FormatVariadic.h"
Jonas Devlieghere69217532018-03-09 09:56:24 +000020#include "llvm/Support/WithColor.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000021#include "llvm/Support/raw_ostream.h"
22#include <map>
23#include <set>
24#include <vector>
25
26using namespace llvm;
27using namespace dwarf;
28using namespace object;
29
Jonas Devlieghere58910602017-09-14 11:33:42 +000030DWARFVerifier::DieRangeInfo::address_range_iterator
31DWARFVerifier::DieRangeInfo::insert(const DWARFAddressRange &R) {
32 auto Begin = Ranges.begin();
33 auto End = Ranges.end();
34 auto Pos = std::lower_bound(Begin, End, R);
35
36 if (Pos != End) {
37 if (Pos->intersects(R))
38 return Pos;
39 if (Pos != Begin) {
40 auto Iter = Pos - 1;
41 if (Iter->intersects(R))
42 return Iter;
43 }
44 }
45
46 Ranges.insert(Pos, R);
47 return Ranges.end();
48}
49
50DWARFVerifier::DieRangeInfo::die_range_info_iterator
51DWARFVerifier::DieRangeInfo::insert(const DieRangeInfo &RI) {
52 auto End = Children.end();
53 auto Iter = Children.begin();
54 while (Iter != End) {
55 if (Iter->intersects(RI))
56 return Iter;
57 ++Iter;
58 }
59 Children.insert(RI);
60 return Children.end();
61}
62
63bool DWARFVerifier::DieRangeInfo::contains(const DieRangeInfo &RHS) const {
64 // Both list of ranges are sorted so we can make this fast.
65
66 if (Ranges.empty() || RHS.Ranges.empty())
67 return false;
68
69 // Since the ranges are sorted we can advance where we start searching with
70 // this object's ranges as we traverse RHS.Ranges.
71 auto End = Ranges.end();
72 auto Iter = findRange(RHS.Ranges.front());
73
74 // Now linearly walk the ranges in this object and see if they contain each
75 // ranges from RHS.Ranges.
76 for (const auto &R : RHS.Ranges) {
77 while (Iter != End) {
78 if (Iter->contains(R))
79 break;
80 ++Iter;
81 }
82 if (Iter == End)
83 return false;
84 }
85 return true;
86}
87
88bool DWARFVerifier::DieRangeInfo::intersects(const DieRangeInfo &RHS) const {
89 if (Ranges.empty() || RHS.Ranges.empty())
90 return false;
91
92 auto End = Ranges.end();
93 auto Iter = findRange(RHS.Ranges.front());
94 for (const auto &R : RHS.Ranges) {
Jonas Devlieghere9d7cecf2018-09-17 14:23:47 +000095 if (Iter == End)
Jonas Devlieghered585a202017-09-14 17:46:23 +000096 return false;
Jonas Devlieghere58910602017-09-14 11:33:42 +000097 if (R.HighPC <= Iter->LowPC)
98 continue;
99 while (Iter != End) {
100 if (Iter->intersects(R))
101 return true;
102 ++Iter;
103 }
104 }
105
106 return false;
107}
108
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000109bool DWARFVerifier::verifyUnitHeader(const DWARFDataExtractor DebugInfoData,
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000110 uint32_t *Offset, unsigned UnitIndex,
111 uint8_t &UnitType, bool &isUnitDWARF64) {
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000112 uint32_t AbbrOffset, Length;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000113 uint8_t AddrSize = 0;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000114 uint16_t Version;
115 bool Success = true;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000116
117 bool ValidLength = false;
118 bool ValidVersion = false;
119 bool ValidAddrSize = false;
120 bool ValidType = true;
121 bool ValidAbbrevOffset = true;
122
123 uint32_t OffsetStart = *Offset;
124 Length = DebugInfoData.getU32(Offset);
125 if (Length == UINT32_MAX) {
126 isUnitDWARF64 = true;
127 OS << format(
128 "Unit[%d] is in 64-bit DWARF format; cannot verify from this point.\n",
129 UnitIndex);
130 return false;
131 }
132 Version = DebugInfoData.getU16(Offset);
133
134 if (Version >= 5) {
135 UnitType = DebugInfoData.getU8(Offset);
136 AddrSize = DebugInfoData.getU8(Offset);
137 AbbrOffset = DebugInfoData.getU32(Offset);
Jonas Devliegheref2fa9eb2017-10-06 22:27:31 +0000138 ValidType = dwarf::isUnitType(UnitType);
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000139 } else {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000140 UnitType = 0;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000141 AbbrOffset = DebugInfoData.getU32(Offset);
142 AddrSize = DebugInfoData.getU8(Offset);
143 }
144
145 if (!DCtx.getDebugAbbrev()->getAbbreviationDeclarationSet(AbbrOffset))
146 ValidAbbrevOffset = false;
147
148 ValidLength = DebugInfoData.isValidOffset(OffsetStart + Length + 3);
149 ValidVersion = DWARFContext::isSupportedVersion(Version);
150 ValidAddrSize = AddrSize == 4 || AddrSize == 8;
151 if (!ValidLength || !ValidVersion || !ValidAddrSize || !ValidAbbrevOffset ||
152 !ValidType) {
153 Success = false;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000154 error() << format("Units[%d] - start offset: 0x%08x \n", UnitIndex,
155 OffsetStart);
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000156 if (!ValidLength)
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000157 note() << "The length for this unit is too "
Jonas Devlieghere9d7cecf2018-09-17 14:23:47 +0000158 "large for the .debug_info provided.\n";
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000159 if (!ValidVersion)
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000160 note() << "The 16 bit unit header version is not valid.\n";
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000161 if (!ValidType)
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000162 note() << "The unit type encoding is not valid.\n";
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000163 if (!ValidAbbrevOffset)
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000164 note() << "The offset into the .debug_abbrev section is "
Jonas Devlieghere9d7cecf2018-09-17 14:23:47 +0000165 "not valid.\n";
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000166 if (!ValidAddrSize)
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000167 note() << "The address size is unsupported.\n";
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000168 }
169 *Offset = OffsetStart + Length + 4;
170 return Success;
171}
172
Jonas Devlieghere9d7cecf2018-09-17 14:23:47 +0000173unsigned DWARFVerifier::verifyUnitContents(DWARFUnit &Unit) {
Paul Robinson508b0812018-08-08 23:50:22 +0000174 unsigned NumUnitErrors = 0;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000175 unsigned NumDies = Unit.getNumDIEs();
176 for (unsigned I = 0; I < NumDies; ++I) {
177 auto Die = Unit.getDIEAtIndex(I);
Jonas Devlieghereb3227422018-09-21 07:50:21 +0000178
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000179 if (Die.getTag() == DW_TAG_null)
180 continue;
Jonas Devlieghereb3227422018-09-21 07:50:21 +0000181
182 bool HasTypeAttr = false;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000183 for (auto AttrValue : Die.attributes()) {
184 NumUnitErrors += verifyDebugInfoAttribute(Die, AttrValue);
185 NumUnitErrors += verifyDebugInfoForm(Die, AttrValue);
Jonas Devlieghereb3227422018-09-21 07:50:21 +0000186 HasTypeAttr |= (AttrValue.Attr == DW_AT_type);
187 }
188
189 if (!HasTypeAttr && (Die.getTag() == DW_TAG_formal_parameter ||
190 Die.getTag() == DW_TAG_variable ||
191 Die.getTag() == DW_TAG_array_type)) {
192 error() << "DIE with tag " << TagString(Die.getTag())
193 << " is missing type attribute:\n";
194 dump(Die) << '\n';
195 NumUnitErrors++;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000196 }
Vedant Kumar5931b4e2018-10-05 20:37:17 +0000197 NumUnitErrors += verifyDebugInfoCallSite(Die);
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000198 }
Jonas Devlieghere58910602017-09-14 11:33:42 +0000199
Jonas Devliegheref2fa9eb2017-10-06 22:27:31 +0000200 DWARFDie Die = Unit.getUnitDIE(/* ExtractUnitDIEOnly = */ false);
201 if (!Die) {
202 error() << "Compilation unit without DIE.\n";
203 NumUnitErrors++;
Paul Robinson508b0812018-08-08 23:50:22 +0000204 return NumUnitErrors;
Jonas Devliegheref2fa9eb2017-10-06 22:27:31 +0000205 }
206
207 if (!dwarf::isUnitType(Die.getTag())) {
208 error() << "Compilation unit root DIE is not a unit DIE: "
209 << dwarf::TagString(Die.getTag()) << ".\n";
Jonas Devlieghere35fdaa92017-09-28 15:57:50 +0000210 NumUnitErrors++;
211 }
212
Jonas Devlieghere9d7cecf2018-09-17 14:23:47 +0000213 uint8_t UnitType = Unit.getUnitType();
214 if (!DWARFUnit::isMatchingUnitTypeAndTag(UnitType, Die.getTag())) {
Jonas Devliegheref2fa9eb2017-10-06 22:27:31 +0000215 error() << "Compilation unit type (" << dwarf::UnitTypeString(UnitType)
216 << ") and root DIE (" << dwarf::TagString(Die.getTag())
217 << ") do not match.\n";
218 NumUnitErrors++;
219 }
220
221 DieRangeInfo RI;
222 NumUnitErrors += verifyDieRanges(Die, RI);
223
Paul Robinson508b0812018-08-08 23:50:22 +0000224 return NumUnitErrors;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000225}
226
Vedant Kumar5931b4e2018-10-05 20:37:17 +0000227unsigned DWARFVerifier::verifyDebugInfoCallSite(const DWARFDie &Die) {
228 if (Die.getTag() != DW_TAG_call_site)
229 return 0;
230
231 DWARFDie Curr = Die.getParent();
232 for (; Curr.isValid() && !Curr.isSubprogramDIE(); Curr = Die.getParent()) {
233 if (Curr.getTag() == DW_TAG_inlined_subroutine) {
234 error() << "Call site entry nested within inlined subroutine:";
235 Curr.dump(OS);
236 return 1;
237 }
238 }
239
240 if (!Curr.isValid()) {
241 error() << "Call site entry not nested within a valid subprogram:";
242 Die.dump(OS);
243 return 1;
244 }
245
246 Optional<DWARFFormValue> CallAttr =
247 Curr.find({DW_AT_call_all_calls, DW_AT_call_all_source_calls,
248 DW_AT_call_all_tail_calls});
249 if (!CallAttr) {
250 error() << "Subprogram with call site entry has no DW_AT_call attribute:";
251 Curr.dump(OS);
252 Die.dump(OS, /*indent*/ 1);
253 return 1;
254 }
255
256 return 0;
257}
258
Spyridoula Gravanic6ef9872017-07-21 00:51:32 +0000259unsigned DWARFVerifier::verifyAbbrevSection(const DWARFDebugAbbrev *Abbrev) {
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000260 unsigned NumErrors = 0;
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000261 if (Abbrev) {
262 const DWARFAbbreviationDeclarationSet *AbbrDecls =
263 Abbrev->getAbbreviationDeclarationSet(0);
264 for (auto AbbrDecl : *AbbrDecls) {
265 SmallDenseSet<uint16_t> AttributeSet;
266 for (auto Attribute : AbbrDecl.attributes()) {
267 auto Result = AttributeSet.insert(Attribute.Attr);
268 if (!Result.second) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000269 error() << "Abbreviation declaration contains multiple "
270 << AttributeString(Attribute.Attr) << " attributes.\n";
Spyridoula Gravanic6ef9872017-07-21 00:51:32 +0000271 AbbrDecl.dump(OS);
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000272 ++NumErrors;
273 }
274 }
275 }
276 }
Spyridoula Gravanic6ef9872017-07-21 00:51:32 +0000277 return NumErrors;
278}
279
280bool DWARFVerifier::handleDebugAbbrev() {
281 OS << "Verifying .debug_abbrev...\n";
282
283 const DWARFObject &DObj = DCtx.getDWARFObj();
284 bool noDebugAbbrev = DObj.getAbbrevSection().empty();
285 bool noDebugAbbrevDWO = DObj.getAbbrevDWOSection().empty();
286
287 if (noDebugAbbrev && noDebugAbbrevDWO) {
288 return true;
289 }
290
291 unsigned NumErrors = 0;
292 if (!noDebugAbbrev)
293 NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrev());
294
295 if (!noDebugAbbrevDWO)
296 NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrevDWO());
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000297 return NumErrors == 0;
298}
299
Paul Robinson508b0812018-08-08 23:50:22 +0000300unsigned DWARFVerifier::verifyUnitSection(const DWARFSection &S,
301 DWARFSectionKind SectionKind) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000302 const DWARFObject &DObj = DCtx.getDWARFObj();
Paul Robinson508b0812018-08-08 23:50:22 +0000303 DWARFDataExtractor DebugInfoData(DObj, S, DCtx.isLittleEndian(), 0);
304 unsigned NumDebugInfoErrors = 0;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000305 uint32_t OffsetStart = 0, Offset = 0, UnitIdx = 0;
306 uint8_t UnitType = 0;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000307 bool isUnitDWARF64 = false;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000308 bool isHeaderChainValid = true;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000309 bool hasDIE = DebugInfoData.isValidOffset(Offset);
Jonas Devlieghere7ef2c202018-09-21 07:49:29 +0000310 DWARFUnitVector TypeUnitVector;
311 DWARFUnitVector CompileUnitVector;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000312 while (hasDIE) {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000313 OffsetStart = Offset;
314 if (!verifyUnitHeader(DebugInfoData, &Offset, UnitIdx, UnitType,
315 isUnitDWARF64)) {
316 isHeaderChainValid = false;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000317 if (isUnitDWARF64)
318 break;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000319 } else {
Paul Robinson5f53f072018-05-14 20:32:31 +0000320 DWARFUnitHeader Header;
Paul Robinson508b0812018-08-08 23:50:22 +0000321 Header.extract(DCtx, DebugInfoData, &OffsetStart, SectionKind);
Jonas Devlieghere7ef2c202018-09-21 07:49:29 +0000322 DWARFUnit *Unit;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000323 switch (UnitType) {
324 case dwarf::DW_UT_type:
325 case dwarf::DW_UT_split_type: {
Jonas Devlieghere7ef2c202018-09-21 07:49:29 +0000326 Unit = TypeUnitVector.addUnit(llvm::make_unique<DWARFTypeUnit>(
Paul Robinson508b0812018-08-08 23:50:22 +0000327 DCtx, S, Header, DCtx.getDebugAbbrev(), &DObj.getRangeSection(),
Wolfgang Pieb6214c112018-10-19 19:23:16 +0000328 &DObj.getLocSection(), DObj.getStringSection(),
329 DObj.getStringOffsetSection(), &DObj.getAppleObjCSection(),
330 DObj.getLineSection(), DCtx.isLittleEndian(), false,
331 TypeUnitVector));
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000332 break;
333 }
334 case dwarf::DW_UT_skeleton:
335 case dwarf::DW_UT_split_compile:
336 case dwarf::DW_UT_compile:
337 case dwarf::DW_UT_partial:
Jonas Devlieghere9d7cecf2018-09-17 14:23:47 +0000338 // UnitType = 0 means that we are verifying a compile unit in DWARF v4.
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000339 case 0: {
Jonas Devlieghere7ef2c202018-09-21 07:49:29 +0000340 Unit = CompileUnitVector.addUnit(llvm::make_unique<DWARFCompileUnit>(
Paul Robinson508b0812018-08-08 23:50:22 +0000341 DCtx, S, Header, DCtx.getDebugAbbrev(), &DObj.getRangeSection(),
Wolfgang Pieb6214c112018-10-19 19:23:16 +0000342 &DObj.getLocSection(), DObj.getStringSection(),
343 DObj.getStringOffsetSection(), &DObj.getAppleObjCSection(),
344 DObj.getLineSection(), DCtx.isLittleEndian(), false,
345 CompileUnitVector));
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000346 break;
347 }
348 default: { llvm_unreachable("Invalid UnitType."); }
349 }
Jonas Devlieghere9d7cecf2018-09-17 14:23:47 +0000350 NumDebugInfoErrors += verifyUnitContents(*Unit);
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000351 }
352 hasDIE = DebugInfoData.isValidOffset(Offset);
353 ++UnitIdx;
354 }
355 if (UnitIdx == 0 && !hasDIE) {
Paul Robinson508b0812018-08-08 23:50:22 +0000356 warn() << "Section is empty.\n";
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000357 isHeaderChainValid = true;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000358 }
Paul Robinson508b0812018-08-08 23:50:22 +0000359 if (!isHeaderChainValid)
360 ++NumDebugInfoErrors;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000361 NumDebugInfoErrors += verifyDebugInfoReferences();
Paul Robinson508b0812018-08-08 23:50:22 +0000362 return NumDebugInfoErrors;
363}
364
365bool DWARFVerifier::handleDebugInfo() {
366 const DWARFObject &DObj = DCtx.getDWARFObj();
367
368 OS << "Verifying .debug_info Unit Header Chain...\n";
369 unsigned result = verifyUnitSection(DObj.getInfoSection(), DW_SECT_INFO);
370
371 OS << "Verifying .debug_types Unit Header Chain...\n";
372 DObj.forEachTypesSections([&](const DWARFSection &S) {
373 result += verifyUnitSection(S, DW_SECT_TYPES);
374 });
375 return result == 0;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000376}
377
Jonas Devlieghere58910602017-09-14 11:33:42 +0000378unsigned DWARFVerifier::verifyDieRanges(const DWARFDie &Die,
379 DieRangeInfo &ParentRI) {
Spyridoula Gravanie0ba4152017-07-24 21:04:11 +0000380 unsigned NumErrors = 0;
Jonas Devlieghere58910602017-09-14 11:33:42 +0000381
382 if (!Die.isValid())
383 return NumErrors;
384
Wolfgang Pieb61d8c8d2018-06-20 22:56:37 +0000385 auto RangesOrError = Die.getAddressRanges();
386 if (!RangesOrError) {
387 // FIXME: Report the error.
388 ++NumErrors;
389 llvm::consumeError(RangesOrError.takeError());
390 return NumErrors;
391 }
Jonas Devlieghere58910602017-09-14 11:33:42 +0000392
Wolfgang Pieb61d8c8d2018-06-20 22:56:37 +0000393 DWARFAddressRangesVector Ranges = RangesOrError.get();
Jonas Devlieghere58910602017-09-14 11:33:42 +0000394 // Build RI for this DIE and check that ranges within this DIE do not
395 // overlap.
396 DieRangeInfo RI(Die);
Jonas Devlieghere58910602017-09-14 11:33:42 +0000397
Saleem Abdulrasoolec77a652018-10-28 22:30:48 +0000398 // TODO support object files better
399 //
400 // Some object file formats (i.e. non-MachO) support COMDAT. ELF in
401 // particular does so by placing each function into a section. The DWARF data
402 // for the function at that point uses a section relative DW_FORM_addrp for
403 // the DW_AT_low_pc and a DW_FORM_data4 for the offset as the DW_AT_high_pc.
404 // In such a case, when the Die is the CU, the ranges will overlap, and we
405 // will flag valid conflicting ranges as invalid.
406 //
407 // For such targets, we should read the ranges from the CU and partition them
408 // by the section id. The ranges within a particular section should be
409 // disjoint, although the ranges across sections may overlap. We would map
410 // the child die to the entity that it references and the section with which
411 // it is associated. The child would then be checked against the range
412 // information for the associated section.
413 //
414 // For now, simply elide the range verification for the CU DIEs if we are
415 // processing an object file.
416
417 if (!IsObjectFile || IsMachOObject || Die.getTag() == DW_TAG_subprogram) {
418 for (auto Range : Ranges) {
419 if (!Range.valid()) {
420 ++NumErrors;
421 error() << "Invalid address range " << Range << "\n";
422 continue;
423 }
424
425 // Verify that ranges don't intersect.
426 const auto IntersectingRange = RI.insert(Range);
427 if (IntersectingRange != RI.Ranges.end()) {
428 ++NumErrors;
429 error() << "DIE has overlapping address ranges: " << Range << " and "
430 << *IntersectingRange << "\n";
431 break;
432 }
Spyridoula Gravanie0ba4152017-07-24 21:04:11 +0000433 }
434 }
Jonas Devlieghere58910602017-09-14 11:33:42 +0000435
436 // Verify that children don't intersect.
437 const auto IntersectingChild = ParentRI.insert(RI);
438 if (IntersectingChild != ParentRI.Children.end()) {
439 ++NumErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000440 error() << "DIEs have overlapping address ranges:";
Jonas Devliegheref1f3e732018-09-19 08:08:13 +0000441 dump(Die);
442 dump(IntersectingChild->Die) << '\n';
Jonas Devlieghere58910602017-09-14 11:33:42 +0000443 }
444
445 // Verify that ranges are contained within their parent.
446 bool ShouldBeContained = !Ranges.empty() && !ParentRI.Ranges.empty() &&
447 !(Die.getTag() == DW_TAG_subprogram &&
448 ParentRI.Die.getTag() == DW_TAG_subprogram);
449 if (ShouldBeContained && !ParentRI.contains(RI)) {
450 ++NumErrors;
Jonas Devlieghere63eca152018-05-22 17:38:03 +0000451 error() << "DIE address ranges are not contained in its parent's ranges:";
Jonas Devliegheref1f3e732018-09-19 08:08:13 +0000452 dump(ParentRI.Die);
453 dump(Die, 2) << '\n';
Jonas Devlieghere58910602017-09-14 11:33:42 +0000454 }
455
456 // Recursively check children.
457 for (DWARFDie Child : Die)
458 NumErrors += verifyDieRanges(Child, RI);
459
Spyridoula Gravanie0ba4152017-07-24 21:04:11 +0000460 return NumErrors;
461}
462
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000463unsigned DWARFVerifier::verifyDebugInfoAttribute(const DWARFDie &Die,
464 DWARFAttribute &AttrValue) {
465 unsigned NumErrors = 0;
George Rimar144e4c52017-10-27 10:42:04 +0000466 auto ReportError = [&](const Twine &TitleMsg) {
467 ++NumErrors;
468 error() << TitleMsg << '\n';
Jonas Devliegheref1f3e732018-09-19 08:08:13 +0000469 dump(Die) << '\n';
George Rimar144e4c52017-10-27 10:42:04 +0000470 };
471
472 const DWARFObject &DObj = DCtx.getDWARFObj();
Greg Claytonc5b2d562017-05-03 18:25:46 +0000473 const auto Attr = AttrValue.Attr;
474 switch (Attr) {
475 case DW_AT_ranges:
476 // Make sure the offset in the DW_AT_ranges attribute is valid.
477 if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
George Rimar144e4c52017-10-27 10:42:04 +0000478 if (*SectionOffset >= DObj.getRangeSection().Data.size())
479 ReportError("DW_AT_ranges offset is beyond .debug_ranges bounds:");
480 break;
Greg Claytonc5b2d562017-05-03 18:25:46 +0000481 }
George Rimar144e4c52017-10-27 10:42:04 +0000482 ReportError("DIE has invalid DW_AT_ranges encoding:");
Greg Claytonc5b2d562017-05-03 18:25:46 +0000483 break;
484 case DW_AT_stmt_list:
485 // Make sure the offset in the DW_AT_stmt_list attribute is valid.
486 if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
George Rimar144e4c52017-10-27 10:42:04 +0000487 if (*SectionOffset >= DObj.getLineSection().Data.size())
488 ReportError("DW_AT_stmt_list offset is beyond .debug_line bounds: " +
George Rimar3d07f602017-10-27 10:58:04 +0000489 llvm::formatv("{0:x8}", *SectionOffset));
George Rimar144e4c52017-10-27 10:42:04 +0000490 break;
Greg Claytonc5b2d562017-05-03 18:25:46 +0000491 }
George Rimar144e4c52017-10-27 10:42:04 +0000492 ReportError("DIE has invalid DW_AT_stmt_list encoding:");
Greg Claytonc5b2d562017-05-03 18:25:46 +0000493 break;
George Rimar144e4c52017-10-27 10:42:04 +0000494 case DW_AT_location: {
Jonas Devlieghere7e0b0232018-05-22 17:37:27 +0000495 auto VerifyLocationExpr = [&](StringRef D) {
Jonas Devlieghere7d4a9742018-02-17 13:06:37 +0000496 DWARFUnit *U = Die.getDwarfUnit();
497 DataExtractor Data(D, DCtx.isLittleEndian(), 0);
498 DWARFExpression Expression(Data, U->getVersion(),
499 U->getAddressByteSize());
500 bool Error = llvm::any_of(Expression, [](DWARFExpression::Operation &Op) {
501 return Op.isError();
502 });
503 if (Error)
504 ReportError("DIE contains invalid DWARF expression:");
505 };
506 if (Optional<ArrayRef<uint8_t>> Expr = AttrValue.Value.getAsBlock()) {
507 // Verify inlined location.
Jonas Devlieghere7e0b0232018-05-22 17:37:27 +0000508 VerifyLocationExpr(llvm::toStringRef(*Expr));
509 } else if (auto LocOffset = AttrValue.Value.getAsSectionOffset()) {
Jonas Devlieghere7d4a9742018-02-17 13:06:37 +0000510 // Verify location list.
511 if (auto DebugLoc = DCtx.getDebugLoc())
512 if (auto LocList = DebugLoc->getLocationListAtOffset(*LocOffset))
513 for (const auto &Entry : LocList->Entries)
Jonas Devlieghere7e0b0232018-05-22 17:37:27 +0000514 VerifyLocationExpr({Entry.Loc.data(), Entry.Loc.size()});
George Rimar144e4c52017-10-27 10:42:04 +0000515 }
George Rimar144e4c52017-10-27 10:42:04 +0000516 break;
517 }
Jonas Devlieghere7ef2c202018-09-21 07:49:29 +0000518 case DW_AT_specification:
519 case DW_AT_abstract_origin: {
520 if (auto ReferencedDie = Die.getAttributeValueAsReferencedDie(Attr)) {
521 auto DieTag = Die.getTag();
522 auto RefTag = ReferencedDie.getTag();
523 if (DieTag == RefTag)
524 break;
525 if (DieTag == DW_TAG_inlined_subroutine && RefTag == DW_TAG_subprogram)
526 break;
527 if (DieTag == DW_TAG_variable && RefTag == DW_TAG_member)
528 break;
529 ReportError("DIE with tag " + TagString(DieTag) + " has " +
530 AttributeString(Attr) +
531 " that points to DIE with "
532 "incompatible tag " +
533 TagString(RefTag));
534 }
David Bolvansky7e30c912018-10-10 20:10:37 +0000535 break;
Jonas Devlieghere7ef2c202018-09-21 07:49:29 +0000536 }
Jonas Devlieghereb3227422018-09-21 07:50:21 +0000537 case DW_AT_type: {
538 DWARFDie TypeDie = Die.getAttributeValueAsReferencedDie(DW_AT_type);
539 if (TypeDie && !isType(TypeDie.getTag())) {
540 ReportError("DIE has " + AttributeString(Attr) +
541 " with incompatible tag " + TagString(TypeDie.getTag()));
Jonas Devlieghereb3227422018-09-21 07:50:21 +0000542 }
David Bolvansky7e30c912018-10-10 20:10:37 +0000543 break;
Jonas Devlieghereb3227422018-09-21 07:50:21 +0000544 }
Greg Claytonc5b2d562017-05-03 18:25:46 +0000545 default:
546 break;
547 }
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000548 return NumErrors;
Greg Claytonc5b2d562017-05-03 18:25:46 +0000549}
Greg Claytonb8c162b2017-05-03 16:02:29 +0000550
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000551unsigned DWARFVerifier::verifyDebugInfoForm(const DWARFDie &Die,
552 DWARFAttribute &AttrValue) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000553 const DWARFObject &DObj = DCtx.getDWARFObj();
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000554 unsigned NumErrors = 0;
Greg Claytonc5b2d562017-05-03 18:25:46 +0000555 const auto Form = AttrValue.Value.getForm();
556 switch (Form) {
557 case DW_FORM_ref1:
558 case DW_FORM_ref2:
559 case DW_FORM_ref4:
560 case DW_FORM_ref8:
561 case DW_FORM_ref_udata: {
562 // Verify all CU relative references are valid CU offsets.
563 Optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
564 assert(RefVal);
565 if (RefVal) {
566 auto DieCU = Die.getDwarfUnit();
567 auto CUSize = DieCU->getNextUnitOffset() - DieCU->getOffset();
568 auto CUOffset = AttrValue.Value.getRawUValue();
569 if (CUOffset >= CUSize) {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000570 ++NumErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000571 error() << FormEncodingString(Form) << " CU offset "
572 << format("0x%08" PRIx64, CUOffset)
573 << " is invalid (must be less than CU size of "
574 << format("0x%08" PRIx32, CUSize) << "):\n";
Adrian Prantld3f9f212017-09-20 17:44:00 +0000575 Die.dump(OS, 0, DumpOpts);
Jonas Devliegheref1f3e732018-09-19 08:08:13 +0000576 dump(Die) << '\n';
Greg Claytonc5b2d562017-05-03 18:25:46 +0000577 } else {
578 // Valid reference, but we will verify it points to an actual
579 // DIE later.
580 ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset());
Greg Claytonb8c162b2017-05-03 16:02:29 +0000581 }
582 }
Greg Claytonc5b2d562017-05-03 18:25:46 +0000583 break;
Greg Claytonb8c162b2017-05-03 16:02:29 +0000584 }
Greg Claytonc5b2d562017-05-03 18:25:46 +0000585 case DW_FORM_ref_addr: {
586 // Verify all absolute DIE references have valid offsets in the
587 // .debug_info section.
588 Optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
589 assert(RefVal);
590 if (RefVal) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000591 if (*RefVal >= DObj.getInfoSection().Data.size()) {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000592 ++NumErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000593 error() << "DW_FORM_ref_addr offset beyond .debug_info "
594 "bounds:\n";
Jonas Devliegheref1f3e732018-09-19 08:08:13 +0000595 dump(Die) << '\n';
Greg Claytonc5b2d562017-05-03 18:25:46 +0000596 } else {
597 // Valid reference, but we will verify it points to an actual
598 // DIE later.
599 ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset());
600 }
601 }
602 break;
603 }
604 case DW_FORM_strp: {
605 auto SecOffset = AttrValue.Value.getAsSectionOffset();
606 assert(SecOffset); // DW_FORM_strp is a section offset.
Rafael Espindolac398e672017-07-19 22:27:28 +0000607 if (SecOffset && *SecOffset >= DObj.getStringSection().size()) {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000608 ++NumErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000609 error() << "DW_FORM_strp offset beyond .debug_str bounds:\n";
Jonas Devliegheref1f3e732018-09-19 08:08:13 +0000610 dump(Die) << '\n';
Greg Claytonc5b2d562017-05-03 18:25:46 +0000611 }
612 break;
613 }
614 default:
615 break;
616 }
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000617 return NumErrors;
Greg Claytonc5b2d562017-05-03 18:25:46 +0000618}
Greg Claytonb8c162b2017-05-03 16:02:29 +0000619
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000620unsigned DWARFVerifier::verifyDebugInfoReferences() {
Greg Claytonb8c162b2017-05-03 16:02:29 +0000621 // Take all references and make sure they point to an actual DIE by
622 // getting the DIE by offset and emitting an error
623 OS << "Verifying .debug_info references...\n";
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000624 unsigned NumErrors = 0;
Greg Claytonb8c162b2017-05-03 16:02:29 +0000625 for (auto Pair : ReferenceToDIEOffsets) {
626 auto Die = DCtx.getDIEForOffset(Pair.first);
627 if (Die)
628 continue;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000629 ++NumErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000630 error() << "invalid DIE reference " << format("0x%08" PRIx64, Pair.first)
631 << ". Offset is in between DIEs:\n";
Jonas Devliegheref1f3e732018-09-19 08:08:13 +0000632 for (auto Offset : Pair.second)
633 dump(DCtx.getDIEForOffset(Offset)) << '\n';
Greg Claytonb8c162b2017-05-03 16:02:29 +0000634 OS << "\n";
635 }
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000636 return NumErrors;
Greg Claytonb8c162b2017-05-03 16:02:29 +0000637}
638
Greg Claytonc5b2d562017-05-03 18:25:46 +0000639void DWARFVerifier::verifyDebugLineStmtOffsets() {
Greg Claytonb8c162b2017-05-03 16:02:29 +0000640 std::map<uint64_t, DWARFDie> StmtListToDie;
Greg Claytonb8c162b2017-05-03 16:02:29 +0000641 for (const auto &CU : DCtx.compile_units()) {
Greg Claytonc5b2d562017-05-03 18:25:46 +0000642 auto Die = CU->getUnitDIE();
Greg Claytonb8c162b2017-05-03 16:02:29 +0000643 // Get the attribute value as a section offset. No need to produce an
644 // error here if the encoding isn't correct because we validate this in
645 // the .debug_info verifier.
Greg Claytonc5b2d562017-05-03 18:25:46 +0000646 auto StmtSectionOffset = toSectionOffset(Die.find(DW_AT_stmt_list));
Greg Claytonb8c162b2017-05-03 16:02:29 +0000647 if (!StmtSectionOffset)
648 continue;
649 const uint32_t LineTableOffset = *StmtSectionOffset;
Greg Claytonc5b2d562017-05-03 18:25:46 +0000650 auto LineTable = DCtx.getLineTableForUnit(CU.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000651 if (LineTableOffset < DCtx.getDWARFObj().getLineSection().Data.size()) {
Greg Claytonc5b2d562017-05-03 18:25:46 +0000652 if (!LineTable) {
653 ++NumDebugLineErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000654 error() << ".debug_line[" << format("0x%08" PRIx32, LineTableOffset)
655 << "] was not able to be parsed for CU:\n";
Jonas Devliegheref1f3e732018-09-19 08:08:13 +0000656 dump(Die) << '\n';
Greg Claytonc5b2d562017-05-03 18:25:46 +0000657 continue;
658 }
659 } else {
660 // Make sure we don't get a valid line table back if the offset is wrong.
661 assert(LineTable == nullptr);
Greg Claytonb8c162b2017-05-03 16:02:29 +0000662 // Skip this line table as it isn't valid. No need to create an error
663 // here because we validate this in the .debug_info verifier.
664 continue;
665 }
Greg Claytonb8c162b2017-05-03 16:02:29 +0000666 auto Iter = StmtListToDie.find(LineTableOffset);
667 if (Iter != StmtListToDie.end()) {
668 ++NumDebugLineErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000669 error() << "two compile unit DIEs, "
670 << format("0x%08" PRIx32, Iter->second.getOffset()) << " and "
671 << format("0x%08" PRIx32, Die.getOffset())
672 << ", have the same DW_AT_stmt_list section offset:\n";
Jonas Devliegheref1f3e732018-09-19 08:08:13 +0000673 dump(Iter->second);
674 dump(Die) << '\n';
Greg Claytonb8c162b2017-05-03 16:02:29 +0000675 // Already verified this line table before, no need to do it again.
676 continue;
677 }
Greg Claytonc5b2d562017-05-03 18:25:46 +0000678 StmtListToDie[LineTableOffset] = Die;
679 }
680}
Greg Claytonb8c162b2017-05-03 16:02:29 +0000681
Greg Claytonc5b2d562017-05-03 18:25:46 +0000682void DWARFVerifier::verifyDebugLineRows() {
683 for (const auto &CU : DCtx.compile_units()) {
684 auto Die = CU->getUnitDIE();
Greg Claytonb8c162b2017-05-03 16:02:29 +0000685 auto LineTable = DCtx.getLineTableForUnit(CU.get());
Greg Claytonc5b2d562017-05-03 18:25:46 +0000686 // If there is no line table we will have created an error in the
687 // .debug_info verifier or in verifyDebugLineStmtOffsets().
688 if (!LineTable)
Greg Claytonb8c162b2017-05-03 16:02:29 +0000689 continue;
Jonas Devliegheref4ed65d2017-09-08 09:48:51 +0000690
691 // Verify prologue.
Greg Claytonb8c162b2017-05-03 16:02:29 +0000692 uint32_t MaxFileIndex = LineTable->Prologue.FileNames.size();
Jonas Devliegheref4ed65d2017-09-08 09:48:51 +0000693 uint32_t MaxDirIndex = LineTable->Prologue.IncludeDirectories.size();
694 uint32_t FileIndex = 1;
695 StringMap<uint16_t> FullPathMap;
696 for (const auto &FileName : LineTable->Prologue.FileNames) {
697 // Verify directory index.
698 if (FileName.DirIdx > MaxDirIndex) {
699 ++NumDebugLineErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000700 error() << ".debug_line["
701 << format("0x%08" PRIx64,
702 *toSectionOffset(Die.find(DW_AT_stmt_list)))
703 << "].prologue.file_names[" << FileIndex
704 << "].dir_idx contains an invalid index: " << FileName.DirIdx
705 << "\n";
Jonas Devliegheref4ed65d2017-09-08 09:48:51 +0000706 }
707
708 // Check file paths for duplicates.
709 std::string FullPath;
710 const bool HasFullPath = LineTable->getFileNameByIndex(
711 FileIndex, CU->getCompilationDir(),
712 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FullPath);
713 assert(HasFullPath && "Invalid index?");
714 (void)HasFullPath;
715 auto It = FullPathMap.find(FullPath);
716 if (It == FullPathMap.end())
717 FullPathMap[FullPath] = FileIndex;
718 else if (It->second != FileIndex) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000719 warn() << ".debug_line["
720 << format("0x%08" PRIx64,
721 *toSectionOffset(Die.find(DW_AT_stmt_list)))
722 << "].prologue.file_names[" << FileIndex
723 << "] is a duplicate of file_names[" << It->second << "]\n";
Jonas Devliegheref4ed65d2017-09-08 09:48:51 +0000724 }
725
726 FileIndex++;
727 }
728
729 // Verify rows.
Greg Claytonb8c162b2017-05-03 16:02:29 +0000730 uint64_t PrevAddress = 0;
731 uint32_t RowIndex = 0;
732 for (const auto &Row : LineTable->Rows) {
Jonas Devliegheref4ed65d2017-09-08 09:48:51 +0000733 // Verify row address.
Greg Claytonb8c162b2017-05-03 16:02:29 +0000734 if (Row.Address < PrevAddress) {
735 ++NumDebugLineErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000736 error() << ".debug_line["
737 << format("0x%08" PRIx64,
738 *toSectionOffset(Die.find(DW_AT_stmt_list)))
739 << "] row[" << RowIndex
740 << "] decreases in address from previous row:\n";
Greg Claytonb8c162b2017-05-03 16:02:29 +0000741
742 DWARFDebugLine::Row::dumpTableHeader(OS);
743 if (RowIndex > 0)
744 LineTable->Rows[RowIndex - 1].dump(OS);
745 Row.dump(OS);
746 OS << '\n';
747 }
748
Jonas Devliegheref4ed65d2017-09-08 09:48:51 +0000749 // Verify file index.
Greg Claytonb8c162b2017-05-03 16:02:29 +0000750 if (Row.File > MaxFileIndex) {
751 ++NumDebugLineErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000752 error() << ".debug_line["
753 << format("0x%08" PRIx64,
754 *toSectionOffset(Die.find(DW_AT_stmt_list)))
755 << "][" << RowIndex << "] has invalid file index " << Row.File
756 << " (valid values are [1," << MaxFileIndex << "]):\n";
Greg Claytonb8c162b2017-05-03 16:02:29 +0000757 DWARFDebugLine::Row::dumpTableHeader(OS);
758 Row.dump(OS);
759 OS << '\n';
760 }
761 if (Row.EndSequence)
762 PrevAddress = 0;
763 else
764 PrevAddress = Row.Address;
765 ++RowIndex;
766 }
767 }
Greg Claytonc5b2d562017-05-03 18:25:46 +0000768}
769
Saleem Abdulrasoolec77a652018-10-28 22:30:48 +0000770DWARFVerifier::DWARFVerifier(raw_ostream &S, DWARFContext &D,
771 DIDumpOptions DumpOpts)
772 : OS(S), DCtx(D), DumpOpts(std::move(DumpOpts)), IsObjectFile(false),
773 IsMachOObject(false) {
774 if (const auto *F = DCtx.getDWARFObj().getFile()) {
775 IsObjectFile = F->isRelocatableObject();
776 IsMachOObject = F->isMachO();
777 }
778}
779
Greg Claytonc5b2d562017-05-03 18:25:46 +0000780bool DWARFVerifier::handleDebugLine() {
781 NumDebugLineErrors = 0;
782 OS << "Verifying .debug_line...\n";
783 verifyDebugLineStmtOffsets();
784 verifyDebugLineRows();
Greg Claytonb8c162b2017-05-03 16:02:29 +0000785 return NumDebugLineErrors == 0;
786}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000787
Pavel Labath9b36fd22018-01-22 13:17:23 +0000788unsigned DWARFVerifier::verifyAppleAccelTable(const DWARFSection *AccelSection,
789 DataExtractor *StrData,
790 const char *SectionName) {
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000791 unsigned NumErrors = 0;
792 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), *AccelSection,
793 DCtx.isLittleEndian(), 0);
Pavel Labath9b36fd22018-01-22 13:17:23 +0000794 AppleAcceleratorTable AccelTable(AccelSectionData, *StrData);
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000795
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000796 OS << "Verifying " << SectionName << "...\n";
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000797
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000798 // Verify that the fixed part of the header is not too short.
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000799 if (!AccelSectionData.isValidOffset(AccelTable.getSizeHdr())) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000800 error() << "Section is too small to fit a section header.\n";
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000801 return 1;
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000802 }
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000803
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000804 // Verify that the section is not too short.
Jonas Devlieghereba915892017-12-11 18:22:47 +0000805 if (Error E = AccelTable.extract()) {
806 error() << toString(std::move(E)) << '\n';
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000807 return 1;
808 }
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000809
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000810 // Verify that all buckets have a valid hash index or are empty.
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000811 uint32_t NumBuckets = AccelTable.getNumBuckets();
812 uint32_t NumHashes = AccelTable.getNumHashes();
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000813
814 uint32_t BucketsOffset =
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000815 AccelTable.getSizeHdr() + AccelTable.getHeaderDataLength();
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000816 uint32_t HashesBase = BucketsOffset + NumBuckets * 4;
817 uint32_t OffsetsBase = HashesBase + NumHashes * 4;
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000818 for (uint32_t BucketIdx = 0; BucketIdx < NumBuckets; ++BucketIdx) {
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000819 uint32_t HashIdx = AccelSectionData.getU32(&BucketsOffset);
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000820 if (HashIdx >= NumHashes && HashIdx != UINT32_MAX) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000821 error() << format("Bucket[%d] has invalid hash index: %u.\n", BucketIdx,
822 HashIdx);
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000823 ++NumErrors;
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000824 }
825 }
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000826 uint32_t NumAtoms = AccelTable.getAtomsDesc().size();
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000827 if (NumAtoms == 0) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000828 error() << "No atoms: failed to read HashData.\n";
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000829 return 1;
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000830 }
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000831 if (!AccelTable.validateForms()) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000832 error() << "Unsupported form: failed to read HashData.\n";
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000833 return 1;
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000834 }
835
836 for (uint32_t HashIdx = 0; HashIdx < NumHashes; ++HashIdx) {
837 uint32_t HashOffset = HashesBase + 4 * HashIdx;
838 uint32_t DataOffset = OffsetsBase + 4 * HashIdx;
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000839 uint32_t Hash = AccelSectionData.getU32(&HashOffset);
840 uint32_t HashDataOffset = AccelSectionData.getU32(&DataOffset);
841 if (!AccelSectionData.isValidOffsetForDataOfSize(HashDataOffset,
842 sizeof(uint64_t))) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000843 error() << format("Hash[%d] has invalid HashData offset: 0x%08x.\n",
844 HashIdx, HashDataOffset);
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000845 ++NumErrors;
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000846 }
847
848 uint32_t StrpOffset;
849 uint32_t StringOffset;
850 uint32_t StringCount = 0;
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000851 unsigned Offset;
852 unsigned Tag;
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000853 while ((StrpOffset = AccelSectionData.getU32(&HashDataOffset)) != 0) {
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000854 const uint32_t NumHashDataObjects =
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000855 AccelSectionData.getU32(&HashDataOffset);
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000856 for (uint32_t HashDataIdx = 0; HashDataIdx < NumHashDataObjects;
857 ++HashDataIdx) {
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000858 std::tie(Offset, Tag) = AccelTable.readAtoms(HashDataOffset);
859 auto Die = DCtx.getDIEForOffset(Offset);
860 if (!Die) {
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000861 const uint32_t BucketIdx =
862 NumBuckets ? (Hash % NumBuckets) : UINT32_MAX;
863 StringOffset = StrpOffset;
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000864 const char *Name = StrData->getCStr(&StringOffset);
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000865 if (!Name)
866 Name = "<NULL>";
867
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000868 error() << format(
869 "%s Bucket[%d] Hash[%d] = 0x%08x "
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000870 "Str[%u] = 0x%08x "
871 "DIE[%d] = 0x%08x is not a valid DIE offset for \"%s\".\n",
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000872 SectionName, BucketIdx, HashIdx, Hash, StringCount, StrpOffset,
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000873 HashDataIdx, Offset, Name);
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000874
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000875 ++NumErrors;
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000876 continue;
877 }
878 if ((Tag != dwarf::DW_TAG_null) && (Die.getTag() != Tag)) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000879 error() << "Tag " << dwarf::TagString(Tag)
880 << " in accelerator table does not match Tag "
881 << dwarf::TagString(Die.getTag()) << " of DIE[" << HashDataIdx
882 << "].\n";
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000883 ++NumErrors;
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000884 }
885 }
886 ++StringCount;
887 }
888 }
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000889 return NumErrors;
890}
891
Pavel Labathb136c392018-03-08 15:34:42 +0000892unsigned
893DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames &AccelTable) {
894 // A map from CU offset to the (first) Name Index offset which claims to index
895 // this CU.
896 DenseMap<uint32_t, uint32_t> CUMap;
897 const uint32_t NotIndexed = std::numeric_limits<uint32_t>::max();
898
899 CUMap.reserve(DCtx.getNumCompileUnits());
900 for (const auto &CU : DCtx.compile_units())
901 CUMap[CU->getOffset()] = NotIndexed;
902
903 unsigned NumErrors = 0;
904 for (const DWARFDebugNames::NameIndex &NI : AccelTable) {
905 if (NI.getCUCount() == 0) {
906 error() << formatv("Name Index @ {0:x} does not index any CU\n",
907 NI.getUnitOffset());
908 ++NumErrors;
909 continue;
910 }
911 for (uint32_t CU = 0, End = NI.getCUCount(); CU < End; ++CU) {
912 uint32_t Offset = NI.getCUOffset(CU);
913 auto Iter = CUMap.find(Offset);
914
915 if (Iter == CUMap.end()) {
916 error() << formatv(
917 "Name Index @ {0:x} references a non-existing CU @ {1:x}\n",
918 NI.getUnitOffset(), Offset);
919 ++NumErrors;
920 continue;
921 }
922
923 if (Iter->second != NotIndexed) {
924 error() << formatv("Name Index @ {0:x} references a CU @ {1:x}, but "
Jonas Devlieghere9d7cecf2018-09-17 14:23:47 +0000925 "this CU is already indexed by Name Index @ {2:x}\n",
926 NI.getUnitOffset(), Offset, Iter->second);
Pavel Labathb136c392018-03-08 15:34:42 +0000927 continue;
928 }
929 Iter->second = NI.getUnitOffset();
930 }
931 }
932
933 for (const auto &KV : CUMap) {
934 if (KV.second == NotIndexed)
935 warn() << formatv("CU @ {0:x} not covered by any Name Index\n", KV.first);
936 }
937
938 return NumErrors;
939}
940
Pavel Labath906b7772018-03-16 10:02:16 +0000941unsigned
942DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex &NI,
943 const DataExtractor &StrData) {
944 struct BucketInfo {
945 uint32_t Bucket;
946 uint32_t Index;
947
948 constexpr BucketInfo(uint32_t Bucket, uint32_t Index)
949 : Bucket(Bucket), Index(Index) {}
950 bool operator<(const BucketInfo &RHS) const { return Index < RHS.Index; };
951 };
952
953 uint32_t NumErrors = 0;
954 if (NI.getBucketCount() == 0) {
955 warn() << formatv("Name Index @ {0:x} does not contain a hash table.\n",
956 NI.getUnitOffset());
957 return NumErrors;
958 }
959
960 // Build up a list of (Bucket, Index) pairs. We use this later to verify that
961 // each Name is reachable from the appropriate bucket.
962 std::vector<BucketInfo> BucketStarts;
963 BucketStarts.reserve(NI.getBucketCount() + 1);
964 for (uint32_t Bucket = 0, End = NI.getBucketCount(); Bucket < End; ++Bucket) {
965 uint32_t Index = NI.getBucketArrayEntry(Bucket);
966 if (Index > NI.getNameCount()) {
967 error() << formatv("Bucket {0} of Name Index @ {1:x} contains invalid "
968 "value {2}. Valid range is [0, {3}].\n",
969 Bucket, NI.getUnitOffset(), Index, NI.getNameCount());
970 ++NumErrors;
971 continue;
972 }
973 if (Index > 0)
974 BucketStarts.emplace_back(Bucket, Index);
975 }
976
977 // If there were any buckets with invalid values, skip further checks as they
978 // will likely produce many errors which will only confuse the actual root
979 // problem.
980 if (NumErrors > 0)
981 return NumErrors;
982
983 // Sort the list in the order of increasing "Index" entries.
984 array_pod_sort(BucketStarts.begin(), BucketStarts.end());
985
986 // Insert a sentinel entry at the end, so we can check that the end of the
987 // table is covered in the loop below.
988 BucketStarts.emplace_back(NI.getBucketCount(), NI.getNameCount() + 1);
989
990 // Loop invariant: NextUncovered is the (1-based) index of the first Name
991 // which is not reachable by any of the buckets we processed so far (and
992 // hasn't been reported as uncovered).
993 uint32_t NextUncovered = 1;
994 for (const BucketInfo &B : BucketStarts) {
995 // Under normal circumstances B.Index be equal to NextUncovered, but it can
996 // be less if a bucket points to names which are already known to be in some
997 // bucket we processed earlier. In that case, we won't trigger this error,
998 // but report the mismatched hash value error instead. (We know the hash
999 // will not match because we have already verified that the name's hash
1000 // puts it into the previous bucket.)
1001 if (B.Index > NextUncovered) {
1002 error() << formatv("Name Index @ {0:x}: Name table entries [{1}, {2}] "
1003 "are not covered by the hash table.\n",
1004 NI.getUnitOffset(), NextUncovered, B.Index - 1);
1005 ++NumErrors;
1006 }
1007 uint32_t Idx = B.Index;
1008
1009 // The rest of the checks apply only to non-sentinel entries.
1010 if (B.Bucket == NI.getBucketCount())
1011 break;
1012
1013 // This triggers if a non-empty bucket points to a name with a mismatched
1014 // hash. Clients are likely to interpret this as an empty bucket, because a
1015 // mismatched hash signals the end of a bucket, but if this is indeed an
1016 // empty bucket, the producer should have signalled this by marking the
1017 // bucket as empty.
1018 uint32_t FirstHash = NI.getHashArrayEntry(Idx);
1019 if (FirstHash % NI.getBucketCount() != B.Bucket) {
1020 error() << formatv(
1021 "Name Index @ {0:x}: Bucket {1} is not empty but points to a "
1022 "mismatched hash value {2:x} (belonging to bucket {3}).\n",
1023 NI.getUnitOffset(), B.Bucket, FirstHash,
1024 FirstHash % NI.getBucketCount());
1025 ++NumErrors;
1026 }
1027
1028 // This find the end of this bucket and also verifies that all the hashes in
1029 // this bucket are correct by comparing the stored hashes to the ones we
1030 // compute ourselves.
1031 while (Idx <= NI.getNameCount()) {
1032 uint32_t Hash = NI.getHashArrayEntry(Idx);
1033 if (Hash % NI.getBucketCount() != B.Bucket)
1034 break;
1035
Pavel Labathd6ca0632018-06-01 10:33:11 +00001036 const char *Str = NI.getNameTableEntry(Idx).getString();
Pavel Labath906b7772018-03-16 10:02:16 +00001037 if (caseFoldingDjbHash(Str) != Hash) {
1038 error() << formatv("Name Index @ {0:x}: String ({1}) at index {2} "
1039 "hashes to {3:x}, but "
1040 "the Name Index hash is {4:x}\n",
1041 NI.getUnitOffset(), Str, Idx,
1042 caseFoldingDjbHash(Str), Hash);
1043 ++NumErrors;
1044 }
1045
1046 ++Idx;
1047 }
1048 NextUncovered = std::max(NextUncovered, Idx);
1049 }
1050 return NumErrors;
1051}
1052
Pavel Labath79cd9422018-03-22 14:50:44 +00001053unsigned DWARFVerifier::verifyNameIndexAttribute(
1054 const DWARFDebugNames::NameIndex &NI, const DWARFDebugNames::Abbrev &Abbr,
1055 DWARFDebugNames::AttributeEncoding AttrEnc) {
1056 StringRef FormName = dwarf::FormEncodingString(AttrEnc.Form);
1057 if (FormName.empty()) {
1058 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1059 "unknown form: {3}.\n",
1060 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1061 AttrEnc.Form);
1062 return 1;
1063 }
1064
1065 if (AttrEnc.Index == DW_IDX_type_hash) {
1066 if (AttrEnc.Form != dwarf::DW_FORM_data8) {
1067 error() << formatv(
1068 "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_type_hash "
1069 "uses an unexpected form {2} (should be {3}).\n",
1070 NI.getUnitOffset(), Abbr.Code, AttrEnc.Form, dwarf::DW_FORM_data8);
1071 return 1;
1072 }
1073 }
1074
1075 // A list of known index attributes and their expected form classes.
1076 // DW_IDX_type_hash is handled specially in the check above, as it has a
1077 // specific form (not just a form class) we should expect.
1078 struct FormClassTable {
1079 dwarf::Index Index;
1080 DWARFFormValue::FormClass Class;
1081 StringLiteral ClassName;
1082 };
1083 static constexpr FormClassTable Table[] = {
1084 {dwarf::DW_IDX_compile_unit, DWARFFormValue::FC_Constant, {"constant"}},
1085 {dwarf::DW_IDX_type_unit, DWARFFormValue::FC_Constant, {"constant"}},
1086 {dwarf::DW_IDX_die_offset, DWARFFormValue::FC_Reference, {"reference"}},
1087 {dwarf::DW_IDX_parent, DWARFFormValue::FC_Constant, {"constant"}},
1088 };
1089
1090 ArrayRef<FormClassTable> TableRef(Table);
1091 auto Iter = find_if(TableRef, [AttrEnc](const FormClassTable &T) {
1092 return T.Index == AttrEnc.Index;
1093 });
1094 if (Iter == TableRef.end()) {
1095 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains an "
1096 "unknown index attribute: {2}.\n",
1097 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index);
1098 return 0;
1099 }
1100
1101 if (!DWARFFormValue(AttrEnc.Form).isFormClass(Iter->Class)) {
1102 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1103 "unexpected form {3} (expected form class {4}).\n",
1104 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1105 AttrEnc.Form, Iter->ClassName);
1106 return 1;
1107 }
1108 return 0;
1109}
1110
1111unsigned
1112DWARFVerifier::verifyNameIndexAbbrevs(const DWARFDebugNames::NameIndex &NI) {
Pavel Labathc9f07b02018-04-06 13:34:12 +00001113 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0) {
1114 warn() << formatv("Name Index @ {0:x}: Verifying indexes of type units is "
1115 "not currently supported.\n",
1116 NI.getUnitOffset());
1117 return 0;
1118 }
1119
Pavel Labath79cd9422018-03-22 14:50:44 +00001120 unsigned NumErrors = 0;
1121 for (const auto &Abbrev : NI.getAbbrevs()) {
1122 StringRef TagName = dwarf::TagString(Abbrev.Tag);
1123 if (TagName.empty()) {
1124 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} references an "
1125 "unknown tag: {2}.\n",
1126 NI.getUnitOffset(), Abbrev.Code, Abbrev.Tag);
1127 }
1128 SmallSet<unsigned, 5> Attributes;
1129 for (const auto &AttrEnc : Abbrev.Attributes) {
1130 if (!Attributes.insert(AttrEnc.Index).second) {
1131 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains "
1132 "multiple {2} attributes.\n",
1133 NI.getUnitOffset(), Abbrev.Code, AttrEnc.Index);
1134 ++NumErrors;
1135 continue;
1136 }
1137 NumErrors += verifyNameIndexAttribute(NI, Abbrev, AttrEnc);
1138 }
Pavel Labathc9f07b02018-04-06 13:34:12 +00001139
1140 if (NI.getCUCount() > 1 && !Attributes.count(dwarf::DW_IDX_compile_unit)) {
1141 error() << formatv("NameIndex @ {0:x}: Indexing multiple compile units "
1142 "and abbreviation {1:x} has no {2} attribute.\n",
1143 NI.getUnitOffset(), Abbrev.Code,
1144 dwarf::DW_IDX_compile_unit);
1145 ++NumErrors;
1146 }
1147 if (!Attributes.count(dwarf::DW_IDX_die_offset)) {
1148 error() << formatv(
1149 "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n",
1150 NI.getUnitOffset(), Abbrev.Code, dwarf::DW_IDX_die_offset);
1151 ++NumErrors;
1152 }
Pavel Labath79cd9422018-03-22 14:50:44 +00001153 }
1154 return NumErrors;
1155}
1156
Jonas Devlieghere6e5c7e62018-09-03 12:12:17 +00001157static SmallVector<StringRef, 2> getNames(const DWARFDie &DIE,
1158 bool IncludeLinkageName = true) {
Pavel Labathc9f07b02018-04-06 13:34:12 +00001159 SmallVector<StringRef, 2> Result;
1160 if (const char *Str = DIE.getName(DINameKind::ShortName))
1161 Result.emplace_back(Str);
1162 else if (DIE.getTag() == dwarf::DW_TAG_namespace)
1163 Result.emplace_back("(anonymous namespace)");
1164
Jonas Devlieghere6e5c7e62018-09-03 12:12:17 +00001165 if (IncludeLinkageName) {
1166 if (const char *Str = DIE.getName(DINameKind::LinkageName)) {
1167 if (Result.empty() || Result[0] != Str)
1168 Result.emplace_back(Str);
1169 }
Pavel Labathc9f07b02018-04-06 13:34:12 +00001170 }
1171
1172 return Result;
1173}
1174
Pavel Labathd6ca0632018-06-01 10:33:11 +00001175unsigned DWARFVerifier::verifyNameIndexEntries(
1176 const DWARFDebugNames::NameIndex &NI,
1177 const DWARFDebugNames::NameTableEntry &NTE) {
Pavel Labathc9f07b02018-04-06 13:34:12 +00001178 // Verifying type unit indexes not supported.
1179 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0)
1180 return 0;
1181
Pavel Labathd6ca0632018-06-01 10:33:11 +00001182 const char *CStr = NTE.getString();
Pavel Labathc9f07b02018-04-06 13:34:12 +00001183 if (!CStr) {
1184 error() << formatv(
1185 "Name Index @ {0:x}: Unable to get string associated with name {1}.\n",
Pavel Labathd6ca0632018-06-01 10:33:11 +00001186 NI.getUnitOffset(), NTE.getIndex());
Pavel Labathc9f07b02018-04-06 13:34:12 +00001187 return 1;
1188 }
1189 StringRef Str(CStr);
1190
1191 unsigned NumErrors = 0;
1192 unsigned NumEntries = 0;
Pavel Labathd6ca0632018-06-01 10:33:11 +00001193 uint32_t EntryID = NTE.getEntryOffset();
1194 uint32_t NextEntryID = EntryID;
1195 Expected<DWARFDebugNames::Entry> EntryOr = NI.getEntry(&NextEntryID);
1196 for (; EntryOr; ++NumEntries, EntryID = NextEntryID,
1197 EntryOr = NI.getEntry(&NextEntryID)) {
Pavel Labathc9f07b02018-04-06 13:34:12 +00001198 uint32_t CUIndex = *EntryOr->getCUIndex();
1199 if (CUIndex > NI.getCUCount()) {
1200 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an "
1201 "invalid CU index ({2}).\n",
1202 NI.getUnitOffset(), EntryID, CUIndex);
1203 ++NumErrors;
1204 continue;
1205 }
1206 uint32_t CUOffset = NI.getCUOffset(CUIndex);
Pavel Labath4adc88e2018-06-13 08:14:27 +00001207 uint64_t DIEOffset = CUOffset + *EntryOr->getDIEUnitOffset();
Pavel Labathc9f07b02018-04-06 13:34:12 +00001208 DWARFDie DIE = DCtx.getDIEForOffset(DIEOffset);
1209 if (!DIE) {
1210 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a "
1211 "non-existing DIE @ {2:x}.\n",
1212 NI.getUnitOffset(), EntryID, DIEOffset);
1213 ++NumErrors;
1214 continue;
1215 }
1216 if (DIE.getDwarfUnit()->getOffset() != CUOffset) {
1217 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched CU of "
1218 "DIE @ {2:x}: index - {3:x}; debug_info - {4:x}.\n",
1219 NI.getUnitOffset(), EntryID, DIEOffset, CUOffset,
1220 DIE.getDwarfUnit()->getOffset());
1221 ++NumErrors;
1222 }
1223 if (DIE.getTag() != EntryOr->tag()) {
1224 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Tag of "
1225 "DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1226 NI.getUnitOffset(), EntryID, DIEOffset, EntryOr->tag(),
1227 DIE.getTag());
1228 ++NumErrors;
1229 }
1230
1231 auto EntryNames = getNames(DIE);
1232 if (!is_contained(EntryNames, Str)) {
1233 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Name "
1234 "of DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1235 NI.getUnitOffset(), EntryID, DIEOffset, Str,
1236 make_range(EntryNames.begin(), EntryNames.end()));
Pavel Labath2a6afe52018-05-14 14:13:20 +00001237 ++NumErrors;
Pavel Labathc9f07b02018-04-06 13:34:12 +00001238 }
1239 }
1240 handleAllErrors(EntryOr.takeError(),
1241 [&](const DWARFDebugNames::SentinelError &) {
1242 if (NumEntries > 0)
1243 return;
1244 error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is "
1245 "not associated with any entries.\n",
Pavel Labathd6ca0632018-06-01 10:33:11 +00001246 NI.getUnitOffset(), NTE.getIndex(), Str);
Pavel Labathc9f07b02018-04-06 13:34:12 +00001247 ++NumErrors;
1248 },
1249 [&](const ErrorInfoBase &Info) {
Pavel Labathd6ca0632018-06-01 10:33:11 +00001250 error()
1251 << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n",
1252 NI.getUnitOffset(), NTE.getIndex(), Str,
1253 Info.message());
Pavel Labathc9f07b02018-04-06 13:34:12 +00001254 ++NumErrors;
1255 });
1256 return NumErrors;
1257}
1258
Pavel Labath80827f12018-05-15 13:24:10 +00001259static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx) {
1260 Optional<DWARFFormValue> Location = Die.findRecursively(DW_AT_location);
1261 if (!Location)
1262 return false;
1263
1264 auto ContainsInterestingOperators = [&](StringRef D) {
1265 DWARFUnit *U = Die.getDwarfUnit();
1266 DataExtractor Data(D, DCtx.isLittleEndian(), U->getAddressByteSize());
1267 DWARFExpression Expression(Data, U->getVersion(), U->getAddressByteSize());
1268 return any_of(Expression, [](DWARFExpression::Operation &Op) {
1269 return !Op.isError() && (Op.getCode() == DW_OP_addr ||
1270 Op.getCode() == DW_OP_form_tls_address ||
1271 Op.getCode() == DW_OP_GNU_push_tls_address);
1272 });
1273 };
1274
1275 if (Optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) {
1276 // Inlined location.
1277 if (ContainsInterestingOperators(toStringRef(*Expr)))
1278 return true;
1279 } else if (Optional<uint64_t> Offset = Location->getAsSectionOffset()) {
1280 // Location list.
1281 if (const DWARFDebugLoc *DebugLoc = DCtx.getDebugLoc()) {
1282 if (const DWARFDebugLoc::LocationList *LocList =
1283 DebugLoc->getLocationListAtOffset(*Offset)) {
1284 if (any_of(LocList->Entries, [&](const DWARFDebugLoc::Entry &E) {
1285 return ContainsInterestingOperators({E.Loc.data(), E.Loc.size()});
1286 }))
1287 return true;
1288 }
1289 }
1290 }
1291 return false;
1292}
1293
1294unsigned DWARFVerifier::verifyNameIndexCompleteness(
1295 const DWARFDie &Die, const DWARFDebugNames::NameIndex &NI) {
1296
1297 // First check, if the Die should be indexed. The code follows the DWARF v5
1298 // wording as closely as possible.
1299
1300 // "All non-defining declarations (that is, debugging information entries
1301 // with a DW_AT_declaration attribute) are excluded."
1302 if (Die.find(DW_AT_declaration))
1303 return 0;
1304
1305 // "DW_TAG_namespace debugging information entries without a DW_AT_name
1306 // attribute are included with the name “(anonymous namespace)”.
1307 // All other debugging information entries without a DW_AT_name attribute
1308 // are excluded."
1309 // "If a subprogram or inlined subroutine is included, and has a
1310 // DW_AT_linkage_name attribute, there will be an additional index entry for
1311 // the linkage name."
Jonas Devlieghere6e5c7e62018-09-03 12:12:17 +00001312 auto IncludeLinkageName = Die.getTag() == DW_TAG_subprogram ||
1313 Die.getTag() == DW_TAG_inlined_subroutine;
1314 auto EntryNames = getNames(Die, IncludeLinkageName);
Pavel Labath80827f12018-05-15 13:24:10 +00001315 if (EntryNames.empty())
1316 return 0;
1317
1318 // We deviate from the specification here, which says:
1319 // "The name index must contain an entry for each debugging information entry
1320 // that defines a named subprogram, label, variable, type, or namespace,
1321 // subject to ..."
1322 // Instead whitelisting all TAGs representing a "type" or a "subprogram", to
1323 // make sure we catch any missing items, we instead blacklist all TAGs that we
1324 // know shouldn't be indexed.
1325 switch (Die.getTag()) {
Jonas Devlieghere3a92c5c2018-08-03 12:01:43 +00001326 // Compile units and modules have names but shouldn't be indexed.
Pavel Labath80827f12018-05-15 13:24:10 +00001327 case DW_TAG_compile_unit:
Jonas Devlieghere3a92c5c2018-08-03 12:01:43 +00001328 case DW_TAG_module:
Pavel Labath80827f12018-05-15 13:24:10 +00001329 return 0;
1330
1331 // Function and template parameters are not globally visible, so we shouldn't
1332 // index them.
1333 case DW_TAG_formal_parameter:
1334 case DW_TAG_template_value_parameter:
1335 case DW_TAG_template_type_parameter:
1336 case DW_TAG_GNU_template_parameter_pack:
1337 case DW_TAG_GNU_template_template_param:
1338 return 0;
1339
1340 // Object members aren't globally visible.
1341 case DW_TAG_member:
1342 return 0;
1343
1344 // According to a strict reading of the specification, enumerators should not
1345 // be indexed (and LLVM currently does not do that). However, this causes
1346 // problems for the debuggers, so we may need to reconsider this.
1347 case DW_TAG_enumerator:
1348 return 0;
1349
1350 // Imported declarations should not be indexed according to the specification
1351 // and LLVM currently does not do that.
1352 case DW_TAG_imported_declaration:
1353 return 0;
1354
1355 // "DW_TAG_subprogram, DW_TAG_inlined_subroutine, and DW_TAG_label debugging
1356 // information entries without an address attribute (DW_AT_low_pc,
1357 // DW_AT_high_pc, DW_AT_ranges, or DW_AT_entry_pc) are excluded."
1358 case DW_TAG_subprogram:
1359 case DW_TAG_inlined_subroutine:
1360 case DW_TAG_label:
1361 if (Die.findRecursively(
1362 {DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_entry_pc}))
1363 break;
1364 return 0;
1365
1366 // "DW_TAG_variable debugging information entries with a DW_AT_location
1367 // attribute that includes a DW_OP_addr or DW_OP_form_tls_address operator are
1368 // included; otherwise, they are excluded."
1369 //
1370 // LLVM extension: We also add DW_OP_GNU_push_tls_address to this list.
1371 case DW_TAG_variable:
1372 if (isVariableIndexable(Die, DCtx))
1373 break;
1374 return 0;
1375
1376 default:
1377 break;
1378 }
1379
1380 // Now we know that our Die should be present in the Index. Let's check if
1381 // that's the case.
1382 unsigned NumErrors = 0;
Pavel Labath4adc88e2018-06-13 08:14:27 +00001383 uint64_t DieUnitOffset = Die.getOffset() - Die.getDwarfUnit()->getOffset();
Pavel Labath80827f12018-05-15 13:24:10 +00001384 for (StringRef Name : EntryNames) {
Pavel Labath4adc88e2018-06-13 08:14:27 +00001385 if (none_of(NI.equal_range(Name), [&](const DWARFDebugNames::Entry &E) {
1386 return E.getDIEUnitOffset() == DieUnitOffset;
Pavel Labath80827f12018-05-15 13:24:10 +00001387 })) {
1388 error() << formatv("Name Index @ {0:x}: Entry for DIE @ {1:x} ({2}) with "
1389 "name {3} missing.\n",
1390 NI.getUnitOffset(), Die.getOffset(), Die.getTag(),
1391 Name);
1392 ++NumErrors;
1393 }
1394 }
1395 return NumErrors;
1396}
1397
Pavel Labathb136c392018-03-08 15:34:42 +00001398unsigned DWARFVerifier::verifyDebugNames(const DWARFSection &AccelSection,
1399 const DataExtractor &StrData) {
1400 unsigned NumErrors = 0;
1401 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), AccelSection,
1402 DCtx.isLittleEndian(), 0);
1403 DWARFDebugNames AccelTable(AccelSectionData, StrData);
1404
1405 OS << "Verifying .debug_names...\n";
1406
1407 // This verifies that we can read individual name indices and their
1408 // abbreviation tables.
1409 if (Error E = AccelTable.extract()) {
1410 error() << toString(std::move(E)) << '\n';
1411 return 1;
1412 }
1413
1414 NumErrors += verifyDebugNamesCULists(AccelTable);
Pavel Labath906b7772018-03-16 10:02:16 +00001415 for (const auto &NI : AccelTable)
1416 NumErrors += verifyNameIndexBuckets(NI, StrData);
Pavel Labath79cd9422018-03-22 14:50:44 +00001417 for (const auto &NI : AccelTable)
1418 NumErrors += verifyNameIndexAbbrevs(NI);
Pavel Labathb136c392018-03-08 15:34:42 +00001419
Pavel Labathc9f07b02018-04-06 13:34:12 +00001420 // Don't attempt Entry validation if any of the previous checks found errors
1421 if (NumErrors > 0)
1422 return NumErrors;
1423 for (const auto &NI : AccelTable)
Pavel Labathd6ca0632018-06-01 10:33:11 +00001424 for (DWARFDebugNames::NameTableEntry NTE : NI)
1425 NumErrors += verifyNameIndexEntries(NI, NTE);
Pavel Labathc9f07b02018-04-06 13:34:12 +00001426
Pavel Labath80827f12018-05-15 13:24:10 +00001427 if (NumErrors > 0)
1428 return NumErrors;
1429
Paul Robinson143eaea2018-08-01 20:43:47 +00001430 for (const std::unique_ptr<DWARFUnit> &U : DCtx.compile_units()) {
Pavel Labath80827f12018-05-15 13:24:10 +00001431 if (const DWARFDebugNames::NameIndex *NI =
Paul Robinson143eaea2018-08-01 20:43:47 +00001432 AccelTable.getCUNameIndex(U->getOffset())) {
1433 auto *CU = cast<DWARFCompileUnit>(U.get());
Pavel Labath80827f12018-05-15 13:24:10 +00001434 for (const DWARFDebugInfoEntry &Die : CU->dies())
Paul Robinson143eaea2018-08-01 20:43:47 +00001435 NumErrors += verifyNameIndexCompleteness(DWARFDie(CU, &Die), *NI);
Pavel Labath80827f12018-05-15 13:24:10 +00001436 }
1437 }
Pavel Labathb136c392018-03-08 15:34:42 +00001438 return NumErrors;
1439}
1440
Spyridoula Gravanidc635f42017-07-26 00:52:31 +00001441bool DWARFVerifier::handleAccelTables() {
1442 const DWARFObject &D = DCtx.getDWARFObj();
1443 DataExtractor StrData(D.getStringSection(), DCtx.isLittleEndian(), 0);
1444 unsigned NumErrors = 0;
1445 if (!D.getAppleNamesSection().Data.empty())
Jonas Devlieghere9d7cecf2018-09-17 14:23:47 +00001446 NumErrors += verifyAppleAccelTable(&D.getAppleNamesSection(), &StrData,
1447 ".apple_names");
Spyridoula Gravanidc635f42017-07-26 00:52:31 +00001448 if (!D.getAppleTypesSection().Data.empty())
Jonas Devlieghere9d7cecf2018-09-17 14:23:47 +00001449 NumErrors += verifyAppleAccelTable(&D.getAppleTypesSection(), &StrData,
1450 ".apple_types");
Spyridoula Gravanidc635f42017-07-26 00:52:31 +00001451 if (!D.getAppleNamespacesSection().Data.empty())
Pavel Labath9b36fd22018-01-22 13:17:23 +00001452 NumErrors += verifyAppleAccelTable(&D.getAppleNamespacesSection(), &StrData,
Jonas Devlieghere9d7cecf2018-09-17 14:23:47 +00001453 ".apple_namespaces");
Spyridoula Gravanidc635f42017-07-26 00:52:31 +00001454 if (!D.getAppleObjCSection().Data.empty())
Jonas Devlieghere9d7cecf2018-09-17 14:23:47 +00001455 NumErrors += verifyAppleAccelTable(&D.getAppleObjCSection(), &StrData,
1456 ".apple_objc");
Pavel Labathb136c392018-03-08 15:34:42 +00001457
1458 if (!D.getDebugNamesSection().Data.empty())
1459 NumErrors += verifyDebugNames(D.getDebugNamesSection(), StrData);
Spyridoula Gravanidc635f42017-07-26 00:52:31 +00001460 return NumErrors == 0;
Spyridoula Gravanie41823b2017-06-14 00:17:55 +00001461}
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +00001462
Jonas Devlieghere6be1f012018-04-15 08:44:15 +00001463raw_ostream &DWARFVerifier::error() const { return WithColor::error(OS); }
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +00001464
Jonas Devlieghere6be1f012018-04-15 08:44:15 +00001465raw_ostream &DWARFVerifier::warn() const { return WithColor::warning(OS); }
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +00001466
Jonas Devlieghere6be1f012018-04-15 08:44:15 +00001467raw_ostream &DWARFVerifier::note() const { return WithColor::note(OS); }
Jonas Devliegheref1f3e732018-09-19 08:08:13 +00001468
1469raw_ostream &DWARFVerifier::dump(const DWARFDie &Die, unsigned indent) const {
1470 Die.dump(OS, indent, DumpOpts);
1471 return OS;
1472}