blob: d4677f60afa024d9915d14ddb9f59ede337a92c9 [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//===----------------------------------------------------------------------===//
9
10#include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
Pavel Labath79cd9422018-03-22 14:50:44 +000011#include "llvm/ADT/SmallSet.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000012#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
13#include "llvm/DebugInfo/DWARF/DWARFContext.h"
14#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
15#include "llvm/DebugInfo/DWARF/DWARFDie.h"
George Rimar144e4c52017-10-27 10:42:04 +000016#include "llvm/DebugInfo/DWARF/DWARFExpression.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000017#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
18#include "llvm/DebugInfo/DWARF/DWARFSection.h"
Pavel Labath906b7772018-03-16 10:02:16 +000019#include "llvm/Support/DJB.h"
George Rimar144e4c52017-10-27 10:42:04 +000020#include "llvm/Support/FormatVariadic.h"
Jonas Devlieghere69217532018-03-09 09:56:24 +000021#include "llvm/Support/WithColor.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000022#include "llvm/Support/raw_ostream.h"
23#include <map>
24#include <set>
25#include <vector>
26
27using namespace llvm;
28using namespace dwarf;
29using namespace object;
30
Jonas Devlieghere58910602017-09-14 11:33:42 +000031DWARFVerifier::DieRangeInfo::address_range_iterator
32DWARFVerifier::DieRangeInfo::insert(const DWARFAddressRange &R) {
33 auto Begin = Ranges.begin();
34 auto End = Ranges.end();
35 auto Pos = std::lower_bound(Begin, End, R);
36
37 if (Pos != End) {
38 if (Pos->intersects(R))
39 return Pos;
40 if (Pos != Begin) {
41 auto Iter = Pos - 1;
42 if (Iter->intersects(R))
43 return Iter;
44 }
45 }
46
47 Ranges.insert(Pos, R);
48 return Ranges.end();
49}
50
51DWARFVerifier::DieRangeInfo::die_range_info_iterator
52DWARFVerifier::DieRangeInfo::insert(const DieRangeInfo &RI) {
53 auto End = Children.end();
54 auto Iter = Children.begin();
55 while (Iter != End) {
56 if (Iter->intersects(RI))
57 return Iter;
58 ++Iter;
59 }
60 Children.insert(RI);
61 return Children.end();
62}
63
64bool DWARFVerifier::DieRangeInfo::contains(const DieRangeInfo &RHS) const {
65 // Both list of ranges are sorted so we can make this fast.
66
67 if (Ranges.empty() || RHS.Ranges.empty())
68 return false;
69
70 // Since the ranges are sorted we can advance where we start searching with
71 // this object's ranges as we traverse RHS.Ranges.
72 auto End = Ranges.end();
73 auto Iter = findRange(RHS.Ranges.front());
74
75 // Now linearly walk the ranges in this object and see if they contain each
76 // ranges from RHS.Ranges.
77 for (const auto &R : RHS.Ranges) {
78 while (Iter != End) {
79 if (Iter->contains(R))
80 break;
81 ++Iter;
82 }
83 if (Iter == End)
84 return false;
85 }
86 return true;
87}
88
89bool DWARFVerifier::DieRangeInfo::intersects(const DieRangeInfo &RHS) const {
90 if (Ranges.empty() || RHS.Ranges.empty())
91 return false;
92
93 auto End = Ranges.end();
94 auto Iter = findRange(RHS.Ranges.front());
95 for (const auto &R : RHS.Ranges) {
Jonas Devlieghered585a202017-09-14 17:46:23 +000096 if(Iter == End)
97 return false;
Jonas Devlieghere58910602017-09-14 11:33:42 +000098 if (R.HighPC <= Iter->LowPC)
99 continue;
100 while (Iter != End) {
101 if (Iter->intersects(R))
102 return true;
103 ++Iter;
104 }
105 }
106
107 return false;
108}
109
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000110bool DWARFVerifier::verifyUnitHeader(const DWARFDataExtractor DebugInfoData,
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000111 uint32_t *Offset, unsigned UnitIndex,
112 uint8_t &UnitType, bool &isUnitDWARF64) {
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000113 uint32_t AbbrOffset, Length;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000114 uint8_t AddrSize = 0;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000115 uint16_t Version;
116 bool Success = true;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000117
118 bool ValidLength = false;
119 bool ValidVersion = false;
120 bool ValidAddrSize = false;
121 bool ValidType = true;
122 bool ValidAbbrevOffset = true;
123
124 uint32_t OffsetStart = *Offset;
125 Length = DebugInfoData.getU32(Offset);
126 if (Length == UINT32_MAX) {
127 isUnitDWARF64 = true;
128 OS << format(
129 "Unit[%d] is in 64-bit DWARF format; cannot verify from this point.\n",
130 UnitIndex);
131 return false;
132 }
133 Version = DebugInfoData.getU16(Offset);
134
135 if (Version >= 5) {
136 UnitType = DebugInfoData.getU8(Offset);
137 AddrSize = DebugInfoData.getU8(Offset);
138 AbbrOffset = DebugInfoData.getU32(Offset);
Jonas Devliegheref2fa9eb2017-10-06 22:27:31 +0000139 ValidType = dwarf::isUnitType(UnitType);
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000140 } else {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000141 UnitType = 0;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000142 AbbrOffset = DebugInfoData.getU32(Offset);
143 AddrSize = DebugInfoData.getU8(Offset);
144 }
145
146 if (!DCtx.getDebugAbbrev()->getAbbreviationDeclarationSet(AbbrOffset))
147 ValidAbbrevOffset = false;
148
149 ValidLength = DebugInfoData.isValidOffset(OffsetStart + Length + 3);
150 ValidVersion = DWARFContext::isSupportedVersion(Version);
151 ValidAddrSize = AddrSize == 4 || AddrSize == 8;
152 if (!ValidLength || !ValidVersion || !ValidAddrSize || !ValidAbbrevOffset ||
153 !ValidType) {
154 Success = false;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000155 error() << format("Units[%d] - start offset: 0x%08x \n", UnitIndex,
156 OffsetStart);
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000157 if (!ValidLength)
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000158 note() << "The length for this unit is too "
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000159 "large for the .debug_info provided.\n";
160 if (!ValidVersion)
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000161 note() << "The 16 bit unit header version is not valid.\n";
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000162 if (!ValidType)
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000163 note() << "The unit type encoding is not valid.\n";
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000164 if (!ValidAbbrevOffset)
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000165 note() << "The offset into the .debug_abbrev section is "
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000166 "not valid.\n";
167 if (!ValidAddrSize)
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000168 note() << "The address size is unsupported.\n";
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000169 }
170 *Offset = OffsetStart + Length + 4;
171 return Success;
172}
173
Paul Robinson50f8ca32018-06-29 19:17:44 +0000174bool DWARFVerifier::verifyUnitContents(DWARFUnit &Unit, uint8_t UnitType) {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000175 uint32_t NumUnitErrors = 0;
176 unsigned NumDies = Unit.getNumDIEs();
177 for (unsigned I = 0; I < NumDies; ++I) {
178 auto Die = Unit.getDIEAtIndex(I);
179 if (Die.getTag() == DW_TAG_null)
180 continue;
181 for (auto AttrValue : Die.attributes()) {
182 NumUnitErrors += verifyDebugInfoAttribute(Die, AttrValue);
183 NumUnitErrors += verifyDebugInfoForm(Die, AttrValue);
184 }
185 }
Jonas Devlieghere58910602017-09-14 11:33:42 +0000186
Jonas Devliegheref2fa9eb2017-10-06 22:27:31 +0000187 DWARFDie Die = Unit.getUnitDIE(/* ExtractUnitDIEOnly = */ false);
188 if (!Die) {
189 error() << "Compilation unit without DIE.\n";
190 NumUnitErrors++;
191 return NumUnitErrors == 0;
192 }
193
194 if (!dwarf::isUnitType(Die.getTag())) {
195 error() << "Compilation unit root DIE is not a unit DIE: "
196 << dwarf::TagString(Die.getTag()) << ".\n";
Jonas Devlieghere35fdaa92017-09-28 15:57:50 +0000197 NumUnitErrors++;
198 }
199
Jonas Devliegheref2fa9eb2017-10-06 22:27:31 +0000200 if (UnitType != 0 &&
201 !DWARFUnit::isMatchingUnitTypeAndTag(UnitType, Die.getTag())) {
202 error() << "Compilation unit type (" << dwarf::UnitTypeString(UnitType)
203 << ") and root DIE (" << dwarf::TagString(Die.getTag())
204 << ") do not match.\n";
205 NumUnitErrors++;
206 }
207
208 DieRangeInfo RI;
209 NumUnitErrors += verifyDieRanges(Die, RI);
210
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000211 return NumUnitErrors == 0;
212}
213
Spyridoula Gravanic6ef9872017-07-21 00:51:32 +0000214unsigned DWARFVerifier::verifyAbbrevSection(const DWARFDebugAbbrev *Abbrev) {
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000215 unsigned NumErrors = 0;
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000216 if (Abbrev) {
217 const DWARFAbbreviationDeclarationSet *AbbrDecls =
218 Abbrev->getAbbreviationDeclarationSet(0);
219 for (auto AbbrDecl : *AbbrDecls) {
220 SmallDenseSet<uint16_t> AttributeSet;
221 for (auto Attribute : AbbrDecl.attributes()) {
222 auto Result = AttributeSet.insert(Attribute.Attr);
223 if (!Result.second) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000224 error() << "Abbreviation declaration contains multiple "
225 << AttributeString(Attribute.Attr) << " attributes.\n";
Spyridoula Gravanic6ef9872017-07-21 00:51:32 +0000226 AbbrDecl.dump(OS);
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000227 ++NumErrors;
228 }
229 }
230 }
231 }
Spyridoula Gravanic6ef9872017-07-21 00:51:32 +0000232 return NumErrors;
233}
234
235bool DWARFVerifier::handleDebugAbbrev() {
236 OS << "Verifying .debug_abbrev...\n";
237
238 const DWARFObject &DObj = DCtx.getDWARFObj();
239 bool noDebugAbbrev = DObj.getAbbrevSection().empty();
240 bool noDebugAbbrevDWO = DObj.getAbbrevDWOSection().empty();
241
242 if (noDebugAbbrev && noDebugAbbrevDWO) {
243 return true;
244 }
245
246 unsigned NumErrors = 0;
247 if (!noDebugAbbrev)
248 NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrev());
249
250 if (!noDebugAbbrevDWO)
251 NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrevDWO());
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000252 return NumErrors == 0;
253}
254
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000255bool DWARFVerifier::handleDebugInfo() {
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000256 OS << "Verifying .debug_info Unit Header Chain...\n";
257
Rafael Espindolac398e672017-07-19 22:27:28 +0000258 const DWARFObject &DObj = DCtx.getDWARFObj();
259 DWARFDataExtractor DebugInfoData(DObj, DObj.getInfoSection(),
260 DCtx.isLittleEndian(), 0);
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000261 uint32_t NumDebugInfoErrors = 0;
262 uint32_t OffsetStart = 0, Offset = 0, UnitIdx = 0;
263 uint8_t UnitType = 0;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000264 bool isUnitDWARF64 = false;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000265 bool isHeaderChainValid = true;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000266 bool hasDIE = DebugInfoData.isValidOffset(Offset);
Paul Robinson11307fa2018-08-01 20:49:44 +0000267 DWARFUnitVector UnitVector{};
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000268 while (hasDIE) {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000269 OffsetStart = Offset;
270 if (!verifyUnitHeader(DebugInfoData, &Offset, UnitIdx, UnitType,
271 isUnitDWARF64)) {
272 isHeaderChainValid = false;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000273 if (isUnitDWARF64)
274 break;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000275 } else {
Paul Robinson5f53f072018-05-14 20:32:31 +0000276 DWARFUnitHeader Header;
277 Header.extract(DCtx, DebugInfoData, &OffsetStart);
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000278 std::unique_ptr<DWARFUnit> Unit;
279 switch (UnitType) {
280 case dwarf::DW_UT_type:
281 case dwarf::DW_UT_split_type: {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000282 Unit.reset(new DWARFTypeUnit(
Paul Robinson5f53f072018-05-14 20:32:31 +0000283 DCtx, DObj.getInfoSection(), Header, DCtx.getDebugAbbrev(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000284 &DObj.getRangeSection(), DObj.getStringSection(),
285 DObj.getStringOffsetSection(), &DObj.getAppleObjCSection(),
Paul Robinson11307fa2018-08-01 20:49:44 +0000286 DObj.getLineSection(), DCtx.isLittleEndian(), false, UnitVector));
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000287 break;
288 }
289 case dwarf::DW_UT_skeleton:
290 case dwarf::DW_UT_split_compile:
291 case dwarf::DW_UT_compile:
292 case dwarf::DW_UT_partial:
293 // UnitType = 0 means that we are
294 // verifying a compile unit in DWARF v4.
295 case 0: {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000296 Unit.reset(new DWARFCompileUnit(
Paul Robinson5f53f072018-05-14 20:32:31 +0000297 DCtx, DObj.getInfoSection(), Header, DCtx.getDebugAbbrev(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000298 &DObj.getRangeSection(), DObj.getStringSection(),
299 DObj.getStringOffsetSection(), &DObj.getAppleObjCSection(),
Paul Robinson11307fa2018-08-01 20:49:44 +0000300 DObj.getLineSection(), DCtx.isLittleEndian(), false, UnitVector));
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000301 break;
302 }
303 default: { llvm_unreachable("Invalid UnitType."); }
304 }
Jonas Devliegheref2fa9eb2017-10-06 22:27:31 +0000305 if (!verifyUnitContents(*Unit, UnitType))
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000306 ++NumDebugInfoErrors;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000307 }
308 hasDIE = DebugInfoData.isValidOffset(Offset);
309 ++UnitIdx;
310 }
311 if (UnitIdx == 0 && !hasDIE) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000312 warn() << ".debug_info is empty.\n";
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000313 isHeaderChainValid = true;
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000314 }
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000315 NumDebugInfoErrors += verifyDebugInfoReferences();
316 return (isHeaderChainValid && NumDebugInfoErrors == 0);
Spyridoula Gravani890eedc2017-07-13 23:25:24 +0000317}
318
Jonas Devlieghere58910602017-09-14 11:33:42 +0000319unsigned DWARFVerifier::verifyDieRanges(const DWARFDie &Die,
320 DieRangeInfo &ParentRI) {
Spyridoula Gravanie0ba4152017-07-24 21:04:11 +0000321 unsigned NumErrors = 0;
Jonas Devlieghere58910602017-09-14 11:33:42 +0000322
323 if (!Die.isValid())
324 return NumErrors;
325
Wolfgang Pieb61d8c8d2018-06-20 22:56:37 +0000326 auto RangesOrError = Die.getAddressRanges();
327 if (!RangesOrError) {
328 // FIXME: Report the error.
329 ++NumErrors;
330 llvm::consumeError(RangesOrError.takeError());
331 return NumErrors;
332 }
Jonas Devlieghere58910602017-09-14 11:33:42 +0000333
Wolfgang Pieb61d8c8d2018-06-20 22:56:37 +0000334 DWARFAddressRangesVector Ranges = RangesOrError.get();
Jonas Devlieghere58910602017-09-14 11:33:42 +0000335 // Build RI for this DIE and check that ranges within this DIE do not
336 // overlap.
337 DieRangeInfo RI(Die);
338 for (auto Range : Ranges) {
339 if (!Range.valid()) {
Spyridoula Gravanie0ba4152017-07-24 21:04:11 +0000340 ++NumErrors;
Jonas Devliegherea15f25d32017-09-29 15:41:22 +0000341 error() << "Invalid address range " << Range << "\n";
Jonas Devlieghere58910602017-09-14 11:33:42 +0000342 continue;
343 }
344
345 // Verify that ranges don't intersect.
346 const auto IntersectingRange = RI.insert(Range);
347 if (IntersectingRange != RI.Ranges.end()) {
348 ++NumErrors;
Jonas Devliegherea15f25d32017-09-29 15:41:22 +0000349 error() << "DIE has overlapping address ranges: " << Range << " and "
350 << *IntersectingRange << "\n";
Jonas Devlieghere58910602017-09-14 11:33:42 +0000351 break;
Spyridoula Gravanie0ba4152017-07-24 21:04:11 +0000352 }
353 }
Jonas Devlieghere58910602017-09-14 11:33:42 +0000354
355 // Verify that children don't intersect.
356 const auto IntersectingChild = ParentRI.insert(RI);
357 if (IntersectingChild != ParentRI.Children.end()) {
358 ++NumErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000359 error() << "DIEs have overlapping address ranges:";
Jonas Devlieghere58910602017-09-14 11:33:42 +0000360 Die.dump(OS, 0);
361 IntersectingChild->Die.dump(OS, 0);
362 OS << "\n";
363 }
364
365 // Verify that ranges are contained within their parent.
366 bool ShouldBeContained = !Ranges.empty() && !ParentRI.Ranges.empty() &&
367 !(Die.getTag() == DW_TAG_subprogram &&
368 ParentRI.Die.getTag() == DW_TAG_subprogram);
369 if (ShouldBeContained && !ParentRI.contains(RI)) {
370 ++NumErrors;
Jonas Devlieghere63eca152018-05-22 17:38:03 +0000371 error() << "DIE address ranges are not contained in its parent's ranges:";
Jonas Devlieghere58910602017-09-14 11:33:42 +0000372 ParentRI.Die.dump(OS, 0);
Jonas Devlieghere63eca152018-05-22 17:38:03 +0000373 Die.dump(OS, 2);
Jonas Devlieghere58910602017-09-14 11:33:42 +0000374 OS << "\n";
375 }
376
377 // Recursively check children.
378 for (DWARFDie Child : Die)
379 NumErrors += verifyDieRanges(Child, RI);
380
Spyridoula Gravanie0ba4152017-07-24 21:04:11 +0000381 return NumErrors;
382}
383
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000384unsigned DWARFVerifier::verifyDebugInfoAttribute(const DWARFDie &Die,
385 DWARFAttribute &AttrValue) {
386 unsigned NumErrors = 0;
George Rimar144e4c52017-10-27 10:42:04 +0000387 auto ReportError = [&](const Twine &TitleMsg) {
388 ++NumErrors;
389 error() << TitleMsg << '\n';
390 Die.dump(OS, 0, DumpOpts);
391 OS << "\n";
392 };
393
394 const DWARFObject &DObj = DCtx.getDWARFObj();
Greg Claytonc5b2d562017-05-03 18:25:46 +0000395 const auto Attr = AttrValue.Attr;
396 switch (Attr) {
397 case DW_AT_ranges:
398 // Make sure the offset in the DW_AT_ranges attribute is valid.
399 if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
George Rimar144e4c52017-10-27 10:42:04 +0000400 if (*SectionOffset >= DObj.getRangeSection().Data.size())
401 ReportError("DW_AT_ranges offset is beyond .debug_ranges bounds:");
402 break;
Greg Claytonc5b2d562017-05-03 18:25:46 +0000403 }
George Rimar144e4c52017-10-27 10:42:04 +0000404 ReportError("DIE has invalid DW_AT_ranges encoding:");
Greg Claytonc5b2d562017-05-03 18:25:46 +0000405 break;
406 case DW_AT_stmt_list:
407 // Make sure the offset in the DW_AT_stmt_list attribute is valid.
408 if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
George Rimar144e4c52017-10-27 10:42:04 +0000409 if (*SectionOffset >= DObj.getLineSection().Data.size())
410 ReportError("DW_AT_stmt_list offset is beyond .debug_line bounds: " +
George Rimar3d07f602017-10-27 10:58:04 +0000411 llvm::formatv("{0:x8}", *SectionOffset));
George Rimar144e4c52017-10-27 10:42:04 +0000412 break;
Greg Claytonc5b2d562017-05-03 18:25:46 +0000413 }
George Rimar144e4c52017-10-27 10:42:04 +0000414 ReportError("DIE has invalid DW_AT_stmt_list encoding:");
Greg Claytonc5b2d562017-05-03 18:25:46 +0000415 break;
George Rimar144e4c52017-10-27 10:42:04 +0000416 case DW_AT_location: {
Jonas Devlieghere7e0b0232018-05-22 17:37:27 +0000417 auto VerifyLocationExpr = [&](StringRef D) {
Jonas Devlieghere7d4a9742018-02-17 13:06:37 +0000418 DWARFUnit *U = Die.getDwarfUnit();
419 DataExtractor Data(D, DCtx.isLittleEndian(), 0);
420 DWARFExpression Expression(Data, U->getVersion(),
421 U->getAddressByteSize());
422 bool Error = llvm::any_of(Expression, [](DWARFExpression::Operation &Op) {
423 return Op.isError();
424 });
425 if (Error)
426 ReportError("DIE contains invalid DWARF expression:");
427 };
428 if (Optional<ArrayRef<uint8_t>> Expr = AttrValue.Value.getAsBlock()) {
429 // Verify inlined location.
Jonas Devlieghere7e0b0232018-05-22 17:37:27 +0000430 VerifyLocationExpr(llvm::toStringRef(*Expr));
431 } else if (auto LocOffset = AttrValue.Value.getAsSectionOffset()) {
Jonas Devlieghere7d4a9742018-02-17 13:06:37 +0000432 // Verify location list.
433 if (auto DebugLoc = DCtx.getDebugLoc())
434 if (auto LocList = DebugLoc->getLocationListAtOffset(*LocOffset))
435 for (const auto &Entry : LocList->Entries)
Jonas Devlieghere7e0b0232018-05-22 17:37:27 +0000436 VerifyLocationExpr({Entry.Loc.data(), Entry.Loc.size()});
George Rimar144e4c52017-10-27 10:42:04 +0000437 }
George Rimar144e4c52017-10-27 10:42:04 +0000438 break;
439 }
Greg Claytonb8c162b2017-05-03 16:02:29 +0000440
Greg Claytonc5b2d562017-05-03 18:25:46 +0000441 default:
442 break;
443 }
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000444 return NumErrors;
Greg Claytonc5b2d562017-05-03 18:25:46 +0000445}
Greg Claytonb8c162b2017-05-03 16:02:29 +0000446
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000447unsigned DWARFVerifier::verifyDebugInfoForm(const DWARFDie &Die,
448 DWARFAttribute &AttrValue) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000449 const DWARFObject &DObj = DCtx.getDWARFObj();
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000450 unsigned NumErrors = 0;
Greg Claytonc5b2d562017-05-03 18:25:46 +0000451 const auto Form = AttrValue.Value.getForm();
452 switch (Form) {
453 case DW_FORM_ref1:
454 case DW_FORM_ref2:
455 case DW_FORM_ref4:
456 case DW_FORM_ref8:
457 case DW_FORM_ref_udata: {
458 // Verify all CU relative references are valid CU offsets.
459 Optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
460 assert(RefVal);
461 if (RefVal) {
462 auto DieCU = Die.getDwarfUnit();
463 auto CUSize = DieCU->getNextUnitOffset() - DieCU->getOffset();
464 auto CUOffset = AttrValue.Value.getRawUValue();
465 if (CUOffset >= CUSize) {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000466 ++NumErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000467 error() << FormEncodingString(Form) << " CU offset "
468 << format("0x%08" PRIx64, CUOffset)
469 << " is invalid (must be less than CU size of "
470 << format("0x%08" PRIx32, CUSize) << "):\n";
Adrian Prantld3f9f212017-09-20 17:44:00 +0000471 Die.dump(OS, 0, DumpOpts);
Greg Claytonc5b2d562017-05-03 18:25:46 +0000472 OS << "\n";
473 } else {
474 // Valid reference, but we will verify it points to an actual
475 // DIE later.
476 ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset());
Greg Claytonb8c162b2017-05-03 16:02:29 +0000477 }
478 }
Greg Claytonc5b2d562017-05-03 18:25:46 +0000479 break;
Greg Claytonb8c162b2017-05-03 16:02:29 +0000480 }
Greg Claytonc5b2d562017-05-03 18:25:46 +0000481 case DW_FORM_ref_addr: {
482 // Verify all absolute DIE references have valid offsets in the
483 // .debug_info section.
484 Optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
485 assert(RefVal);
486 if (RefVal) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000487 if (*RefVal >= DObj.getInfoSection().Data.size()) {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000488 ++NumErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000489 error() << "DW_FORM_ref_addr offset beyond .debug_info "
490 "bounds:\n";
Adrian Prantld3f9f212017-09-20 17:44:00 +0000491 Die.dump(OS, 0, DumpOpts);
Greg Claytonc5b2d562017-05-03 18:25:46 +0000492 OS << "\n";
493 } else {
494 // Valid reference, but we will verify it points to an actual
495 // DIE later.
496 ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset());
497 }
498 }
499 break;
500 }
501 case DW_FORM_strp: {
502 auto SecOffset = AttrValue.Value.getAsSectionOffset();
503 assert(SecOffset); // DW_FORM_strp is a section offset.
Rafael Espindolac398e672017-07-19 22:27:28 +0000504 if (SecOffset && *SecOffset >= DObj.getStringSection().size()) {
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000505 ++NumErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000506 error() << "DW_FORM_strp offset beyond .debug_str bounds:\n";
Adrian Prantld3f9f212017-09-20 17:44:00 +0000507 Die.dump(OS, 0, DumpOpts);
Greg Claytonc5b2d562017-05-03 18:25:46 +0000508 OS << "\n";
509 }
510 break;
511 }
512 default:
513 break;
514 }
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000515 return NumErrors;
Greg Claytonc5b2d562017-05-03 18:25:46 +0000516}
Greg Claytonb8c162b2017-05-03 16:02:29 +0000517
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000518unsigned DWARFVerifier::verifyDebugInfoReferences() {
Greg Claytonb8c162b2017-05-03 16:02:29 +0000519 // Take all references and make sure they point to an actual DIE by
520 // getting the DIE by offset and emitting an error
521 OS << "Verifying .debug_info references...\n";
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000522 unsigned NumErrors = 0;
Greg Claytonb8c162b2017-05-03 16:02:29 +0000523 for (auto Pair : ReferenceToDIEOffsets) {
524 auto Die = DCtx.getDIEForOffset(Pair.first);
525 if (Die)
526 continue;
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000527 ++NumErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000528 error() << "invalid DIE reference " << format("0x%08" PRIx64, Pair.first)
529 << ". Offset is in between DIEs:\n";
Greg Claytonb8c162b2017-05-03 16:02:29 +0000530 for (auto Offset : Pair.second) {
531 auto ReferencingDie = DCtx.getDIEForOffset(Offset);
Adrian Prantld3f9f212017-09-20 17:44:00 +0000532 ReferencingDie.dump(OS, 0, DumpOpts);
Greg Claytonb8c162b2017-05-03 16:02:29 +0000533 OS << "\n";
534 }
535 OS << "\n";
536 }
Spyridoula Gravanif6bd788d2017-07-18 01:00:26 +0000537 return NumErrors;
Greg Claytonb8c162b2017-05-03 16:02:29 +0000538}
539
Greg Claytonc5b2d562017-05-03 18:25:46 +0000540void DWARFVerifier::verifyDebugLineStmtOffsets() {
Greg Claytonb8c162b2017-05-03 16:02:29 +0000541 std::map<uint64_t, DWARFDie> StmtListToDie;
Greg Claytonb8c162b2017-05-03 16:02:29 +0000542 for (const auto &CU : DCtx.compile_units()) {
Greg Claytonc5b2d562017-05-03 18:25:46 +0000543 auto Die = CU->getUnitDIE();
Greg Claytonb8c162b2017-05-03 16:02:29 +0000544 // Get the attribute value as a section offset. No need to produce an
545 // error here if the encoding isn't correct because we validate this in
546 // the .debug_info verifier.
Greg Claytonc5b2d562017-05-03 18:25:46 +0000547 auto StmtSectionOffset = toSectionOffset(Die.find(DW_AT_stmt_list));
Greg Claytonb8c162b2017-05-03 16:02:29 +0000548 if (!StmtSectionOffset)
549 continue;
550 const uint32_t LineTableOffset = *StmtSectionOffset;
Greg Claytonc5b2d562017-05-03 18:25:46 +0000551 auto LineTable = DCtx.getLineTableForUnit(CU.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000552 if (LineTableOffset < DCtx.getDWARFObj().getLineSection().Data.size()) {
Greg Claytonc5b2d562017-05-03 18:25:46 +0000553 if (!LineTable) {
554 ++NumDebugLineErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000555 error() << ".debug_line[" << format("0x%08" PRIx32, LineTableOffset)
556 << "] was not able to be parsed for CU:\n";
Adrian Prantld3f9f212017-09-20 17:44:00 +0000557 Die.dump(OS, 0, DumpOpts);
Greg Claytonc5b2d562017-05-03 18:25:46 +0000558 OS << '\n';
559 continue;
560 }
561 } else {
562 // Make sure we don't get a valid line table back if the offset is wrong.
563 assert(LineTable == nullptr);
Greg Claytonb8c162b2017-05-03 16:02:29 +0000564 // Skip this line table as it isn't valid. No need to create an error
565 // here because we validate this in the .debug_info verifier.
566 continue;
567 }
Greg Claytonb8c162b2017-05-03 16:02:29 +0000568 auto Iter = StmtListToDie.find(LineTableOffset);
569 if (Iter != StmtListToDie.end()) {
570 ++NumDebugLineErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000571 error() << "two compile unit DIEs, "
572 << format("0x%08" PRIx32, Iter->second.getOffset()) << " and "
573 << format("0x%08" PRIx32, Die.getOffset())
574 << ", have the same DW_AT_stmt_list section offset:\n";
Adrian Prantld3f9f212017-09-20 17:44:00 +0000575 Iter->second.dump(OS, 0, DumpOpts);
576 Die.dump(OS, 0, DumpOpts);
Greg Claytonb8c162b2017-05-03 16:02:29 +0000577 OS << '\n';
578 // Already verified this line table before, no need to do it again.
579 continue;
580 }
Greg Claytonc5b2d562017-05-03 18:25:46 +0000581 StmtListToDie[LineTableOffset] = Die;
582 }
583}
Greg Claytonb8c162b2017-05-03 16:02:29 +0000584
Greg Claytonc5b2d562017-05-03 18:25:46 +0000585void DWARFVerifier::verifyDebugLineRows() {
586 for (const auto &CU : DCtx.compile_units()) {
587 auto Die = CU->getUnitDIE();
Greg Claytonb8c162b2017-05-03 16:02:29 +0000588 auto LineTable = DCtx.getLineTableForUnit(CU.get());
Greg Claytonc5b2d562017-05-03 18:25:46 +0000589 // If there is no line table we will have created an error in the
590 // .debug_info verifier or in verifyDebugLineStmtOffsets().
591 if (!LineTable)
Greg Claytonb8c162b2017-05-03 16:02:29 +0000592 continue;
Jonas Devliegheref4ed65d2017-09-08 09:48:51 +0000593
594 // Verify prologue.
Greg Claytonb8c162b2017-05-03 16:02:29 +0000595 uint32_t MaxFileIndex = LineTable->Prologue.FileNames.size();
Jonas Devliegheref4ed65d2017-09-08 09:48:51 +0000596 uint32_t MaxDirIndex = LineTable->Prologue.IncludeDirectories.size();
597 uint32_t FileIndex = 1;
598 StringMap<uint16_t> FullPathMap;
599 for (const auto &FileName : LineTable->Prologue.FileNames) {
600 // Verify directory index.
601 if (FileName.DirIdx > MaxDirIndex) {
602 ++NumDebugLineErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000603 error() << ".debug_line["
604 << format("0x%08" PRIx64,
605 *toSectionOffset(Die.find(DW_AT_stmt_list)))
606 << "].prologue.file_names[" << FileIndex
607 << "].dir_idx contains an invalid index: " << FileName.DirIdx
608 << "\n";
Jonas Devliegheref4ed65d2017-09-08 09:48:51 +0000609 }
610
611 // Check file paths for duplicates.
612 std::string FullPath;
613 const bool HasFullPath = LineTable->getFileNameByIndex(
614 FileIndex, CU->getCompilationDir(),
615 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FullPath);
616 assert(HasFullPath && "Invalid index?");
617 (void)HasFullPath;
618 auto It = FullPathMap.find(FullPath);
619 if (It == FullPathMap.end())
620 FullPathMap[FullPath] = FileIndex;
621 else if (It->second != FileIndex) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000622 warn() << ".debug_line["
623 << format("0x%08" PRIx64,
624 *toSectionOffset(Die.find(DW_AT_stmt_list)))
625 << "].prologue.file_names[" << FileIndex
626 << "] is a duplicate of file_names[" << It->second << "]\n";
Jonas Devliegheref4ed65d2017-09-08 09:48:51 +0000627 }
628
629 FileIndex++;
630 }
631
632 // Verify rows.
Greg Claytonb8c162b2017-05-03 16:02:29 +0000633 uint64_t PrevAddress = 0;
634 uint32_t RowIndex = 0;
635 for (const auto &Row : LineTable->Rows) {
Jonas Devliegheref4ed65d2017-09-08 09:48:51 +0000636 // Verify row address.
Greg Claytonb8c162b2017-05-03 16:02:29 +0000637 if (Row.Address < PrevAddress) {
638 ++NumDebugLineErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000639 error() << ".debug_line["
640 << format("0x%08" PRIx64,
641 *toSectionOffset(Die.find(DW_AT_stmt_list)))
642 << "] row[" << RowIndex
643 << "] decreases in address from previous row:\n";
Greg Claytonb8c162b2017-05-03 16:02:29 +0000644
645 DWARFDebugLine::Row::dumpTableHeader(OS);
646 if (RowIndex > 0)
647 LineTable->Rows[RowIndex - 1].dump(OS);
648 Row.dump(OS);
649 OS << '\n';
650 }
651
Jonas Devliegheref4ed65d2017-09-08 09:48:51 +0000652 // Verify file index.
Greg Claytonb8c162b2017-05-03 16:02:29 +0000653 if (Row.File > MaxFileIndex) {
654 ++NumDebugLineErrors;
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000655 error() << ".debug_line["
656 << format("0x%08" PRIx64,
657 *toSectionOffset(Die.find(DW_AT_stmt_list)))
658 << "][" << RowIndex << "] has invalid file index " << Row.File
659 << " (valid values are [1," << MaxFileIndex << "]):\n";
Greg Claytonb8c162b2017-05-03 16:02:29 +0000660 DWARFDebugLine::Row::dumpTableHeader(OS);
661 Row.dump(OS);
662 OS << '\n';
663 }
664 if (Row.EndSequence)
665 PrevAddress = 0;
666 else
667 PrevAddress = Row.Address;
668 ++RowIndex;
669 }
670 }
Greg Claytonc5b2d562017-05-03 18:25:46 +0000671}
672
673bool DWARFVerifier::handleDebugLine() {
674 NumDebugLineErrors = 0;
675 OS << "Verifying .debug_line...\n";
676 verifyDebugLineStmtOffsets();
677 verifyDebugLineRows();
Greg Claytonb8c162b2017-05-03 16:02:29 +0000678 return NumDebugLineErrors == 0;
679}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000680
Pavel Labath9b36fd22018-01-22 13:17:23 +0000681unsigned DWARFVerifier::verifyAppleAccelTable(const DWARFSection *AccelSection,
682 DataExtractor *StrData,
683 const char *SectionName) {
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000684 unsigned NumErrors = 0;
685 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), *AccelSection,
686 DCtx.isLittleEndian(), 0);
Pavel Labath9b36fd22018-01-22 13:17:23 +0000687 AppleAcceleratorTable AccelTable(AccelSectionData, *StrData);
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000688
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000689 OS << "Verifying " << SectionName << "...\n";
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000690
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000691 // Verify that the fixed part of the header is not too short.
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000692 if (!AccelSectionData.isValidOffset(AccelTable.getSizeHdr())) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000693 error() << "Section is too small to fit a section header.\n";
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000694 return 1;
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000695 }
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000696
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000697 // Verify that the section is not too short.
Jonas Devlieghereba915892017-12-11 18:22:47 +0000698 if (Error E = AccelTable.extract()) {
699 error() << toString(std::move(E)) << '\n';
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000700 return 1;
701 }
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000702
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000703 // Verify that all buckets have a valid hash index or are empty.
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000704 uint32_t NumBuckets = AccelTable.getNumBuckets();
705 uint32_t NumHashes = AccelTable.getNumHashes();
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000706
707 uint32_t BucketsOffset =
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000708 AccelTable.getSizeHdr() + AccelTable.getHeaderDataLength();
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000709 uint32_t HashesBase = BucketsOffset + NumBuckets * 4;
710 uint32_t OffsetsBase = HashesBase + NumHashes * 4;
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000711 for (uint32_t BucketIdx = 0; BucketIdx < NumBuckets; ++BucketIdx) {
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000712 uint32_t HashIdx = AccelSectionData.getU32(&BucketsOffset);
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000713 if (HashIdx >= NumHashes && HashIdx != UINT32_MAX) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000714 error() << format("Bucket[%d] has invalid hash index: %u.\n", BucketIdx,
715 HashIdx);
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000716 ++NumErrors;
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000717 }
718 }
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000719 uint32_t NumAtoms = AccelTable.getAtomsDesc().size();
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000720 if (NumAtoms == 0) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000721 error() << "No atoms: failed to read HashData.\n";
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000722 return 1;
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000723 }
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000724 if (!AccelTable.validateForms()) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000725 error() << "Unsupported form: failed to read HashData.\n";
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000726 return 1;
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000727 }
728
729 for (uint32_t HashIdx = 0; HashIdx < NumHashes; ++HashIdx) {
730 uint32_t HashOffset = HashesBase + 4 * HashIdx;
731 uint32_t DataOffset = OffsetsBase + 4 * HashIdx;
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000732 uint32_t Hash = AccelSectionData.getU32(&HashOffset);
733 uint32_t HashDataOffset = AccelSectionData.getU32(&DataOffset);
734 if (!AccelSectionData.isValidOffsetForDataOfSize(HashDataOffset,
735 sizeof(uint64_t))) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000736 error() << format("Hash[%d] has invalid HashData offset: 0x%08x.\n",
737 HashIdx, HashDataOffset);
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000738 ++NumErrors;
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000739 }
740
741 uint32_t StrpOffset;
742 uint32_t StringOffset;
743 uint32_t StringCount = 0;
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000744 unsigned Offset;
745 unsigned Tag;
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000746 while ((StrpOffset = AccelSectionData.getU32(&HashDataOffset)) != 0) {
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000747 const uint32_t NumHashDataObjects =
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000748 AccelSectionData.getU32(&HashDataOffset);
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000749 for (uint32_t HashDataIdx = 0; HashDataIdx < NumHashDataObjects;
750 ++HashDataIdx) {
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000751 std::tie(Offset, Tag) = AccelTable.readAtoms(HashDataOffset);
752 auto Die = DCtx.getDIEForOffset(Offset);
753 if (!Die) {
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000754 const uint32_t BucketIdx =
755 NumBuckets ? (Hash % NumBuckets) : UINT32_MAX;
756 StringOffset = StrpOffset;
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000757 const char *Name = StrData->getCStr(&StringOffset);
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000758 if (!Name)
759 Name = "<NULL>";
760
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000761 error() << format(
762 "%s Bucket[%d] Hash[%d] = 0x%08x "
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000763 "Str[%u] = 0x%08x "
764 "DIE[%d] = 0x%08x is not a valid DIE offset for \"%s\".\n",
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000765 SectionName, BucketIdx, HashIdx, Hash, StringCount, StrpOffset,
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000766 HashDataIdx, Offset, Name);
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000767
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000768 ++NumErrors;
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000769 continue;
770 }
771 if ((Tag != dwarf::DW_TAG_null) && (Die.getTag() != Tag)) {
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +0000772 error() << "Tag " << dwarf::TagString(Tag)
773 << " in accelerator table does not match Tag "
774 << dwarf::TagString(Die.getTag()) << " of DIE[" << HashDataIdx
775 << "].\n";
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000776 ++NumErrors;
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000777 }
778 }
779 ++StringCount;
780 }
781 }
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000782 return NumErrors;
783}
784
Pavel Labathb136c392018-03-08 15:34:42 +0000785unsigned
786DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames &AccelTable) {
787 // A map from CU offset to the (first) Name Index offset which claims to index
788 // this CU.
789 DenseMap<uint32_t, uint32_t> CUMap;
790 const uint32_t NotIndexed = std::numeric_limits<uint32_t>::max();
791
792 CUMap.reserve(DCtx.getNumCompileUnits());
793 for (const auto &CU : DCtx.compile_units())
794 CUMap[CU->getOffset()] = NotIndexed;
795
796 unsigned NumErrors = 0;
797 for (const DWARFDebugNames::NameIndex &NI : AccelTable) {
798 if (NI.getCUCount() == 0) {
799 error() << formatv("Name Index @ {0:x} does not index any CU\n",
800 NI.getUnitOffset());
801 ++NumErrors;
802 continue;
803 }
804 for (uint32_t CU = 0, End = NI.getCUCount(); CU < End; ++CU) {
805 uint32_t Offset = NI.getCUOffset(CU);
806 auto Iter = CUMap.find(Offset);
807
808 if (Iter == CUMap.end()) {
809 error() << formatv(
810 "Name Index @ {0:x} references a non-existing CU @ {1:x}\n",
811 NI.getUnitOffset(), Offset);
812 ++NumErrors;
813 continue;
814 }
815
816 if (Iter->second != NotIndexed) {
817 error() << formatv("Name Index @ {0:x} references a CU @ {1:x}, but "
818 "this CU is already indexed by Name Index @ {2:x}\n",
819 NI.getUnitOffset(), Offset, Iter->second);
820 continue;
821 }
822 Iter->second = NI.getUnitOffset();
823 }
824 }
825
826 for (const auto &KV : CUMap) {
827 if (KV.second == NotIndexed)
828 warn() << formatv("CU @ {0:x} not covered by any Name Index\n", KV.first);
829 }
830
831 return NumErrors;
832}
833
Pavel Labath906b7772018-03-16 10:02:16 +0000834unsigned
835DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex &NI,
836 const DataExtractor &StrData) {
837 struct BucketInfo {
838 uint32_t Bucket;
839 uint32_t Index;
840
841 constexpr BucketInfo(uint32_t Bucket, uint32_t Index)
842 : Bucket(Bucket), Index(Index) {}
843 bool operator<(const BucketInfo &RHS) const { return Index < RHS.Index; };
844 };
845
846 uint32_t NumErrors = 0;
847 if (NI.getBucketCount() == 0) {
848 warn() << formatv("Name Index @ {0:x} does not contain a hash table.\n",
849 NI.getUnitOffset());
850 return NumErrors;
851 }
852
853 // Build up a list of (Bucket, Index) pairs. We use this later to verify that
854 // each Name is reachable from the appropriate bucket.
855 std::vector<BucketInfo> BucketStarts;
856 BucketStarts.reserve(NI.getBucketCount() + 1);
857 for (uint32_t Bucket = 0, End = NI.getBucketCount(); Bucket < End; ++Bucket) {
858 uint32_t Index = NI.getBucketArrayEntry(Bucket);
859 if (Index > NI.getNameCount()) {
860 error() << formatv("Bucket {0} of Name Index @ {1:x} contains invalid "
861 "value {2}. Valid range is [0, {3}].\n",
862 Bucket, NI.getUnitOffset(), Index, NI.getNameCount());
863 ++NumErrors;
864 continue;
865 }
866 if (Index > 0)
867 BucketStarts.emplace_back(Bucket, Index);
868 }
869
870 // If there were any buckets with invalid values, skip further checks as they
871 // will likely produce many errors which will only confuse the actual root
872 // problem.
873 if (NumErrors > 0)
874 return NumErrors;
875
876 // Sort the list in the order of increasing "Index" entries.
877 array_pod_sort(BucketStarts.begin(), BucketStarts.end());
878
879 // Insert a sentinel entry at the end, so we can check that the end of the
880 // table is covered in the loop below.
881 BucketStarts.emplace_back(NI.getBucketCount(), NI.getNameCount() + 1);
882
883 // Loop invariant: NextUncovered is the (1-based) index of the first Name
884 // which is not reachable by any of the buckets we processed so far (and
885 // hasn't been reported as uncovered).
886 uint32_t NextUncovered = 1;
887 for (const BucketInfo &B : BucketStarts) {
888 // Under normal circumstances B.Index be equal to NextUncovered, but it can
889 // be less if a bucket points to names which are already known to be in some
890 // bucket we processed earlier. In that case, we won't trigger this error,
891 // but report the mismatched hash value error instead. (We know the hash
892 // will not match because we have already verified that the name's hash
893 // puts it into the previous bucket.)
894 if (B.Index > NextUncovered) {
895 error() << formatv("Name Index @ {0:x}: Name table entries [{1}, {2}] "
896 "are not covered by the hash table.\n",
897 NI.getUnitOffset(), NextUncovered, B.Index - 1);
898 ++NumErrors;
899 }
900 uint32_t Idx = B.Index;
901
902 // The rest of the checks apply only to non-sentinel entries.
903 if (B.Bucket == NI.getBucketCount())
904 break;
905
906 // This triggers if a non-empty bucket points to a name with a mismatched
907 // hash. Clients are likely to interpret this as an empty bucket, because a
908 // mismatched hash signals the end of a bucket, but if this is indeed an
909 // empty bucket, the producer should have signalled this by marking the
910 // bucket as empty.
911 uint32_t FirstHash = NI.getHashArrayEntry(Idx);
912 if (FirstHash % NI.getBucketCount() != B.Bucket) {
913 error() << formatv(
914 "Name Index @ {0:x}: Bucket {1} is not empty but points to a "
915 "mismatched hash value {2:x} (belonging to bucket {3}).\n",
916 NI.getUnitOffset(), B.Bucket, FirstHash,
917 FirstHash % NI.getBucketCount());
918 ++NumErrors;
919 }
920
921 // This find the end of this bucket and also verifies that all the hashes in
922 // this bucket are correct by comparing the stored hashes to the ones we
923 // compute ourselves.
924 while (Idx <= NI.getNameCount()) {
925 uint32_t Hash = NI.getHashArrayEntry(Idx);
926 if (Hash % NI.getBucketCount() != B.Bucket)
927 break;
928
Pavel Labathd6ca0632018-06-01 10:33:11 +0000929 const char *Str = NI.getNameTableEntry(Idx).getString();
Pavel Labath906b7772018-03-16 10:02:16 +0000930 if (caseFoldingDjbHash(Str) != Hash) {
931 error() << formatv("Name Index @ {0:x}: String ({1}) at index {2} "
932 "hashes to {3:x}, but "
933 "the Name Index hash is {4:x}\n",
934 NI.getUnitOffset(), Str, Idx,
935 caseFoldingDjbHash(Str), Hash);
936 ++NumErrors;
937 }
938
939 ++Idx;
940 }
941 NextUncovered = std::max(NextUncovered, Idx);
942 }
943 return NumErrors;
944}
945
Pavel Labath79cd9422018-03-22 14:50:44 +0000946unsigned DWARFVerifier::verifyNameIndexAttribute(
947 const DWARFDebugNames::NameIndex &NI, const DWARFDebugNames::Abbrev &Abbr,
948 DWARFDebugNames::AttributeEncoding AttrEnc) {
949 StringRef FormName = dwarf::FormEncodingString(AttrEnc.Form);
950 if (FormName.empty()) {
951 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
952 "unknown form: {3}.\n",
953 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
954 AttrEnc.Form);
955 return 1;
956 }
957
958 if (AttrEnc.Index == DW_IDX_type_hash) {
959 if (AttrEnc.Form != dwarf::DW_FORM_data8) {
960 error() << formatv(
961 "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_type_hash "
962 "uses an unexpected form {2} (should be {3}).\n",
963 NI.getUnitOffset(), Abbr.Code, AttrEnc.Form, dwarf::DW_FORM_data8);
964 return 1;
965 }
966 }
967
968 // A list of known index attributes and their expected form classes.
969 // DW_IDX_type_hash is handled specially in the check above, as it has a
970 // specific form (not just a form class) we should expect.
971 struct FormClassTable {
972 dwarf::Index Index;
973 DWARFFormValue::FormClass Class;
974 StringLiteral ClassName;
975 };
976 static constexpr FormClassTable Table[] = {
977 {dwarf::DW_IDX_compile_unit, DWARFFormValue::FC_Constant, {"constant"}},
978 {dwarf::DW_IDX_type_unit, DWARFFormValue::FC_Constant, {"constant"}},
979 {dwarf::DW_IDX_die_offset, DWARFFormValue::FC_Reference, {"reference"}},
980 {dwarf::DW_IDX_parent, DWARFFormValue::FC_Constant, {"constant"}},
981 };
982
983 ArrayRef<FormClassTable> TableRef(Table);
984 auto Iter = find_if(TableRef, [AttrEnc](const FormClassTable &T) {
985 return T.Index == AttrEnc.Index;
986 });
987 if (Iter == TableRef.end()) {
988 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains an "
989 "unknown index attribute: {2}.\n",
990 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index);
991 return 0;
992 }
993
994 if (!DWARFFormValue(AttrEnc.Form).isFormClass(Iter->Class)) {
995 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
996 "unexpected form {3} (expected form class {4}).\n",
997 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
998 AttrEnc.Form, Iter->ClassName);
999 return 1;
1000 }
1001 return 0;
1002}
1003
1004unsigned
1005DWARFVerifier::verifyNameIndexAbbrevs(const DWARFDebugNames::NameIndex &NI) {
Pavel Labathc9f07b02018-04-06 13:34:12 +00001006 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0) {
1007 warn() << formatv("Name Index @ {0:x}: Verifying indexes of type units is "
1008 "not currently supported.\n",
1009 NI.getUnitOffset());
1010 return 0;
1011 }
1012
Pavel Labath79cd9422018-03-22 14:50:44 +00001013 unsigned NumErrors = 0;
1014 for (const auto &Abbrev : NI.getAbbrevs()) {
1015 StringRef TagName = dwarf::TagString(Abbrev.Tag);
1016 if (TagName.empty()) {
1017 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} references an "
1018 "unknown tag: {2}.\n",
1019 NI.getUnitOffset(), Abbrev.Code, Abbrev.Tag);
1020 }
1021 SmallSet<unsigned, 5> Attributes;
1022 for (const auto &AttrEnc : Abbrev.Attributes) {
1023 if (!Attributes.insert(AttrEnc.Index).second) {
1024 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains "
1025 "multiple {2} attributes.\n",
1026 NI.getUnitOffset(), Abbrev.Code, AttrEnc.Index);
1027 ++NumErrors;
1028 continue;
1029 }
1030 NumErrors += verifyNameIndexAttribute(NI, Abbrev, AttrEnc);
1031 }
Pavel Labathc9f07b02018-04-06 13:34:12 +00001032
1033 if (NI.getCUCount() > 1 && !Attributes.count(dwarf::DW_IDX_compile_unit)) {
1034 error() << formatv("NameIndex @ {0:x}: Indexing multiple compile units "
1035 "and abbreviation {1:x} has no {2} attribute.\n",
1036 NI.getUnitOffset(), Abbrev.Code,
1037 dwarf::DW_IDX_compile_unit);
1038 ++NumErrors;
1039 }
1040 if (!Attributes.count(dwarf::DW_IDX_die_offset)) {
1041 error() << formatv(
1042 "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n",
1043 NI.getUnitOffset(), Abbrev.Code, dwarf::DW_IDX_die_offset);
1044 ++NumErrors;
1045 }
Pavel Labath79cd9422018-03-22 14:50:44 +00001046 }
1047 return NumErrors;
1048}
1049
Pavel Labathc9f07b02018-04-06 13:34:12 +00001050static SmallVector<StringRef, 2> getNames(const DWARFDie &DIE) {
1051 SmallVector<StringRef, 2> Result;
1052 if (const char *Str = DIE.getName(DINameKind::ShortName))
1053 Result.emplace_back(Str);
1054 else if (DIE.getTag() == dwarf::DW_TAG_namespace)
1055 Result.emplace_back("(anonymous namespace)");
1056
1057 if (const char *Str = DIE.getName(DINameKind::LinkageName)) {
1058 if (Result.empty() || Result[0] != Str)
1059 Result.emplace_back(Str);
1060 }
1061
1062 return Result;
1063}
1064
Pavel Labathd6ca0632018-06-01 10:33:11 +00001065unsigned DWARFVerifier::verifyNameIndexEntries(
1066 const DWARFDebugNames::NameIndex &NI,
1067 const DWARFDebugNames::NameTableEntry &NTE) {
Pavel Labathc9f07b02018-04-06 13:34:12 +00001068 // Verifying type unit indexes not supported.
1069 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0)
1070 return 0;
1071
Pavel Labathd6ca0632018-06-01 10:33:11 +00001072 const char *CStr = NTE.getString();
Pavel Labathc9f07b02018-04-06 13:34:12 +00001073 if (!CStr) {
1074 error() << formatv(
1075 "Name Index @ {0:x}: Unable to get string associated with name {1}.\n",
Pavel Labathd6ca0632018-06-01 10:33:11 +00001076 NI.getUnitOffset(), NTE.getIndex());
Pavel Labathc9f07b02018-04-06 13:34:12 +00001077 return 1;
1078 }
1079 StringRef Str(CStr);
1080
1081 unsigned NumErrors = 0;
1082 unsigned NumEntries = 0;
Pavel Labathd6ca0632018-06-01 10:33:11 +00001083 uint32_t EntryID = NTE.getEntryOffset();
1084 uint32_t NextEntryID = EntryID;
1085 Expected<DWARFDebugNames::Entry> EntryOr = NI.getEntry(&NextEntryID);
1086 for (; EntryOr; ++NumEntries, EntryID = NextEntryID,
1087 EntryOr = NI.getEntry(&NextEntryID)) {
Pavel Labathc9f07b02018-04-06 13:34:12 +00001088 uint32_t CUIndex = *EntryOr->getCUIndex();
1089 if (CUIndex > NI.getCUCount()) {
1090 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an "
1091 "invalid CU index ({2}).\n",
1092 NI.getUnitOffset(), EntryID, CUIndex);
1093 ++NumErrors;
1094 continue;
1095 }
1096 uint32_t CUOffset = NI.getCUOffset(CUIndex);
Pavel Labath4adc88e2018-06-13 08:14:27 +00001097 uint64_t DIEOffset = CUOffset + *EntryOr->getDIEUnitOffset();
Pavel Labathc9f07b02018-04-06 13:34:12 +00001098 DWARFDie DIE = DCtx.getDIEForOffset(DIEOffset);
1099 if (!DIE) {
1100 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a "
1101 "non-existing DIE @ {2:x}.\n",
1102 NI.getUnitOffset(), EntryID, DIEOffset);
1103 ++NumErrors;
1104 continue;
1105 }
1106 if (DIE.getDwarfUnit()->getOffset() != CUOffset) {
1107 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched CU of "
1108 "DIE @ {2:x}: index - {3:x}; debug_info - {4:x}.\n",
1109 NI.getUnitOffset(), EntryID, DIEOffset, CUOffset,
1110 DIE.getDwarfUnit()->getOffset());
1111 ++NumErrors;
1112 }
1113 if (DIE.getTag() != EntryOr->tag()) {
1114 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Tag of "
1115 "DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1116 NI.getUnitOffset(), EntryID, DIEOffset, EntryOr->tag(),
1117 DIE.getTag());
1118 ++NumErrors;
1119 }
1120
1121 auto EntryNames = getNames(DIE);
1122 if (!is_contained(EntryNames, Str)) {
1123 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Name "
1124 "of DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1125 NI.getUnitOffset(), EntryID, DIEOffset, Str,
1126 make_range(EntryNames.begin(), EntryNames.end()));
Pavel Labath2a6afe52018-05-14 14:13:20 +00001127 ++NumErrors;
Pavel Labathc9f07b02018-04-06 13:34:12 +00001128 }
1129 }
1130 handleAllErrors(EntryOr.takeError(),
1131 [&](const DWARFDebugNames::SentinelError &) {
1132 if (NumEntries > 0)
1133 return;
1134 error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is "
1135 "not associated with any entries.\n",
Pavel Labathd6ca0632018-06-01 10:33:11 +00001136 NI.getUnitOffset(), NTE.getIndex(), Str);
Pavel Labathc9f07b02018-04-06 13:34:12 +00001137 ++NumErrors;
1138 },
1139 [&](const ErrorInfoBase &Info) {
Pavel Labathd6ca0632018-06-01 10:33:11 +00001140 error()
1141 << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n",
1142 NI.getUnitOffset(), NTE.getIndex(), Str,
1143 Info.message());
Pavel Labathc9f07b02018-04-06 13:34:12 +00001144 ++NumErrors;
1145 });
1146 return NumErrors;
1147}
1148
Pavel Labath80827f12018-05-15 13:24:10 +00001149static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx) {
1150 Optional<DWARFFormValue> Location = Die.findRecursively(DW_AT_location);
1151 if (!Location)
1152 return false;
1153
1154 auto ContainsInterestingOperators = [&](StringRef D) {
1155 DWARFUnit *U = Die.getDwarfUnit();
1156 DataExtractor Data(D, DCtx.isLittleEndian(), U->getAddressByteSize());
1157 DWARFExpression Expression(Data, U->getVersion(), U->getAddressByteSize());
1158 return any_of(Expression, [](DWARFExpression::Operation &Op) {
1159 return !Op.isError() && (Op.getCode() == DW_OP_addr ||
1160 Op.getCode() == DW_OP_form_tls_address ||
1161 Op.getCode() == DW_OP_GNU_push_tls_address);
1162 });
1163 };
1164
1165 if (Optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) {
1166 // Inlined location.
1167 if (ContainsInterestingOperators(toStringRef(*Expr)))
1168 return true;
1169 } else if (Optional<uint64_t> Offset = Location->getAsSectionOffset()) {
1170 // Location list.
1171 if (const DWARFDebugLoc *DebugLoc = DCtx.getDebugLoc()) {
1172 if (const DWARFDebugLoc::LocationList *LocList =
1173 DebugLoc->getLocationListAtOffset(*Offset)) {
1174 if (any_of(LocList->Entries, [&](const DWARFDebugLoc::Entry &E) {
1175 return ContainsInterestingOperators({E.Loc.data(), E.Loc.size()});
1176 }))
1177 return true;
1178 }
1179 }
1180 }
1181 return false;
1182}
1183
1184unsigned DWARFVerifier::verifyNameIndexCompleteness(
1185 const DWARFDie &Die, const DWARFDebugNames::NameIndex &NI) {
1186
1187 // First check, if the Die should be indexed. The code follows the DWARF v5
1188 // wording as closely as possible.
1189
1190 // "All non-defining declarations (that is, debugging information entries
1191 // with a DW_AT_declaration attribute) are excluded."
1192 if (Die.find(DW_AT_declaration))
1193 return 0;
1194
1195 // "DW_TAG_namespace debugging information entries without a DW_AT_name
1196 // attribute are included with the name “(anonymous namespace)”.
1197 // All other debugging information entries without a DW_AT_name attribute
1198 // are excluded."
1199 // "If a subprogram or inlined subroutine is included, and has a
1200 // DW_AT_linkage_name attribute, there will be an additional index entry for
1201 // the linkage name."
1202 auto EntryNames = getNames(Die);
1203 if (EntryNames.empty())
1204 return 0;
1205
1206 // We deviate from the specification here, which says:
1207 // "The name index must contain an entry for each debugging information entry
1208 // that defines a named subprogram, label, variable, type, or namespace,
1209 // subject to ..."
1210 // Instead whitelisting all TAGs representing a "type" or a "subprogram", to
1211 // make sure we catch any missing items, we instead blacklist all TAGs that we
1212 // know shouldn't be indexed.
1213 switch (Die.getTag()) {
1214 // Compile unit has a name but it shouldn't be indexed.
1215 case DW_TAG_compile_unit:
1216 return 0;
1217
1218 // Function and template parameters are not globally visible, so we shouldn't
1219 // index them.
1220 case DW_TAG_formal_parameter:
1221 case DW_TAG_template_value_parameter:
1222 case DW_TAG_template_type_parameter:
1223 case DW_TAG_GNU_template_parameter_pack:
1224 case DW_TAG_GNU_template_template_param:
1225 return 0;
1226
1227 // Object members aren't globally visible.
1228 case DW_TAG_member:
1229 return 0;
1230
1231 // According to a strict reading of the specification, enumerators should not
1232 // be indexed (and LLVM currently does not do that). However, this causes
1233 // problems for the debuggers, so we may need to reconsider this.
1234 case DW_TAG_enumerator:
1235 return 0;
1236
1237 // Imported declarations should not be indexed according to the specification
1238 // and LLVM currently does not do that.
1239 case DW_TAG_imported_declaration:
1240 return 0;
1241
1242 // "DW_TAG_subprogram, DW_TAG_inlined_subroutine, and DW_TAG_label debugging
1243 // information entries without an address attribute (DW_AT_low_pc,
1244 // DW_AT_high_pc, DW_AT_ranges, or DW_AT_entry_pc) are excluded."
1245 case DW_TAG_subprogram:
1246 case DW_TAG_inlined_subroutine:
1247 case DW_TAG_label:
1248 if (Die.findRecursively(
1249 {DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_entry_pc}))
1250 break;
1251 return 0;
1252
1253 // "DW_TAG_variable debugging information entries with a DW_AT_location
1254 // attribute that includes a DW_OP_addr or DW_OP_form_tls_address operator are
1255 // included; otherwise, they are excluded."
1256 //
1257 // LLVM extension: We also add DW_OP_GNU_push_tls_address to this list.
1258 case DW_TAG_variable:
1259 if (isVariableIndexable(Die, DCtx))
1260 break;
1261 return 0;
1262
1263 default:
1264 break;
1265 }
1266
1267 // Now we know that our Die should be present in the Index. Let's check if
1268 // that's the case.
1269 unsigned NumErrors = 0;
Pavel Labath4adc88e2018-06-13 08:14:27 +00001270 uint64_t DieUnitOffset = Die.getOffset() - Die.getDwarfUnit()->getOffset();
Pavel Labath80827f12018-05-15 13:24:10 +00001271 for (StringRef Name : EntryNames) {
Pavel Labath4adc88e2018-06-13 08:14:27 +00001272 if (none_of(NI.equal_range(Name), [&](const DWARFDebugNames::Entry &E) {
1273 return E.getDIEUnitOffset() == DieUnitOffset;
Pavel Labath80827f12018-05-15 13:24:10 +00001274 })) {
1275 error() << formatv("Name Index @ {0:x}: Entry for DIE @ {1:x} ({2}) with "
1276 "name {3} missing.\n",
1277 NI.getUnitOffset(), Die.getOffset(), Die.getTag(),
1278 Name);
1279 ++NumErrors;
1280 }
1281 }
1282 return NumErrors;
1283}
1284
Pavel Labathb136c392018-03-08 15:34:42 +00001285unsigned DWARFVerifier::verifyDebugNames(const DWARFSection &AccelSection,
1286 const DataExtractor &StrData) {
1287 unsigned NumErrors = 0;
1288 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), AccelSection,
1289 DCtx.isLittleEndian(), 0);
1290 DWARFDebugNames AccelTable(AccelSectionData, StrData);
1291
1292 OS << "Verifying .debug_names...\n";
1293
1294 // This verifies that we can read individual name indices and their
1295 // abbreviation tables.
1296 if (Error E = AccelTable.extract()) {
1297 error() << toString(std::move(E)) << '\n';
1298 return 1;
1299 }
1300
1301 NumErrors += verifyDebugNamesCULists(AccelTable);
Pavel Labath906b7772018-03-16 10:02:16 +00001302 for (const auto &NI : AccelTable)
1303 NumErrors += verifyNameIndexBuckets(NI, StrData);
Pavel Labath79cd9422018-03-22 14:50:44 +00001304 for (const auto &NI : AccelTable)
1305 NumErrors += verifyNameIndexAbbrevs(NI);
Pavel Labathb136c392018-03-08 15:34:42 +00001306
Pavel Labathc9f07b02018-04-06 13:34:12 +00001307 // Don't attempt Entry validation if any of the previous checks found errors
1308 if (NumErrors > 0)
1309 return NumErrors;
1310 for (const auto &NI : AccelTable)
Pavel Labathd6ca0632018-06-01 10:33:11 +00001311 for (DWARFDebugNames::NameTableEntry NTE : NI)
1312 NumErrors += verifyNameIndexEntries(NI, NTE);
Pavel Labathc9f07b02018-04-06 13:34:12 +00001313
Pavel Labath80827f12018-05-15 13:24:10 +00001314 if (NumErrors > 0)
1315 return NumErrors;
1316
Paul Robinson143eaea2018-08-01 20:43:47 +00001317 for (const std::unique_ptr<DWARFUnit> &U : DCtx.compile_units()) {
Pavel Labath80827f12018-05-15 13:24:10 +00001318 if (const DWARFDebugNames::NameIndex *NI =
Paul Robinson143eaea2018-08-01 20:43:47 +00001319 AccelTable.getCUNameIndex(U->getOffset())) {
1320 auto *CU = cast<DWARFCompileUnit>(U.get());
Pavel Labath80827f12018-05-15 13:24:10 +00001321 for (const DWARFDebugInfoEntry &Die : CU->dies())
Paul Robinson143eaea2018-08-01 20:43:47 +00001322 NumErrors += verifyNameIndexCompleteness(DWARFDie(CU, &Die), *NI);
Pavel Labath80827f12018-05-15 13:24:10 +00001323 }
1324 }
Pavel Labathb136c392018-03-08 15:34:42 +00001325 return NumErrors;
1326}
1327
Spyridoula Gravanidc635f42017-07-26 00:52:31 +00001328bool DWARFVerifier::handleAccelTables() {
1329 const DWARFObject &D = DCtx.getDWARFObj();
1330 DataExtractor StrData(D.getStringSection(), DCtx.isLittleEndian(), 0);
1331 unsigned NumErrors = 0;
1332 if (!D.getAppleNamesSection().Data.empty())
1333 NumErrors +=
Pavel Labath9b36fd22018-01-22 13:17:23 +00001334 verifyAppleAccelTable(&D.getAppleNamesSection(), &StrData, ".apple_names");
Spyridoula Gravanidc635f42017-07-26 00:52:31 +00001335 if (!D.getAppleTypesSection().Data.empty())
1336 NumErrors +=
Pavel Labath9b36fd22018-01-22 13:17:23 +00001337 verifyAppleAccelTable(&D.getAppleTypesSection(), &StrData, ".apple_types");
Spyridoula Gravanidc635f42017-07-26 00:52:31 +00001338 if (!D.getAppleNamespacesSection().Data.empty())
Pavel Labath9b36fd22018-01-22 13:17:23 +00001339 NumErrors += verifyAppleAccelTable(&D.getAppleNamespacesSection(), &StrData,
Spyridoula Gravanidc635f42017-07-26 00:52:31 +00001340 ".apple_namespaces");
1341 if (!D.getAppleObjCSection().Data.empty())
1342 NumErrors +=
Pavel Labath9b36fd22018-01-22 13:17:23 +00001343 verifyAppleAccelTable(&D.getAppleObjCSection(), &StrData, ".apple_objc");
Pavel Labathb136c392018-03-08 15:34:42 +00001344
1345 if (!D.getDebugNamesSection().Data.empty())
1346 NumErrors += verifyDebugNames(D.getDebugNamesSection(), StrData);
Spyridoula Gravanidc635f42017-07-26 00:52:31 +00001347 return NumErrors == 0;
Spyridoula Gravanie41823b2017-06-14 00:17:55 +00001348}
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +00001349
Jonas Devlieghere6be1f012018-04-15 08:44:15 +00001350raw_ostream &DWARFVerifier::error() const { return WithColor::error(OS); }
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +00001351
Jonas Devlieghere6be1f012018-04-15 08:44:15 +00001352raw_ostream &DWARFVerifier::warn() const { return WithColor::warning(OS); }
Jonas Devlieghere19fc4d92017-09-29 09:33:31 +00001353
Jonas Devlieghere6be1f012018-04-15 08:44:15 +00001354raw_ostream &DWARFVerifier::note() const { return WithColor::note(OS); }