DWARFVerifier.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  1. //===- DWARFVerifier.cpp --------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
  9. #include "llvm/ADT/IntervalMap.h"
  10. #include "llvm/ADT/SmallSet.h"
  11. #include "llvm/BinaryFormat/Dwarf.h"
  12. #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
  13. #include "llvm/DebugInfo/DWARF/DWARFAttribute.h"
  14. #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
  15. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  16. #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
  17. #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
  18. #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
  19. #include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
  20. #include "llvm/DebugInfo/DWARF/DWARFDie.h"
  21. #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
  22. #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
  23. #include "llvm/DebugInfo/DWARF/DWARFLocationExpression.h"
  24. #include "llvm/DebugInfo/DWARF/DWARFObject.h"
  25. #include "llvm/DebugInfo/DWARF/DWARFSection.h"
  26. #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
  27. #include "llvm/Object/Error.h"
  28. #include "llvm/Support/DJB.h"
  29. #include "llvm/Support/Error.h"
  30. #include "llvm/Support/ErrorHandling.h"
  31. #include "llvm/Support/FormatVariadic.h"
  32. #include "llvm/Support/WithColor.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include <map>
  35. #include <set>
  36. #include <vector>
  37. using namespace llvm;
  38. using namespace dwarf;
  39. using namespace object;
  40. namespace llvm {
  41. class DWARFDebugInfoEntry;
  42. }
  43. std::optional<DWARFAddressRange>
  44. DWARFVerifier::DieRangeInfo::insert(const DWARFAddressRange &R) {
  45. auto Begin = Ranges.begin();
  46. auto End = Ranges.end();
  47. auto Pos = std::lower_bound(Begin, End, R);
  48. if (Pos != End) {
  49. DWARFAddressRange Range(*Pos);
  50. if (Pos->merge(R))
  51. return Range;
  52. }
  53. if (Pos != Begin) {
  54. auto Iter = Pos - 1;
  55. DWARFAddressRange Range(*Iter);
  56. if (Iter->merge(R))
  57. return Range;
  58. }
  59. Ranges.insert(Pos, R);
  60. return std::nullopt;
  61. }
  62. DWARFVerifier::DieRangeInfo::die_range_info_iterator
  63. DWARFVerifier::DieRangeInfo::insert(const DieRangeInfo &RI) {
  64. if (RI.Ranges.empty())
  65. return Children.end();
  66. auto End = Children.end();
  67. auto Iter = Children.begin();
  68. while (Iter != End) {
  69. if (Iter->intersects(RI))
  70. return Iter;
  71. ++Iter;
  72. }
  73. Children.insert(RI);
  74. return Children.end();
  75. }
  76. bool DWARFVerifier::DieRangeInfo::contains(const DieRangeInfo &RHS) const {
  77. auto I1 = Ranges.begin(), E1 = Ranges.end();
  78. auto I2 = RHS.Ranges.begin(), E2 = RHS.Ranges.end();
  79. if (I2 == E2)
  80. return true;
  81. DWARFAddressRange R = *I2;
  82. while (I1 != E1) {
  83. bool Covered = I1->LowPC <= R.LowPC;
  84. if (R.LowPC == R.HighPC || (Covered && R.HighPC <= I1->HighPC)) {
  85. if (++I2 == E2)
  86. return true;
  87. R = *I2;
  88. continue;
  89. }
  90. if (!Covered)
  91. return false;
  92. if (R.LowPC < I1->HighPC)
  93. R.LowPC = I1->HighPC;
  94. ++I1;
  95. }
  96. return false;
  97. }
  98. bool DWARFVerifier::DieRangeInfo::intersects(const DieRangeInfo &RHS) const {
  99. auto I1 = Ranges.begin(), E1 = Ranges.end();
  100. auto I2 = RHS.Ranges.begin(), E2 = RHS.Ranges.end();
  101. while (I1 != E1 && I2 != E2) {
  102. if (I1->intersects(*I2))
  103. return true;
  104. if (I1->LowPC < I2->LowPC)
  105. ++I1;
  106. else
  107. ++I2;
  108. }
  109. return false;
  110. }
  111. bool DWARFVerifier::verifyUnitHeader(const DWARFDataExtractor DebugInfoData,
  112. uint64_t *Offset, unsigned UnitIndex,
  113. uint8_t &UnitType, bool &isUnitDWARF64) {
  114. uint64_t AbbrOffset, Length;
  115. uint8_t AddrSize = 0;
  116. uint16_t Version;
  117. bool Success = true;
  118. bool ValidLength = false;
  119. bool ValidVersion = false;
  120. bool ValidAddrSize = false;
  121. bool ValidType = true;
  122. bool ValidAbbrevOffset = true;
  123. uint64_t OffsetStart = *Offset;
  124. DwarfFormat Format;
  125. std::tie(Length, Format) = DebugInfoData.getInitialLength(Offset);
  126. isUnitDWARF64 = Format == DWARF64;
  127. Version = DebugInfoData.getU16(Offset);
  128. if (Version >= 5) {
  129. UnitType = DebugInfoData.getU8(Offset);
  130. AddrSize = DebugInfoData.getU8(Offset);
  131. AbbrOffset = isUnitDWARF64 ? DebugInfoData.getU64(Offset) : DebugInfoData.getU32(Offset);
  132. ValidType = dwarf::isUnitType(UnitType);
  133. } else {
  134. UnitType = 0;
  135. AbbrOffset = isUnitDWARF64 ? DebugInfoData.getU64(Offset) : DebugInfoData.getU32(Offset);
  136. AddrSize = DebugInfoData.getU8(Offset);
  137. }
  138. if (!DCtx.getDebugAbbrev()->getAbbreviationDeclarationSet(AbbrOffset))
  139. ValidAbbrevOffset = false;
  140. ValidLength = DebugInfoData.isValidOffset(OffsetStart + Length + 3);
  141. ValidVersion = DWARFContext::isSupportedVersion(Version);
  142. ValidAddrSize = DWARFContext::isAddressSizeSupported(AddrSize);
  143. if (!ValidLength || !ValidVersion || !ValidAddrSize || !ValidAbbrevOffset ||
  144. !ValidType) {
  145. Success = false;
  146. error() << format("Units[%d] - start offset: 0x%08" PRIx64 " \n", UnitIndex,
  147. OffsetStart);
  148. if (!ValidLength)
  149. note() << "The length for this unit is too "
  150. "large for the .debug_info provided.\n";
  151. if (!ValidVersion)
  152. note() << "The 16 bit unit header version is not valid.\n";
  153. if (!ValidType)
  154. note() << "The unit type encoding is not valid.\n";
  155. if (!ValidAbbrevOffset)
  156. note() << "The offset into the .debug_abbrev section is "
  157. "not valid.\n";
  158. if (!ValidAddrSize)
  159. note() << "The address size is unsupported.\n";
  160. }
  161. *Offset = OffsetStart + Length + (isUnitDWARF64 ? 12 : 4);
  162. return Success;
  163. }
  164. bool DWARFVerifier::verifyName(const DWARFDie &Die) {
  165. // FIXME Add some kind of record of which DIE names have already failed and
  166. // don't bother checking a DIE that uses an already failed DIE.
  167. std::string ReconstructedName;
  168. raw_string_ostream OS(ReconstructedName);
  169. std::string OriginalFullName;
  170. Die.getFullName(OS, &OriginalFullName);
  171. OS.flush();
  172. if (OriginalFullName.empty() || OriginalFullName == ReconstructedName)
  173. return false;
  174. error() << "Simplified template DW_AT_name could not be reconstituted:\n"
  175. << formatv(" original: {0}\n"
  176. " reconstituted: {1}\n",
  177. OriginalFullName, ReconstructedName);
  178. dump(Die) << '\n';
  179. dump(Die.getDwarfUnit()->getUnitDIE()) << '\n';
  180. return true;
  181. }
  182. unsigned DWARFVerifier::verifyUnitContents(DWARFUnit &Unit,
  183. ReferenceMap &UnitLocalReferences,
  184. ReferenceMap &CrossUnitReferences) {
  185. unsigned NumUnitErrors = 0;
  186. unsigned NumDies = Unit.getNumDIEs();
  187. for (unsigned I = 0; I < NumDies; ++I) {
  188. auto Die = Unit.getDIEAtIndex(I);
  189. if (Die.getTag() == DW_TAG_null)
  190. continue;
  191. for (auto AttrValue : Die.attributes()) {
  192. NumUnitErrors += verifyDebugInfoAttribute(Die, AttrValue);
  193. NumUnitErrors += verifyDebugInfoForm(Die, AttrValue, UnitLocalReferences,
  194. CrossUnitReferences);
  195. }
  196. NumUnitErrors += verifyName(Die);
  197. if (Die.hasChildren()) {
  198. if (Die.getFirstChild().isValid() &&
  199. Die.getFirstChild().getTag() == DW_TAG_null) {
  200. warn() << dwarf::TagString(Die.getTag())
  201. << " has DW_CHILDREN_yes but DIE has no children: ";
  202. Die.dump(OS);
  203. }
  204. }
  205. NumUnitErrors += verifyDebugInfoCallSite(Die);
  206. }
  207. DWARFDie Die = Unit.getUnitDIE(/* ExtractUnitDIEOnly = */ false);
  208. if (!Die) {
  209. error() << "Compilation unit without DIE.\n";
  210. NumUnitErrors++;
  211. return NumUnitErrors;
  212. }
  213. if (!dwarf::isUnitType(Die.getTag())) {
  214. error() << "Compilation unit root DIE is not a unit DIE: "
  215. << dwarf::TagString(Die.getTag()) << ".\n";
  216. NumUnitErrors++;
  217. }
  218. uint8_t UnitType = Unit.getUnitType();
  219. if (!DWARFUnit::isMatchingUnitTypeAndTag(UnitType, Die.getTag())) {
  220. error() << "Compilation unit type (" << dwarf::UnitTypeString(UnitType)
  221. << ") and root DIE (" << dwarf::TagString(Die.getTag())
  222. << ") do not match.\n";
  223. NumUnitErrors++;
  224. }
  225. // According to DWARF Debugging Information Format Version 5,
  226. // 3.1.2 Skeleton Compilation Unit Entries:
  227. // "A skeleton compilation unit has no children."
  228. if (Die.getTag() == dwarf::DW_TAG_skeleton_unit && Die.hasChildren()) {
  229. error() << "Skeleton compilation unit has children.\n";
  230. NumUnitErrors++;
  231. }
  232. DieRangeInfo RI;
  233. NumUnitErrors += verifyDieRanges(Die, RI);
  234. return NumUnitErrors;
  235. }
  236. unsigned DWARFVerifier::verifyDebugInfoCallSite(const DWARFDie &Die) {
  237. if (Die.getTag() != DW_TAG_call_site && Die.getTag() != DW_TAG_GNU_call_site)
  238. return 0;
  239. DWARFDie Curr = Die.getParent();
  240. for (; Curr.isValid() && !Curr.isSubprogramDIE(); Curr = Die.getParent()) {
  241. if (Curr.getTag() == DW_TAG_inlined_subroutine) {
  242. error() << "Call site entry nested within inlined subroutine:";
  243. Curr.dump(OS);
  244. return 1;
  245. }
  246. }
  247. if (!Curr.isValid()) {
  248. error() << "Call site entry not nested within a valid subprogram:";
  249. Die.dump(OS);
  250. return 1;
  251. }
  252. std::optional<DWARFFormValue> CallAttr = Curr.find(
  253. {DW_AT_call_all_calls, DW_AT_call_all_source_calls,
  254. DW_AT_call_all_tail_calls, DW_AT_GNU_all_call_sites,
  255. DW_AT_GNU_all_source_call_sites, DW_AT_GNU_all_tail_call_sites});
  256. if (!CallAttr) {
  257. error() << "Subprogram with call site entry has no DW_AT_call attribute:";
  258. Curr.dump(OS);
  259. Die.dump(OS, /*indent*/ 1);
  260. return 1;
  261. }
  262. return 0;
  263. }
  264. unsigned DWARFVerifier::verifyAbbrevSection(const DWARFDebugAbbrev *Abbrev) {
  265. unsigned NumErrors = 0;
  266. if (Abbrev) {
  267. const DWARFAbbreviationDeclarationSet *AbbrDecls =
  268. Abbrev->getAbbreviationDeclarationSet(0);
  269. for (auto AbbrDecl : *AbbrDecls) {
  270. SmallDenseSet<uint16_t> AttributeSet;
  271. for (auto Attribute : AbbrDecl.attributes()) {
  272. auto Result = AttributeSet.insert(Attribute.Attr);
  273. if (!Result.second) {
  274. error() << "Abbreviation declaration contains multiple "
  275. << AttributeString(Attribute.Attr) << " attributes.\n";
  276. AbbrDecl.dump(OS);
  277. ++NumErrors;
  278. }
  279. }
  280. }
  281. }
  282. return NumErrors;
  283. }
  284. bool DWARFVerifier::handleDebugAbbrev() {
  285. OS << "Verifying .debug_abbrev...\n";
  286. const DWARFObject &DObj = DCtx.getDWARFObj();
  287. unsigned NumErrors = 0;
  288. if (!DObj.getAbbrevSection().empty())
  289. NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrev());
  290. if (!DObj.getAbbrevDWOSection().empty())
  291. NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrevDWO());
  292. return NumErrors == 0;
  293. }
  294. unsigned DWARFVerifier::verifyUnits(const DWARFUnitVector &Units) {
  295. unsigned NumDebugInfoErrors = 0;
  296. ReferenceMap CrossUnitReferences;
  297. unsigned Index = 1;
  298. for (const auto &Unit : Units) {
  299. OS << "Verifying unit: " << Index << " / " << Units.getNumUnits();
  300. if (const char* Name = Unit->getUnitDIE(true).getShortName())
  301. OS << ", \"" << Name << '\"';
  302. OS << '\n';
  303. OS.flush();
  304. ReferenceMap UnitLocalReferences;
  305. NumDebugInfoErrors +=
  306. verifyUnitContents(*Unit, UnitLocalReferences, CrossUnitReferences);
  307. NumDebugInfoErrors += verifyDebugInfoReferences(
  308. UnitLocalReferences, [&](uint64_t Offset) { return Unit.get(); });
  309. ++Index;
  310. }
  311. NumDebugInfoErrors += verifyDebugInfoReferences(
  312. CrossUnitReferences, [&](uint64_t Offset) -> DWARFUnit * {
  313. if (DWARFUnit *U = Units.getUnitForOffset(Offset))
  314. return U;
  315. return nullptr;
  316. });
  317. return NumDebugInfoErrors;
  318. }
  319. unsigned DWARFVerifier::verifyUnitSection(const DWARFSection &S) {
  320. const DWARFObject &DObj = DCtx.getDWARFObj();
  321. DWARFDataExtractor DebugInfoData(DObj, S, DCtx.isLittleEndian(), 0);
  322. unsigned NumDebugInfoErrors = 0;
  323. uint64_t Offset = 0, UnitIdx = 0;
  324. uint8_t UnitType = 0;
  325. bool isUnitDWARF64 = false;
  326. bool isHeaderChainValid = true;
  327. bool hasDIE = DebugInfoData.isValidOffset(Offset);
  328. DWARFUnitVector TypeUnitVector;
  329. DWARFUnitVector CompileUnitVector;
  330. /// A map that tracks all references (converted absolute references) so we
  331. /// can verify each reference points to a valid DIE and not an offset that
  332. /// lies between to valid DIEs.
  333. ReferenceMap CrossUnitReferences;
  334. while (hasDIE) {
  335. if (!verifyUnitHeader(DebugInfoData, &Offset, UnitIdx, UnitType,
  336. isUnitDWARF64)) {
  337. isHeaderChainValid = false;
  338. if (isUnitDWARF64)
  339. break;
  340. }
  341. hasDIE = DebugInfoData.isValidOffset(Offset);
  342. ++UnitIdx;
  343. }
  344. if (UnitIdx == 0 && !hasDIE) {
  345. warn() << "Section is empty.\n";
  346. isHeaderChainValid = true;
  347. }
  348. if (!isHeaderChainValid)
  349. ++NumDebugInfoErrors;
  350. return NumDebugInfoErrors;
  351. }
  352. unsigned DWARFVerifier::verifyIndex(StringRef Name,
  353. DWARFSectionKind InfoColumnKind,
  354. StringRef IndexStr) {
  355. if (IndexStr.empty())
  356. return 0;
  357. OS << "Verifying " << Name << "...\n";
  358. DWARFUnitIndex Index(InfoColumnKind);
  359. DataExtractor D(IndexStr, DCtx.isLittleEndian(), 0);
  360. if (!Index.parse(D))
  361. return 1;
  362. using MapType = IntervalMap<uint64_t, uint64_t>;
  363. MapType::Allocator Alloc;
  364. std::vector<std::unique_ptr<MapType>> Sections(Index.getColumnKinds().size());
  365. for (const DWARFUnitIndex::Entry &E : Index.getRows()) {
  366. uint64_t Sig = E.getSignature();
  367. if (!E.getContributions())
  368. continue;
  369. for (auto E : enumerate(
  370. InfoColumnKind == DW_SECT_INFO
  371. ? ArrayRef(E.getContributions(), Index.getColumnKinds().size())
  372. : ArrayRef(E.getContribution(), 1))) {
  373. const DWARFUnitIndex::Entry::SectionContribution &SC = E.value();
  374. int Col = E.index();
  375. if (SC.getLength() == 0)
  376. continue;
  377. if (!Sections[Col])
  378. Sections[Col] = std::make_unique<MapType>(Alloc);
  379. auto &M = *Sections[Col];
  380. auto I = M.find(SC.getOffset());
  381. if (I != M.end() && I.start() < (SC.getOffset() + SC.getLength())) {
  382. error() << llvm::formatv(
  383. "overlapping index entries for entries {0:x16} "
  384. "and {1:x16} for column {2}\n",
  385. *I, Sig, toString(Index.getColumnKinds()[Col]));
  386. return 1;
  387. }
  388. M.insert(SC.getOffset(), SC.getOffset() + SC.getLength() - 1, Sig);
  389. }
  390. }
  391. return 0;
  392. }
  393. bool DWARFVerifier::handleDebugCUIndex() {
  394. return verifyIndex(".debug_cu_index", DWARFSectionKind::DW_SECT_INFO,
  395. DCtx.getDWARFObj().getCUIndexSection()) == 0;
  396. }
  397. bool DWARFVerifier::handleDebugTUIndex() {
  398. return verifyIndex(".debug_tu_index", DWARFSectionKind::DW_SECT_EXT_TYPES,
  399. DCtx.getDWARFObj().getTUIndexSection()) == 0;
  400. }
  401. bool DWARFVerifier::handleDebugInfo() {
  402. const DWARFObject &DObj = DCtx.getDWARFObj();
  403. unsigned NumErrors = 0;
  404. OS << "Verifying .debug_info Unit Header Chain...\n";
  405. DObj.forEachInfoSections([&](const DWARFSection &S) {
  406. NumErrors += verifyUnitSection(S);
  407. });
  408. OS << "Verifying .debug_types Unit Header Chain...\n";
  409. DObj.forEachTypesSections([&](const DWARFSection &S) {
  410. NumErrors += verifyUnitSection(S);
  411. });
  412. OS << "Verifying non-dwo Units...\n";
  413. NumErrors += verifyUnits(DCtx.getNormalUnitsVector());
  414. OS << "Verifying dwo Units...\n";
  415. NumErrors += verifyUnits(DCtx.getDWOUnitsVector());
  416. return NumErrors == 0;
  417. }
  418. unsigned DWARFVerifier::verifyDieRanges(const DWARFDie &Die,
  419. DieRangeInfo &ParentRI) {
  420. unsigned NumErrors = 0;
  421. if (!Die.isValid())
  422. return NumErrors;
  423. DWARFUnit *Unit = Die.getDwarfUnit();
  424. auto RangesOrError = Die.getAddressRanges();
  425. if (!RangesOrError) {
  426. // FIXME: Report the error.
  427. if (!Unit->isDWOUnit())
  428. ++NumErrors;
  429. llvm::consumeError(RangesOrError.takeError());
  430. return NumErrors;
  431. }
  432. const DWARFAddressRangesVector &Ranges = RangesOrError.get();
  433. // Build RI for this DIE and check that ranges within this DIE do not
  434. // overlap.
  435. DieRangeInfo RI(Die);
  436. // TODO support object files better
  437. //
  438. // Some object file formats (i.e. non-MachO) support COMDAT. ELF in
  439. // particular does so by placing each function into a section. The DWARF data
  440. // for the function at that point uses a section relative DW_FORM_addrp for
  441. // the DW_AT_low_pc and a DW_FORM_data4 for the offset as the DW_AT_high_pc.
  442. // In such a case, when the Die is the CU, the ranges will overlap, and we
  443. // will flag valid conflicting ranges as invalid.
  444. //
  445. // For such targets, we should read the ranges from the CU and partition them
  446. // by the section id. The ranges within a particular section should be
  447. // disjoint, although the ranges across sections may overlap. We would map
  448. // the child die to the entity that it references and the section with which
  449. // it is associated. The child would then be checked against the range
  450. // information for the associated section.
  451. //
  452. // For now, simply elide the range verification for the CU DIEs if we are
  453. // processing an object file.
  454. if (!IsObjectFile || IsMachOObject || Die.getTag() != DW_TAG_compile_unit) {
  455. bool DumpDieAfterError = false;
  456. for (const auto &Range : Ranges) {
  457. if (!Range.valid()) {
  458. ++NumErrors;
  459. error() << "Invalid address range " << Range << "\n";
  460. DumpDieAfterError = true;
  461. continue;
  462. }
  463. // Verify that ranges don't intersect and also build up the DieRangeInfo
  464. // address ranges. Don't break out of the loop below early, or we will
  465. // think this DIE doesn't have all of the address ranges it is supposed
  466. // to have. Compile units often have DW_AT_ranges that can contain one or
  467. // more dead stripped address ranges which tend to all be at the same
  468. // address: 0 or -1.
  469. if (auto PrevRange = RI.insert(Range)) {
  470. ++NumErrors;
  471. error() << "DIE has overlapping ranges in DW_AT_ranges attribute: "
  472. << *PrevRange << " and " << Range << '\n';
  473. DumpDieAfterError = true;
  474. }
  475. }
  476. if (DumpDieAfterError)
  477. dump(Die, 2) << '\n';
  478. }
  479. // Verify that children don't intersect.
  480. const auto IntersectingChild = ParentRI.insert(RI);
  481. if (IntersectingChild != ParentRI.Children.end()) {
  482. ++NumErrors;
  483. error() << "DIEs have overlapping address ranges:";
  484. dump(Die);
  485. dump(IntersectingChild->Die) << '\n';
  486. }
  487. // Verify that ranges are contained within their parent.
  488. bool ShouldBeContained = !RI.Ranges.empty() && !ParentRI.Ranges.empty() &&
  489. !(Die.getTag() == DW_TAG_subprogram &&
  490. ParentRI.Die.getTag() == DW_TAG_subprogram);
  491. if (ShouldBeContained && !ParentRI.contains(RI)) {
  492. ++NumErrors;
  493. error() << "DIE address ranges are not contained in its parent's ranges:";
  494. dump(ParentRI.Die);
  495. dump(Die, 2) << '\n';
  496. }
  497. // Recursively check children.
  498. for (DWARFDie Child : Die)
  499. NumErrors += verifyDieRanges(Child, RI);
  500. return NumErrors;
  501. }
  502. unsigned DWARFVerifier::verifyDebugInfoAttribute(const DWARFDie &Die,
  503. DWARFAttribute &AttrValue) {
  504. unsigned NumErrors = 0;
  505. auto ReportError = [&](const Twine &TitleMsg) {
  506. ++NumErrors;
  507. error() << TitleMsg << '\n';
  508. dump(Die) << '\n';
  509. };
  510. const DWARFObject &DObj = DCtx.getDWARFObj();
  511. DWARFUnit *U = Die.getDwarfUnit();
  512. const auto Attr = AttrValue.Attr;
  513. switch (Attr) {
  514. case DW_AT_ranges:
  515. // Make sure the offset in the DW_AT_ranges attribute is valid.
  516. if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
  517. unsigned DwarfVersion = U->getVersion();
  518. const DWARFSection &RangeSection = DwarfVersion < 5
  519. ? DObj.getRangesSection()
  520. : DObj.getRnglistsSection();
  521. if (U->isDWOUnit() && RangeSection.Data.empty())
  522. break;
  523. if (*SectionOffset >= RangeSection.Data.size())
  524. ReportError(
  525. "DW_AT_ranges offset is beyond " +
  526. StringRef(DwarfVersion < 5 ? ".debug_ranges" : ".debug_rnglists") +
  527. " bounds: " + llvm::formatv("{0:x8}", *SectionOffset));
  528. break;
  529. }
  530. ReportError("DIE has invalid DW_AT_ranges encoding:");
  531. break;
  532. case DW_AT_stmt_list:
  533. // Make sure the offset in the DW_AT_stmt_list attribute is valid.
  534. if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
  535. if (*SectionOffset >= U->getLineSection().Data.size())
  536. ReportError("DW_AT_stmt_list offset is beyond .debug_line bounds: " +
  537. llvm::formatv("{0:x8}", *SectionOffset));
  538. break;
  539. }
  540. ReportError("DIE has invalid DW_AT_stmt_list encoding:");
  541. break;
  542. case DW_AT_location: {
  543. // FIXME: It might be nice if there's a way to walk location expressions
  544. // without trying to resolve the address ranges - it'd be a more efficient
  545. // API (since the API is currently unnecessarily resolving addresses for
  546. // this use case which only wants to validate the expressions themselves) &
  547. // then the expressions could be validated even if the addresses can't be
  548. // resolved.
  549. // That sort of API would probably look like a callback "for each
  550. // expression" with some way to lazily resolve the address ranges when
  551. // needed (& then the existing API used here could be built on top of that -
  552. // using the callback API to build the data structure and return it).
  553. if (Expected<std::vector<DWARFLocationExpression>> Loc =
  554. Die.getLocations(DW_AT_location)) {
  555. for (const auto &Entry : *Loc) {
  556. DataExtractor Data(toStringRef(Entry.Expr), DCtx.isLittleEndian(), 0);
  557. DWARFExpression Expression(Data, U->getAddressByteSize(),
  558. U->getFormParams().Format);
  559. bool Error =
  560. any_of(Expression, [](const DWARFExpression::Operation &Op) {
  561. return Op.isError();
  562. });
  563. if (Error || !Expression.verify(U))
  564. ReportError("DIE contains invalid DWARF expression:");
  565. }
  566. } else if (Error Err = handleErrors(
  567. Loc.takeError(), [&](std::unique_ptr<ResolverError> E) {
  568. return U->isDWOUnit() ? Error::success()
  569. : Error(std::move(E));
  570. }))
  571. ReportError(toString(std::move(Err)));
  572. break;
  573. }
  574. case DW_AT_specification:
  575. case DW_AT_abstract_origin: {
  576. if (auto ReferencedDie = Die.getAttributeValueAsReferencedDie(Attr)) {
  577. auto DieTag = Die.getTag();
  578. auto RefTag = ReferencedDie.getTag();
  579. if (DieTag == RefTag)
  580. break;
  581. if (DieTag == DW_TAG_inlined_subroutine && RefTag == DW_TAG_subprogram)
  582. break;
  583. if (DieTag == DW_TAG_variable && RefTag == DW_TAG_member)
  584. break;
  585. // This might be reference to a function declaration.
  586. if (DieTag == DW_TAG_GNU_call_site && RefTag == DW_TAG_subprogram)
  587. break;
  588. ReportError("DIE with tag " + TagString(DieTag) + " has " +
  589. AttributeString(Attr) +
  590. " that points to DIE with "
  591. "incompatible tag " +
  592. TagString(RefTag));
  593. }
  594. break;
  595. }
  596. case DW_AT_type: {
  597. DWARFDie TypeDie = Die.getAttributeValueAsReferencedDie(DW_AT_type);
  598. if (TypeDie && !isType(TypeDie.getTag())) {
  599. ReportError("DIE has " + AttributeString(Attr) +
  600. " with incompatible tag " + TagString(TypeDie.getTag()));
  601. }
  602. break;
  603. }
  604. case DW_AT_call_file:
  605. case DW_AT_decl_file: {
  606. if (auto FileIdx = AttrValue.Value.getAsUnsignedConstant()) {
  607. if (U->isDWOUnit() && !U->isTypeUnit())
  608. break;
  609. const auto *LT = U->getContext().getLineTableForUnit(U);
  610. if (LT) {
  611. if (!LT->hasFileAtIndex(*FileIdx)) {
  612. bool IsZeroIndexed = LT->Prologue.getVersion() >= 5;
  613. if (std::optional<uint64_t> LastFileIdx =
  614. LT->getLastValidFileIndex()) {
  615. ReportError("DIE has " + AttributeString(Attr) +
  616. " with an invalid file index " +
  617. llvm::formatv("{0}", *FileIdx) +
  618. " (valid values are [" + (IsZeroIndexed ? "0-" : "1-") +
  619. llvm::formatv("{0}", *LastFileIdx) + "])");
  620. } else {
  621. ReportError("DIE has " + AttributeString(Attr) +
  622. " with an invalid file index " +
  623. llvm::formatv("{0}", *FileIdx) +
  624. " (the file table in the prologue is empty)");
  625. }
  626. }
  627. } else {
  628. ReportError("DIE has " + AttributeString(Attr) +
  629. " that references a file with index " +
  630. llvm::formatv("{0}", *FileIdx) +
  631. " and the compile unit has no line table");
  632. }
  633. } else {
  634. ReportError("DIE has " + AttributeString(Attr) +
  635. " with invalid encoding");
  636. }
  637. break;
  638. }
  639. case DW_AT_call_line:
  640. case DW_AT_decl_line: {
  641. if (!AttrValue.Value.getAsUnsignedConstant()) {
  642. ReportError("DIE has " + AttributeString(Attr) +
  643. " with invalid encoding");
  644. }
  645. break;
  646. }
  647. default:
  648. break;
  649. }
  650. return NumErrors;
  651. }
  652. unsigned DWARFVerifier::verifyDebugInfoForm(const DWARFDie &Die,
  653. DWARFAttribute &AttrValue,
  654. ReferenceMap &LocalReferences,
  655. ReferenceMap &CrossUnitReferences) {
  656. auto DieCU = Die.getDwarfUnit();
  657. unsigned NumErrors = 0;
  658. const auto Form = AttrValue.Value.getForm();
  659. switch (Form) {
  660. case DW_FORM_ref1:
  661. case DW_FORM_ref2:
  662. case DW_FORM_ref4:
  663. case DW_FORM_ref8:
  664. case DW_FORM_ref_udata: {
  665. // Verify all CU relative references are valid CU offsets.
  666. std::optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
  667. assert(RefVal);
  668. if (RefVal) {
  669. auto CUSize = DieCU->getNextUnitOffset() - DieCU->getOffset();
  670. auto CUOffset = AttrValue.Value.getRawUValue();
  671. if (CUOffset >= CUSize) {
  672. ++NumErrors;
  673. error() << FormEncodingString(Form) << " CU offset "
  674. << format("0x%08" PRIx64, CUOffset)
  675. << " is invalid (must be less than CU size of "
  676. << format("0x%08" PRIx64, CUSize) << "):\n";
  677. Die.dump(OS, 0, DumpOpts);
  678. dump(Die) << '\n';
  679. } else {
  680. // Valid reference, but we will verify it points to an actual
  681. // DIE later.
  682. LocalReferences[*RefVal].insert(Die.getOffset());
  683. }
  684. }
  685. break;
  686. }
  687. case DW_FORM_ref_addr: {
  688. // Verify all absolute DIE references have valid offsets in the
  689. // .debug_info section.
  690. std::optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
  691. assert(RefVal);
  692. if (RefVal) {
  693. if (*RefVal >= DieCU->getInfoSection().Data.size()) {
  694. ++NumErrors;
  695. error() << "DW_FORM_ref_addr offset beyond .debug_info "
  696. "bounds:\n";
  697. dump(Die) << '\n';
  698. } else {
  699. // Valid reference, but we will verify it points to an actual
  700. // DIE later.
  701. CrossUnitReferences[*RefVal].insert(Die.getOffset());
  702. }
  703. }
  704. break;
  705. }
  706. case DW_FORM_strp:
  707. case DW_FORM_strx:
  708. case DW_FORM_strx1:
  709. case DW_FORM_strx2:
  710. case DW_FORM_strx3:
  711. case DW_FORM_strx4: {
  712. if (Error E = AttrValue.Value.getAsCString().takeError()) {
  713. ++NumErrors;
  714. error() << toString(std::move(E)) << ":\n";
  715. dump(Die) << '\n';
  716. }
  717. break;
  718. }
  719. default:
  720. break;
  721. }
  722. return NumErrors;
  723. }
  724. unsigned DWARFVerifier::verifyDebugInfoReferences(
  725. const ReferenceMap &References,
  726. llvm::function_ref<DWARFUnit *(uint64_t)> GetUnitForOffset) {
  727. auto GetDIEForOffset = [&](uint64_t Offset) {
  728. if (DWARFUnit *U = GetUnitForOffset(Offset))
  729. return U->getDIEForOffset(Offset);
  730. return DWARFDie();
  731. };
  732. unsigned NumErrors = 0;
  733. for (const std::pair<const uint64_t, std::set<uint64_t>> &Pair :
  734. References) {
  735. if (GetDIEForOffset(Pair.first))
  736. continue;
  737. ++NumErrors;
  738. error() << "invalid DIE reference " << format("0x%08" PRIx64, Pair.first)
  739. << ". Offset is in between DIEs:\n";
  740. for (auto Offset : Pair.second)
  741. dump(GetDIEForOffset(Offset)) << '\n';
  742. OS << "\n";
  743. }
  744. return NumErrors;
  745. }
  746. void DWARFVerifier::verifyDebugLineStmtOffsets() {
  747. std::map<uint64_t, DWARFDie> StmtListToDie;
  748. for (const auto &CU : DCtx.compile_units()) {
  749. auto Die = CU->getUnitDIE();
  750. // Get the attribute value as a section offset. No need to produce an
  751. // error here if the encoding isn't correct because we validate this in
  752. // the .debug_info verifier.
  753. auto StmtSectionOffset = toSectionOffset(Die.find(DW_AT_stmt_list));
  754. if (!StmtSectionOffset)
  755. continue;
  756. const uint64_t LineTableOffset = *StmtSectionOffset;
  757. auto LineTable = DCtx.getLineTableForUnit(CU.get());
  758. if (LineTableOffset < DCtx.getDWARFObj().getLineSection().Data.size()) {
  759. if (!LineTable) {
  760. ++NumDebugLineErrors;
  761. error() << ".debug_line[" << format("0x%08" PRIx64, LineTableOffset)
  762. << "] was not able to be parsed for CU:\n";
  763. dump(Die) << '\n';
  764. continue;
  765. }
  766. } else {
  767. // Make sure we don't get a valid line table back if the offset is wrong.
  768. assert(LineTable == nullptr);
  769. // Skip this line table as it isn't valid. No need to create an error
  770. // here because we validate this in the .debug_info verifier.
  771. continue;
  772. }
  773. auto Iter = StmtListToDie.find(LineTableOffset);
  774. if (Iter != StmtListToDie.end()) {
  775. ++NumDebugLineErrors;
  776. error() << "two compile unit DIEs, "
  777. << format("0x%08" PRIx64, Iter->second.getOffset()) << " and "
  778. << format("0x%08" PRIx64, Die.getOffset())
  779. << ", have the same DW_AT_stmt_list section offset:\n";
  780. dump(Iter->second);
  781. dump(Die) << '\n';
  782. // Already verified this line table before, no need to do it again.
  783. continue;
  784. }
  785. StmtListToDie[LineTableOffset] = Die;
  786. }
  787. }
  788. void DWARFVerifier::verifyDebugLineRows() {
  789. for (const auto &CU : DCtx.compile_units()) {
  790. auto Die = CU->getUnitDIE();
  791. auto LineTable = DCtx.getLineTableForUnit(CU.get());
  792. // If there is no line table we will have created an error in the
  793. // .debug_info verifier or in verifyDebugLineStmtOffsets().
  794. if (!LineTable)
  795. continue;
  796. // Verify prologue.
  797. uint32_t MaxDirIndex = LineTable->Prologue.IncludeDirectories.size();
  798. uint32_t FileIndex = 1;
  799. StringMap<uint16_t> FullPathMap;
  800. for (const auto &FileName : LineTable->Prologue.FileNames) {
  801. // Verify directory index.
  802. if (FileName.DirIdx > MaxDirIndex) {
  803. ++NumDebugLineErrors;
  804. error() << ".debug_line["
  805. << format("0x%08" PRIx64,
  806. *toSectionOffset(Die.find(DW_AT_stmt_list)))
  807. << "].prologue.file_names[" << FileIndex
  808. << "].dir_idx contains an invalid index: " << FileName.DirIdx
  809. << "\n";
  810. }
  811. // Check file paths for duplicates.
  812. std::string FullPath;
  813. const bool HasFullPath = LineTable->getFileNameByIndex(
  814. FileIndex, CU->getCompilationDir(),
  815. DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FullPath);
  816. assert(HasFullPath && "Invalid index?");
  817. (void)HasFullPath;
  818. auto It = FullPathMap.find(FullPath);
  819. if (It == FullPathMap.end())
  820. FullPathMap[FullPath] = FileIndex;
  821. else if (It->second != FileIndex) {
  822. warn() << ".debug_line["
  823. << format("0x%08" PRIx64,
  824. *toSectionOffset(Die.find(DW_AT_stmt_list)))
  825. << "].prologue.file_names[" << FileIndex
  826. << "] is a duplicate of file_names[" << It->second << "]\n";
  827. }
  828. FileIndex++;
  829. }
  830. // Verify rows.
  831. uint64_t PrevAddress = 0;
  832. uint32_t RowIndex = 0;
  833. for (const auto &Row : LineTable->Rows) {
  834. // Verify row address.
  835. if (Row.Address.Address < PrevAddress) {
  836. ++NumDebugLineErrors;
  837. error() << ".debug_line["
  838. << format("0x%08" PRIx64,
  839. *toSectionOffset(Die.find(DW_AT_stmt_list)))
  840. << "] row[" << RowIndex
  841. << "] decreases in address from previous row:\n";
  842. DWARFDebugLine::Row::dumpTableHeader(OS, 0);
  843. if (RowIndex > 0)
  844. LineTable->Rows[RowIndex - 1].dump(OS);
  845. Row.dump(OS);
  846. OS << '\n';
  847. }
  848. // Verify file index.
  849. if (!LineTable->hasFileAtIndex(Row.File)) {
  850. ++NumDebugLineErrors;
  851. bool isDWARF5 = LineTable->Prologue.getVersion() >= 5;
  852. error() << ".debug_line["
  853. << format("0x%08" PRIx64,
  854. *toSectionOffset(Die.find(DW_AT_stmt_list)))
  855. << "][" << RowIndex << "] has invalid file index " << Row.File
  856. << " (valid values are [" << (isDWARF5 ? "0," : "1,")
  857. << LineTable->Prologue.FileNames.size()
  858. << (isDWARF5 ? ")" : "]") << "):\n";
  859. DWARFDebugLine::Row::dumpTableHeader(OS, 0);
  860. Row.dump(OS);
  861. OS << '\n';
  862. }
  863. if (Row.EndSequence)
  864. PrevAddress = 0;
  865. else
  866. PrevAddress = Row.Address.Address;
  867. ++RowIndex;
  868. }
  869. }
  870. }
  871. DWARFVerifier::DWARFVerifier(raw_ostream &S, DWARFContext &D,
  872. DIDumpOptions DumpOpts)
  873. : OS(S), DCtx(D), DumpOpts(std::move(DumpOpts)), IsObjectFile(false),
  874. IsMachOObject(false) {
  875. if (const auto *F = DCtx.getDWARFObj().getFile()) {
  876. IsObjectFile = F->isRelocatableObject();
  877. IsMachOObject = F->isMachO();
  878. }
  879. }
  880. bool DWARFVerifier::handleDebugLine() {
  881. NumDebugLineErrors = 0;
  882. OS << "Verifying .debug_line...\n";
  883. verifyDebugLineStmtOffsets();
  884. verifyDebugLineRows();
  885. return NumDebugLineErrors == 0;
  886. }
  887. unsigned DWARFVerifier::verifyAppleAccelTable(const DWARFSection *AccelSection,
  888. DataExtractor *StrData,
  889. const char *SectionName) {
  890. unsigned NumErrors = 0;
  891. DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), *AccelSection,
  892. DCtx.isLittleEndian(), 0);
  893. AppleAcceleratorTable AccelTable(AccelSectionData, *StrData);
  894. OS << "Verifying " << SectionName << "...\n";
  895. // Verify that the fixed part of the header is not too short.
  896. if (!AccelSectionData.isValidOffset(AccelTable.getSizeHdr())) {
  897. error() << "Section is too small to fit a section header.\n";
  898. return 1;
  899. }
  900. // Verify that the section is not too short.
  901. if (Error E = AccelTable.extract()) {
  902. error() << toString(std::move(E)) << '\n';
  903. return 1;
  904. }
  905. // Verify that all buckets have a valid hash index or are empty.
  906. uint32_t NumBuckets = AccelTable.getNumBuckets();
  907. uint32_t NumHashes = AccelTable.getNumHashes();
  908. uint64_t BucketsOffset =
  909. AccelTable.getSizeHdr() + AccelTable.getHeaderDataLength();
  910. uint64_t HashesBase = BucketsOffset + NumBuckets * 4;
  911. uint64_t OffsetsBase = HashesBase + NumHashes * 4;
  912. for (uint32_t BucketIdx = 0; BucketIdx < NumBuckets; ++BucketIdx) {
  913. uint32_t HashIdx = AccelSectionData.getU32(&BucketsOffset);
  914. if (HashIdx >= NumHashes && HashIdx != UINT32_MAX) {
  915. error() << format("Bucket[%d] has invalid hash index: %u.\n", BucketIdx,
  916. HashIdx);
  917. ++NumErrors;
  918. }
  919. }
  920. uint32_t NumAtoms = AccelTable.getAtomsDesc().size();
  921. if (NumAtoms == 0) {
  922. error() << "No atoms: failed to read HashData.\n";
  923. return 1;
  924. }
  925. if (!AccelTable.validateForms()) {
  926. error() << "Unsupported form: failed to read HashData.\n";
  927. return 1;
  928. }
  929. for (uint32_t HashIdx = 0; HashIdx < NumHashes; ++HashIdx) {
  930. uint64_t HashOffset = HashesBase + 4 * HashIdx;
  931. uint64_t DataOffset = OffsetsBase + 4 * HashIdx;
  932. uint32_t Hash = AccelSectionData.getU32(&HashOffset);
  933. uint64_t HashDataOffset = AccelSectionData.getU32(&DataOffset);
  934. if (!AccelSectionData.isValidOffsetForDataOfSize(HashDataOffset,
  935. sizeof(uint64_t))) {
  936. error() << format("Hash[%d] has invalid HashData offset: "
  937. "0x%08" PRIx64 ".\n",
  938. HashIdx, HashDataOffset);
  939. ++NumErrors;
  940. }
  941. uint64_t StrpOffset;
  942. uint64_t StringOffset;
  943. uint32_t StringCount = 0;
  944. uint64_t Offset;
  945. unsigned Tag;
  946. while ((StrpOffset = AccelSectionData.getU32(&HashDataOffset)) != 0) {
  947. const uint32_t NumHashDataObjects =
  948. AccelSectionData.getU32(&HashDataOffset);
  949. for (uint32_t HashDataIdx = 0; HashDataIdx < NumHashDataObjects;
  950. ++HashDataIdx) {
  951. std::tie(Offset, Tag) = AccelTable.readAtoms(&HashDataOffset);
  952. auto Die = DCtx.getDIEForOffset(Offset);
  953. if (!Die) {
  954. const uint32_t BucketIdx =
  955. NumBuckets ? (Hash % NumBuckets) : UINT32_MAX;
  956. StringOffset = StrpOffset;
  957. const char *Name = StrData->getCStr(&StringOffset);
  958. if (!Name)
  959. Name = "<NULL>";
  960. error() << format(
  961. "%s Bucket[%d] Hash[%d] = 0x%08x "
  962. "Str[%u] = 0x%08" PRIx64 " DIE[%d] = 0x%08" PRIx64 " "
  963. "is not a valid DIE offset for \"%s\".\n",
  964. SectionName, BucketIdx, HashIdx, Hash, StringCount, StrpOffset,
  965. HashDataIdx, Offset, Name);
  966. ++NumErrors;
  967. continue;
  968. }
  969. if ((Tag != dwarf::DW_TAG_null) && (Die.getTag() != Tag)) {
  970. error() << "Tag " << dwarf::TagString(Tag)
  971. << " in accelerator table does not match Tag "
  972. << dwarf::TagString(Die.getTag()) << " of DIE[" << HashDataIdx
  973. << "].\n";
  974. ++NumErrors;
  975. }
  976. }
  977. ++StringCount;
  978. }
  979. }
  980. return NumErrors;
  981. }
  982. unsigned
  983. DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames &AccelTable) {
  984. // A map from CU offset to the (first) Name Index offset which claims to index
  985. // this CU.
  986. DenseMap<uint64_t, uint64_t> CUMap;
  987. const uint64_t NotIndexed = std::numeric_limits<uint64_t>::max();
  988. CUMap.reserve(DCtx.getNumCompileUnits());
  989. for (const auto &CU : DCtx.compile_units())
  990. CUMap[CU->getOffset()] = NotIndexed;
  991. unsigned NumErrors = 0;
  992. for (const DWARFDebugNames::NameIndex &NI : AccelTable) {
  993. if (NI.getCUCount() == 0) {
  994. error() << formatv("Name Index @ {0:x} does not index any CU\n",
  995. NI.getUnitOffset());
  996. ++NumErrors;
  997. continue;
  998. }
  999. for (uint32_t CU = 0, End = NI.getCUCount(); CU < End; ++CU) {
  1000. uint64_t Offset = NI.getCUOffset(CU);
  1001. auto Iter = CUMap.find(Offset);
  1002. if (Iter == CUMap.end()) {
  1003. error() << formatv(
  1004. "Name Index @ {0:x} references a non-existing CU @ {1:x}\n",
  1005. NI.getUnitOffset(), Offset);
  1006. ++NumErrors;
  1007. continue;
  1008. }
  1009. if (Iter->second != NotIndexed) {
  1010. error() << formatv("Name Index @ {0:x} references a CU @ {1:x}, but "
  1011. "this CU is already indexed by Name Index @ {2:x}\n",
  1012. NI.getUnitOffset(), Offset, Iter->second);
  1013. continue;
  1014. }
  1015. Iter->second = NI.getUnitOffset();
  1016. }
  1017. }
  1018. for (const auto &KV : CUMap) {
  1019. if (KV.second == NotIndexed)
  1020. warn() << formatv("CU @ {0:x} not covered by any Name Index\n", KV.first);
  1021. }
  1022. return NumErrors;
  1023. }
  1024. unsigned
  1025. DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex &NI,
  1026. const DataExtractor &StrData) {
  1027. struct BucketInfo {
  1028. uint32_t Bucket;
  1029. uint32_t Index;
  1030. constexpr BucketInfo(uint32_t Bucket, uint32_t Index)
  1031. : Bucket(Bucket), Index(Index) {}
  1032. bool operator<(const BucketInfo &RHS) const { return Index < RHS.Index; }
  1033. };
  1034. uint32_t NumErrors = 0;
  1035. if (NI.getBucketCount() == 0) {
  1036. warn() << formatv("Name Index @ {0:x} does not contain a hash table.\n",
  1037. NI.getUnitOffset());
  1038. return NumErrors;
  1039. }
  1040. // Build up a list of (Bucket, Index) pairs. We use this later to verify that
  1041. // each Name is reachable from the appropriate bucket.
  1042. std::vector<BucketInfo> BucketStarts;
  1043. BucketStarts.reserve(NI.getBucketCount() + 1);
  1044. for (uint32_t Bucket = 0, End = NI.getBucketCount(); Bucket < End; ++Bucket) {
  1045. uint32_t Index = NI.getBucketArrayEntry(Bucket);
  1046. if (Index > NI.getNameCount()) {
  1047. error() << formatv("Bucket {0} of Name Index @ {1:x} contains invalid "
  1048. "value {2}. Valid range is [0, {3}].\n",
  1049. Bucket, NI.getUnitOffset(), Index, NI.getNameCount());
  1050. ++NumErrors;
  1051. continue;
  1052. }
  1053. if (Index > 0)
  1054. BucketStarts.emplace_back(Bucket, Index);
  1055. }
  1056. // If there were any buckets with invalid values, skip further checks as they
  1057. // will likely produce many errors which will only confuse the actual root
  1058. // problem.
  1059. if (NumErrors > 0)
  1060. return NumErrors;
  1061. // Sort the list in the order of increasing "Index" entries.
  1062. array_pod_sort(BucketStarts.begin(), BucketStarts.end());
  1063. // Insert a sentinel entry at the end, so we can check that the end of the
  1064. // table is covered in the loop below.
  1065. BucketStarts.emplace_back(NI.getBucketCount(), NI.getNameCount() + 1);
  1066. // Loop invariant: NextUncovered is the (1-based) index of the first Name
  1067. // which is not reachable by any of the buckets we processed so far (and
  1068. // hasn't been reported as uncovered).
  1069. uint32_t NextUncovered = 1;
  1070. for (const BucketInfo &B : BucketStarts) {
  1071. // Under normal circumstances B.Index be equal to NextUncovered, but it can
  1072. // be less if a bucket points to names which are already known to be in some
  1073. // bucket we processed earlier. In that case, we won't trigger this error,
  1074. // but report the mismatched hash value error instead. (We know the hash
  1075. // will not match because we have already verified that the name's hash
  1076. // puts it into the previous bucket.)
  1077. if (B.Index > NextUncovered) {
  1078. error() << formatv("Name Index @ {0:x}: Name table entries [{1}, {2}] "
  1079. "are not covered by the hash table.\n",
  1080. NI.getUnitOffset(), NextUncovered, B.Index - 1);
  1081. ++NumErrors;
  1082. }
  1083. uint32_t Idx = B.Index;
  1084. // The rest of the checks apply only to non-sentinel entries.
  1085. if (B.Bucket == NI.getBucketCount())
  1086. break;
  1087. // This triggers if a non-empty bucket points to a name with a mismatched
  1088. // hash. Clients are likely to interpret this as an empty bucket, because a
  1089. // mismatched hash signals the end of a bucket, but if this is indeed an
  1090. // empty bucket, the producer should have signalled this by marking the
  1091. // bucket as empty.
  1092. uint32_t FirstHash = NI.getHashArrayEntry(Idx);
  1093. if (FirstHash % NI.getBucketCount() != B.Bucket) {
  1094. error() << formatv(
  1095. "Name Index @ {0:x}: Bucket {1} is not empty but points to a "
  1096. "mismatched hash value {2:x} (belonging to bucket {3}).\n",
  1097. NI.getUnitOffset(), B.Bucket, FirstHash,
  1098. FirstHash % NI.getBucketCount());
  1099. ++NumErrors;
  1100. }
  1101. // This find the end of this bucket and also verifies that all the hashes in
  1102. // this bucket are correct by comparing the stored hashes to the ones we
  1103. // compute ourselves.
  1104. while (Idx <= NI.getNameCount()) {
  1105. uint32_t Hash = NI.getHashArrayEntry(Idx);
  1106. if (Hash % NI.getBucketCount() != B.Bucket)
  1107. break;
  1108. const char *Str = NI.getNameTableEntry(Idx).getString();
  1109. if (caseFoldingDjbHash(Str) != Hash) {
  1110. error() << formatv("Name Index @ {0:x}: String ({1}) at index {2} "
  1111. "hashes to {3:x}, but "
  1112. "the Name Index hash is {4:x}\n",
  1113. NI.getUnitOffset(), Str, Idx,
  1114. caseFoldingDjbHash(Str), Hash);
  1115. ++NumErrors;
  1116. }
  1117. ++Idx;
  1118. }
  1119. NextUncovered = std::max(NextUncovered, Idx);
  1120. }
  1121. return NumErrors;
  1122. }
  1123. unsigned DWARFVerifier::verifyNameIndexAttribute(
  1124. const DWARFDebugNames::NameIndex &NI, const DWARFDebugNames::Abbrev &Abbr,
  1125. DWARFDebugNames::AttributeEncoding AttrEnc) {
  1126. StringRef FormName = dwarf::FormEncodingString(AttrEnc.Form);
  1127. if (FormName.empty()) {
  1128. error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
  1129. "unknown form: {3}.\n",
  1130. NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
  1131. AttrEnc.Form);
  1132. return 1;
  1133. }
  1134. if (AttrEnc.Index == DW_IDX_type_hash) {
  1135. if (AttrEnc.Form != dwarf::DW_FORM_data8) {
  1136. error() << formatv(
  1137. "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_type_hash "
  1138. "uses an unexpected form {2} (should be {3}).\n",
  1139. NI.getUnitOffset(), Abbr.Code, AttrEnc.Form, dwarf::DW_FORM_data8);
  1140. return 1;
  1141. }
  1142. }
  1143. // A list of known index attributes and their expected form classes.
  1144. // DW_IDX_type_hash is handled specially in the check above, as it has a
  1145. // specific form (not just a form class) we should expect.
  1146. struct FormClassTable {
  1147. dwarf::Index Index;
  1148. DWARFFormValue::FormClass Class;
  1149. StringLiteral ClassName;
  1150. };
  1151. static constexpr FormClassTable Table[] = {
  1152. {dwarf::DW_IDX_compile_unit, DWARFFormValue::FC_Constant, {"constant"}},
  1153. {dwarf::DW_IDX_type_unit, DWARFFormValue::FC_Constant, {"constant"}},
  1154. {dwarf::DW_IDX_die_offset, DWARFFormValue::FC_Reference, {"reference"}},
  1155. {dwarf::DW_IDX_parent, DWARFFormValue::FC_Constant, {"constant"}},
  1156. };
  1157. ArrayRef<FormClassTable> TableRef(Table);
  1158. auto Iter = find_if(TableRef, [AttrEnc](const FormClassTable &T) {
  1159. return T.Index == AttrEnc.Index;
  1160. });
  1161. if (Iter == TableRef.end()) {
  1162. warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains an "
  1163. "unknown index attribute: {2}.\n",
  1164. NI.getUnitOffset(), Abbr.Code, AttrEnc.Index);
  1165. return 0;
  1166. }
  1167. if (!DWARFFormValue(AttrEnc.Form).isFormClass(Iter->Class)) {
  1168. error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
  1169. "unexpected form {3} (expected form class {4}).\n",
  1170. NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
  1171. AttrEnc.Form, Iter->ClassName);
  1172. return 1;
  1173. }
  1174. return 0;
  1175. }
  1176. unsigned
  1177. DWARFVerifier::verifyNameIndexAbbrevs(const DWARFDebugNames::NameIndex &NI) {
  1178. if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0) {
  1179. warn() << formatv("Name Index @ {0:x}: Verifying indexes of type units is "
  1180. "not currently supported.\n",
  1181. NI.getUnitOffset());
  1182. return 0;
  1183. }
  1184. unsigned NumErrors = 0;
  1185. for (const auto &Abbrev : NI.getAbbrevs()) {
  1186. StringRef TagName = dwarf::TagString(Abbrev.Tag);
  1187. if (TagName.empty()) {
  1188. warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} references an "
  1189. "unknown tag: {2}.\n",
  1190. NI.getUnitOffset(), Abbrev.Code, Abbrev.Tag);
  1191. }
  1192. SmallSet<unsigned, 5> Attributes;
  1193. for (const auto &AttrEnc : Abbrev.Attributes) {
  1194. if (!Attributes.insert(AttrEnc.Index).second) {
  1195. error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains "
  1196. "multiple {2} attributes.\n",
  1197. NI.getUnitOffset(), Abbrev.Code, AttrEnc.Index);
  1198. ++NumErrors;
  1199. continue;
  1200. }
  1201. NumErrors += verifyNameIndexAttribute(NI, Abbrev, AttrEnc);
  1202. }
  1203. if (NI.getCUCount() > 1 && !Attributes.count(dwarf::DW_IDX_compile_unit)) {
  1204. error() << formatv("NameIndex @ {0:x}: Indexing multiple compile units "
  1205. "and abbreviation {1:x} has no {2} attribute.\n",
  1206. NI.getUnitOffset(), Abbrev.Code,
  1207. dwarf::DW_IDX_compile_unit);
  1208. ++NumErrors;
  1209. }
  1210. if (!Attributes.count(dwarf::DW_IDX_die_offset)) {
  1211. error() << formatv(
  1212. "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n",
  1213. NI.getUnitOffset(), Abbrev.Code, dwarf::DW_IDX_die_offset);
  1214. ++NumErrors;
  1215. }
  1216. }
  1217. return NumErrors;
  1218. }
  1219. static SmallVector<StringRef, 2> getNames(const DWARFDie &DIE,
  1220. bool IncludeLinkageName = true) {
  1221. SmallVector<StringRef, 2> Result;
  1222. if (const char *Str = DIE.getShortName())
  1223. Result.emplace_back(Str);
  1224. else if (DIE.getTag() == dwarf::DW_TAG_namespace)
  1225. Result.emplace_back("(anonymous namespace)");
  1226. if (IncludeLinkageName) {
  1227. if (const char *Str = DIE.getLinkageName())
  1228. Result.emplace_back(Str);
  1229. }
  1230. return Result;
  1231. }
  1232. unsigned DWARFVerifier::verifyNameIndexEntries(
  1233. const DWARFDebugNames::NameIndex &NI,
  1234. const DWARFDebugNames::NameTableEntry &NTE) {
  1235. // Verifying type unit indexes not supported.
  1236. if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0)
  1237. return 0;
  1238. const char *CStr = NTE.getString();
  1239. if (!CStr) {
  1240. error() << formatv(
  1241. "Name Index @ {0:x}: Unable to get string associated with name {1}.\n",
  1242. NI.getUnitOffset(), NTE.getIndex());
  1243. return 1;
  1244. }
  1245. StringRef Str(CStr);
  1246. unsigned NumErrors = 0;
  1247. unsigned NumEntries = 0;
  1248. uint64_t EntryID = NTE.getEntryOffset();
  1249. uint64_t NextEntryID = EntryID;
  1250. Expected<DWARFDebugNames::Entry> EntryOr = NI.getEntry(&NextEntryID);
  1251. for (; EntryOr; ++NumEntries, EntryID = NextEntryID,
  1252. EntryOr = NI.getEntry(&NextEntryID)) {
  1253. uint32_t CUIndex = *EntryOr->getCUIndex();
  1254. if (CUIndex > NI.getCUCount()) {
  1255. error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an "
  1256. "invalid CU index ({2}).\n",
  1257. NI.getUnitOffset(), EntryID, CUIndex);
  1258. ++NumErrors;
  1259. continue;
  1260. }
  1261. uint64_t CUOffset = NI.getCUOffset(CUIndex);
  1262. uint64_t DIEOffset = CUOffset + *EntryOr->getDIEUnitOffset();
  1263. DWARFDie DIE = DCtx.getDIEForOffset(DIEOffset);
  1264. if (!DIE) {
  1265. error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a "
  1266. "non-existing DIE @ {2:x}.\n",
  1267. NI.getUnitOffset(), EntryID, DIEOffset);
  1268. ++NumErrors;
  1269. continue;
  1270. }
  1271. if (DIE.getDwarfUnit()->getOffset() != CUOffset) {
  1272. error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched CU of "
  1273. "DIE @ {2:x}: index - {3:x}; debug_info - {4:x}.\n",
  1274. NI.getUnitOffset(), EntryID, DIEOffset, CUOffset,
  1275. DIE.getDwarfUnit()->getOffset());
  1276. ++NumErrors;
  1277. }
  1278. if (DIE.getTag() != EntryOr->tag()) {
  1279. error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Tag of "
  1280. "DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
  1281. NI.getUnitOffset(), EntryID, DIEOffset, EntryOr->tag(),
  1282. DIE.getTag());
  1283. ++NumErrors;
  1284. }
  1285. auto EntryNames = getNames(DIE);
  1286. if (!is_contained(EntryNames, Str)) {
  1287. error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Name "
  1288. "of DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
  1289. NI.getUnitOffset(), EntryID, DIEOffset, Str,
  1290. make_range(EntryNames.begin(), EntryNames.end()));
  1291. ++NumErrors;
  1292. }
  1293. }
  1294. handleAllErrors(EntryOr.takeError(),
  1295. [&](const DWARFDebugNames::SentinelError &) {
  1296. if (NumEntries > 0)
  1297. return;
  1298. error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is "
  1299. "not associated with any entries.\n",
  1300. NI.getUnitOffset(), NTE.getIndex(), Str);
  1301. ++NumErrors;
  1302. },
  1303. [&](const ErrorInfoBase &Info) {
  1304. error()
  1305. << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n",
  1306. NI.getUnitOffset(), NTE.getIndex(), Str,
  1307. Info.message());
  1308. ++NumErrors;
  1309. });
  1310. return NumErrors;
  1311. }
  1312. static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx) {
  1313. Expected<std::vector<DWARFLocationExpression>> Loc =
  1314. Die.getLocations(DW_AT_location);
  1315. if (!Loc) {
  1316. consumeError(Loc.takeError());
  1317. return false;
  1318. }
  1319. DWARFUnit *U = Die.getDwarfUnit();
  1320. for (const auto &Entry : *Loc) {
  1321. DataExtractor Data(toStringRef(Entry.Expr), DCtx.isLittleEndian(),
  1322. U->getAddressByteSize());
  1323. DWARFExpression Expression(Data, U->getAddressByteSize(),
  1324. U->getFormParams().Format);
  1325. bool IsInteresting =
  1326. any_of(Expression, [](const DWARFExpression::Operation &Op) {
  1327. return !Op.isError() && (Op.getCode() == DW_OP_addr ||
  1328. Op.getCode() == DW_OP_form_tls_address ||
  1329. Op.getCode() == DW_OP_GNU_push_tls_address);
  1330. });
  1331. if (IsInteresting)
  1332. return true;
  1333. }
  1334. return false;
  1335. }
  1336. unsigned DWARFVerifier::verifyNameIndexCompleteness(
  1337. const DWARFDie &Die, const DWARFDebugNames::NameIndex &NI) {
  1338. // First check, if the Die should be indexed. The code follows the DWARF v5
  1339. // wording as closely as possible.
  1340. // "All non-defining declarations (that is, debugging information entries
  1341. // with a DW_AT_declaration attribute) are excluded."
  1342. if (Die.find(DW_AT_declaration))
  1343. return 0;
  1344. // "DW_TAG_namespace debugging information entries without a DW_AT_name
  1345. // attribute are included with the name “(anonymous namespace)”.
  1346. // All other debugging information entries without a DW_AT_name attribute
  1347. // are excluded."
  1348. // "If a subprogram or inlined subroutine is included, and has a
  1349. // DW_AT_linkage_name attribute, there will be an additional index entry for
  1350. // the linkage name."
  1351. auto IncludeLinkageName = Die.getTag() == DW_TAG_subprogram ||
  1352. Die.getTag() == DW_TAG_inlined_subroutine;
  1353. auto EntryNames = getNames(Die, IncludeLinkageName);
  1354. if (EntryNames.empty())
  1355. return 0;
  1356. // We deviate from the specification here, which says:
  1357. // "The name index must contain an entry for each debugging information entry
  1358. // that defines a named subprogram, label, variable, type, or namespace,
  1359. // subject to ..."
  1360. // Explicitly exclude all TAGs that we know shouldn't be indexed.
  1361. switch (Die.getTag()) {
  1362. // Compile units and modules have names but shouldn't be indexed.
  1363. case DW_TAG_compile_unit:
  1364. case DW_TAG_module:
  1365. return 0;
  1366. // Function and template parameters are not globally visible, so we shouldn't
  1367. // index them.
  1368. case DW_TAG_formal_parameter:
  1369. case DW_TAG_template_value_parameter:
  1370. case DW_TAG_template_type_parameter:
  1371. case DW_TAG_GNU_template_parameter_pack:
  1372. case DW_TAG_GNU_template_template_param:
  1373. return 0;
  1374. // Object members aren't globally visible.
  1375. case DW_TAG_member:
  1376. return 0;
  1377. // According to a strict reading of the specification, enumerators should not
  1378. // be indexed (and LLVM currently does not do that). However, this causes
  1379. // problems for the debuggers, so we may need to reconsider this.
  1380. case DW_TAG_enumerator:
  1381. return 0;
  1382. // Imported declarations should not be indexed according to the specification
  1383. // and LLVM currently does not do that.
  1384. case DW_TAG_imported_declaration:
  1385. return 0;
  1386. // "DW_TAG_subprogram, DW_TAG_inlined_subroutine, and DW_TAG_label debugging
  1387. // information entries without an address attribute (DW_AT_low_pc,
  1388. // DW_AT_high_pc, DW_AT_ranges, or DW_AT_entry_pc) are excluded."
  1389. case DW_TAG_subprogram:
  1390. case DW_TAG_inlined_subroutine:
  1391. case DW_TAG_label:
  1392. if (Die.findRecursively(
  1393. {DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_entry_pc}))
  1394. break;
  1395. return 0;
  1396. // "DW_TAG_variable debugging information entries with a DW_AT_location
  1397. // attribute that includes a DW_OP_addr or DW_OP_form_tls_address operator are
  1398. // included; otherwise, they are excluded."
  1399. //
  1400. // LLVM extension: We also add DW_OP_GNU_push_tls_address to this list.
  1401. case DW_TAG_variable:
  1402. if (isVariableIndexable(Die, DCtx))
  1403. break;
  1404. return 0;
  1405. default:
  1406. break;
  1407. }
  1408. // Now we know that our Die should be present in the Index. Let's check if
  1409. // that's the case.
  1410. unsigned NumErrors = 0;
  1411. uint64_t DieUnitOffset = Die.getOffset() - Die.getDwarfUnit()->getOffset();
  1412. for (StringRef Name : EntryNames) {
  1413. if (none_of(NI.equal_range(Name), [&](const DWARFDebugNames::Entry &E) {
  1414. return E.getDIEUnitOffset() == DieUnitOffset;
  1415. })) {
  1416. error() << formatv("Name Index @ {0:x}: Entry for DIE @ {1:x} ({2}) with "
  1417. "name {3} missing.\n",
  1418. NI.getUnitOffset(), Die.getOffset(), Die.getTag(),
  1419. Name);
  1420. ++NumErrors;
  1421. }
  1422. }
  1423. return NumErrors;
  1424. }
  1425. unsigned DWARFVerifier::verifyDebugNames(const DWARFSection &AccelSection,
  1426. const DataExtractor &StrData) {
  1427. unsigned NumErrors = 0;
  1428. DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), AccelSection,
  1429. DCtx.isLittleEndian(), 0);
  1430. DWARFDebugNames AccelTable(AccelSectionData, StrData);
  1431. OS << "Verifying .debug_names...\n";
  1432. // This verifies that we can read individual name indices and their
  1433. // abbreviation tables.
  1434. if (Error E = AccelTable.extract()) {
  1435. error() << toString(std::move(E)) << '\n';
  1436. return 1;
  1437. }
  1438. NumErrors += verifyDebugNamesCULists(AccelTable);
  1439. for (const auto &NI : AccelTable)
  1440. NumErrors += verifyNameIndexBuckets(NI, StrData);
  1441. for (const auto &NI : AccelTable)
  1442. NumErrors += verifyNameIndexAbbrevs(NI);
  1443. // Don't attempt Entry validation if any of the previous checks found errors
  1444. if (NumErrors > 0)
  1445. return NumErrors;
  1446. for (const auto &NI : AccelTable)
  1447. for (const DWARFDebugNames::NameTableEntry &NTE : NI)
  1448. NumErrors += verifyNameIndexEntries(NI, NTE);
  1449. if (NumErrors > 0)
  1450. return NumErrors;
  1451. for (const std::unique_ptr<DWARFUnit> &U : DCtx.compile_units()) {
  1452. if (const DWARFDebugNames::NameIndex *NI =
  1453. AccelTable.getCUNameIndex(U->getOffset())) {
  1454. auto *CU = cast<DWARFCompileUnit>(U.get());
  1455. for (const DWARFDebugInfoEntry &Die : CU->dies())
  1456. NumErrors += verifyNameIndexCompleteness(DWARFDie(CU, &Die), *NI);
  1457. }
  1458. }
  1459. return NumErrors;
  1460. }
  1461. bool DWARFVerifier::handleAccelTables() {
  1462. const DWARFObject &D = DCtx.getDWARFObj();
  1463. DataExtractor StrData(D.getStrSection(), DCtx.isLittleEndian(), 0);
  1464. unsigned NumErrors = 0;
  1465. if (!D.getAppleNamesSection().Data.empty())
  1466. NumErrors += verifyAppleAccelTable(&D.getAppleNamesSection(), &StrData,
  1467. ".apple_names");
  1468. if (!D.getAppleTypesSection().Data.empty())
  1469. NumErrors += verifyAppleAccelTable(&D.getAppleTypesSection(), &StrData,
  1470. ".apple_types");
  1471. if (!D.getAppleNamespacesSection().Data.empty())
  1472. NumErrors += verifyAppleAccelTable(&D.getAppleNamespacesSection(), &StrData,
  1473. ".apple_namespaces");
  1474. if (!D.getAppleObjCSection().Data.empty())
  1475. NumErrors += verifyAppleAccelTable(&D.getAppleObjCSection(), &StrData,
  1476. ".apple_objc");
  1477. if (!D.getNamesSection().Data.empty())
  1478. NumErrors += verifyDebugNames(D.getNamesSection(), StrData);
  1479. return NumErrors == 0;
  1480. }
  1481. raw_ostream &DWARFVerifier::error() const { return WithColor::error(OS); }
  1482. raw_ostream &DWARFVerifier::warn() const { return WithColor::warning(OS); }
  1483. raw_ostream &DWARFVerifier::note() const { return WithColor::note(OS); }
  1484. raw_ostream &DWARFVerifier::dump(const DWARFDie &Die, unsigned indent) const {
  1485. Die.dump(OS, indent, DumpOpts);
  1486. return OS;
  1487. }