BugReporterVisitors.cpp 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393
  1. //===- BugReporterVisitors.cpp - Helpers for reporting bugs ---------------===//
  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. // This file defines a set of BugReporter "visitors" which can be used to
  11. // enhance the diagnostics reported for a bug.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/AST/DeclBase.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/ExprObjC.h"
  22. #include "clang/AST/Stmt.h"
  23. #include "clang/AST/Type.h"
  24. #include "clang/Analysis/AnalysisDeclContext.h"
  25. #include "clang/Analysis/CFG.h"
  26. #include "clang/Analysis/CFGStmtMap.h"
  27. #include "clang/Analysis/ProgramPoint.h"
  28. #include "clang/Basic/IdentifierTable.h"
  29. #include "clang/Basic/LLVM.h"
  30. #include "clang/Basic/SourceLocation.h"
  31. #include "clang/Basic/SourceManager.h"
  32. #include "clang/Lex/Lexer.h"
  33. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  34. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  35. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  36. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  37. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  38. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  39. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  40. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  41. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  42. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
  43. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  44. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  45. #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
  46. #include "clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h"
  47. #include "llvm/ADT/ArrayRef.h"
  48. #include "llvm/ADT/None.h"
  49. #include "llvm/ADT/Optional.h"
  50. #include "llvm/ADT/STLExtras.h"
  51. #include "llvm/ADT/SmallPtrSet.h"
  52. #include "llvm/ADT/SmallString.h"
  53. #include "llvm/ADT/SmallVector.h"
  54. #include "llvm/ADT/StringExtras.h"
  55. #include "llvm/ADT/StringRef.h"
  56. #include "llvm/Support/Casting.h"
  57. #include "llvm/Support/ErrorHandling.h"
  58. #include "llvm/Support/raw_ostream.h"
  59. #include <cassert>
  60. #include <deque>
  61. #include <memory>
  62. #include <string>
  63. #include <utility>
  64. using namespace clang;
  65. using namespace ento;
  66. //===----------------------------------------------------------------------===//
  67. // Utility functions.
  68. //===----------------------------------------------------------------------===//
  69. bool bugreporter::isDeclRefExprToReference(const Expr *E) {
  70. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  71. return DRE->getDecl()->getType()->isReferenceType();
  72. return false;
  73. }
  74. static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
  75. if (B->isAdditiveOp() && B->getType()->isPointerType()) {
  76. if (B->getLHS()->getType()->isPointerType()) {
  77. return B->getLHS();
  78. } else if (B->getRHS()->getType()->isPointerType()) {
  79. return B->getRHS();
  80. }
  81. }
  82. return nullptr;
  83. }
  84. /// Given that expression S represents a pointer that would be dereferenced,
  85. /// try to find a sub-expression from which the pointer came from.
  86. /// This is used for tracking down origins of a null or undefined value:
  87. /// "this is null because that is null because that is null" etc.
  88. /// We wipe away field and element offsets because they merely add offsets.
  89. /// We also wipe away all casts except lvalue-to-rvalue casts, because the
  90. /// latter represent an actual pointer dereference; however, we remove
  91. /// the final lvalue-to-rvalue cast before returning from this function
  92. /// because it demonstrates more clearly from where the pointer rvalue was
  93. /// loaded. Examples:
  94. /// x->y.z ==> x (lvalue)
  95. /// foo()->y.z ==> foo() (rvalue)
  96. const Expr *bugreporter::getDerefExpr(const Stmt *S) {
  97. const auto *E = dyn_cast<Expr>(S);
  98. if (!E)
  99. return nullptr;
  100. while (true) {
  101. if (const auto *CE = dyn_cast<CastExpr>(E)) {
  102. if (CE->getCastKind() == CK_LValueToRValue) {
  103. // This cast represents the load we're looking for.
  104. break;
  105. }
  106. E = CE->getSubExpr();
  107. } else if (const auto *B = dyn_cast<BinaryOperator>(E)) {
  108. // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
  109. if (const Expr *Inner = peelOffPointerArithmetic(B)) {
  110. E = Inner;
  111. } else {
  112. // Probably more arithmetic can be pattern-matched here,
  113. // but for now give up.
  114. break;
  115. }
  116. } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
  117. if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf ||
  118. (U->isIncrementDecrementOp() && U->getType()->isPointerType())) {
  119. // Operators '*' and '&' don't actually mean anything.
  120. // We look at casts instead.
  121. E = U->getSubExpr();
  122. } else {
  123. // Probably more arithmetic can be pattern-matched here,
  124. // but for now give up.
  125. break;
  126. }
  127. }
  128. // Pattern match for a few useful cases: a[0], p->f, *p etc.
  129. else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
  130. E = ME->getBase();
  131. } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
  132. E = IvarRef->getBase();
  133. } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
  134. E = AE->getBase();
  135. } else if (const auto *PE = dyn_cast<ParenExpr>(E)) {
  136. E = PE->getSubExpr();
  137. } else if (const auto *EWC = dyn_cast<ExprWithCleanups>(E)) {
  138. E = EWC->getSubExpr();
  139. } else {
  140. // Other arbitrary stuff.
  141. break;
  142. }
  143. }
  144. // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
  145. // deeper into the sub-expression. This way we return the lvalue from which
  146. // our pointer rvalue was loaded.
  147. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E))
  148. if (CE->getCastKind() == CK_LValueToRValue)
  149. E = CE->getSubExpr();
  150. return E;
  151. }
  152. const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
  153. const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
  154. if (const auto *BE = dyn_cast<BinaryOperator>(S))
  155. return BE->getRHS();
  156. return nullptr;
  157. }
  158. const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
  159. const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
  160. if (const auto *RS = dyn_cast<ReturnStmt>(S))
  161. return RS->getRetValue();
  162. return nullptr;
  163. }
  164. //===----------------------------------------------------------------------===//
  165. // Definitions for bug reporter visitors.
  166. //===----------------------------------------------------------------------===//
  167. std::shared_ptr<PathDiagnosticPiece>
  168. BugReporterVisitor::getEndPath(BugReporterContext &BRC,
  169. const ExplodedNode *EndPathNode, BugReport &BR) {
  170. return nullptr;
  171. }
  172. void
  173. BugReporterVisitor::finalizeVisitor(BugReporterContext &BRC,
  174. const ExplodedNode *EndPathNode,
  175. BugReport &BR) {}
  176. std::shared_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
  177. BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
  178. PathDiagnosticLocation L =
  179. PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
  180. const auto &Ranges = BR.getRanges();
  181. // Only add the statement itself as a range if we didn't specify any
  182. // special ranges for this report.
  183. auto P = std::make_shared<PathDiagnosticEventPiece>(
  184. L, BR.getDescription(), Ranges.begin() == Ranges.end());
  185. for (SourceRange Range : Ranges)
  186. P->addRange(Range);
  187. return P;
  188. }
  189. /// \return name of the macro inside the location \p Loc.
  190. static StringRef getMacroName(SourceLocation Loc,
  191. BugReporterContext &BRC) {
  192. return Lexer::getImmediateMacroName(
  193. Loc,
  194. BRC.getSourceManager(),
  195. BRC.getASTContext().getLangOpts());
  196. }
  197. /// \return Whether given spelling location corresponds to an expansion
  198. /// of a function-like macro.
  199. static bool isFunctionMacroExpansion(SourceLocation Loc,
  200. const SourceManager &SM) {
  201. if (!Loc.isMacroID())
  202. return false;
  203. while (SM.isMacroArgExpansion(Loc))
  204. Loc = SM.getImmediateExpansionRange(Loc).getBegin();
  205. std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
  206. SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
  207. const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
  208. return EInfo.isFunctionMacroExpansion();
  209. }
  210. namespace {
  211. /// Put a diagnostic on return statement of all inlined functions
  212. /// for which the region of interest \p RegionOfInterest was passed into,
  213. /// but not written inside, and it has caused an undefined read or a null
  214. /// pointer dereference outside.
  215. class NoStoreFuncVisitor final : public BugReporterVisitor {
  216. const SubRegion *RegionOfInterest;
  217. static constexpr const char *DiagnosticsMsg =
  218. "Returning without writing to '";
  219. /// Frames writing into \c RegionOfInterest.
  220. /// This visitor generates a note only if a function does not write into
  221. /// a region of interest. This information is not immediately available
  222. /// by looking at the node associated with the exit from the function
  223. /// (usually the return statement). To avoid recomputing the same information
  224. /// many times (going up the path for each node and checking whether the
  225. /// region was written into) we instead lazily compute the
  226. /// stack frames along the path which write into the region of interest.
  227. llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion;
  228. llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated;
  229. public:
  230. NoStoreFuncVisitor(const SubRegion *R) : RegionOfInterest(R) {}
  231. void Profile(llvm::FoldingSetNodeID &ID) const override {
  232. static int Tag = 0;
  233. ID.AddPointer(&Tag);
  234. }
  235. std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
  236. const ExplodedNode *PrevN,
  237. BugReporterContext &BRC,
  238. BugReport &BR) override {
  239. const LocationContext *Ctx = N->getLocationContext();
  240. const StackFrameContext *SCtx = Ctx->getStackFrame();
  241. ProgramStateRef State = N->getState();
  242. auto CallExitLoc = N->getLocationAs<CallExitBegin>();
  243. // No diagnostic if region was modified inside the frame.
  244. if (!CallExitLoc)
  245. return nullptr;
  246. CallEventRef<> Call =
  247. BRC.getStateManager().getCallEventManager().getCaller(SCtx, State);
  248. const PrintingPolicy &PP = BRC.getASTContext().getPrintingPolicy();
  249. const SourceManager &SM = BRC.getSourceManager();
  250. if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
  251. const MemRegion *ThisRegion = CCall->getCXXThisVal().getAsRegion();
  252. if (RegionOfInterest->isSubRegionOf(ThisRegion)
  253. && !CCall->getDecl()->isImplicit()
  254. && !isRegionOfInterestModifiedInFrame(N))
  255. return notModifiedInConstructorDiagnostics(Ctx, SM, PP, *CallExitLoc,
  256. CCall, ThisRegion);
  257. }
  258. ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call);
  259. for (unsigned I = 0; I < Call->getNumArgs() && I < parameters.size(); ++I) {
  260. const ParmVarDecl *PVD = parameters[I];
  261. SVal S = Call->getArgSVal(I);
  262. unsigned IndirectionLevel = 1;
  263. QualType T = PVD->getType();
  264. while (const MemRegion *R = S.getAsRegion()) {
  265. if (RegionOfInterest->isSubRegionOf(R)
  266. && !isPointerToConst(PVD->getType())) {
  267. if (isRegionOfInterestModifiedInFrame(N))
  268. return nullptr;
  269. return notModifiedDiagnostics(
  270. Ctx, SM, PP, *CallExitLoc, Call, PVD, R, IndirectionLevel);
  271. }
  272. QualType PT = T->getPointeeType();
  273. if (PT.isNull() || PT->isVoidType()) break;
  274. S = State->getSVal(R, PT);
  275. T = PT;
  276. IndirectionLevel++;
  277. }
  278. }
  279. return nullptr;
  280. }
  281. private:
  282. /// Check and lazily calculate whether the region of interest is
  283. /// modified in the stack frame to which \p N belongs.
  284. /// The calculation is cached in FramesModifyingRegion.
  285. bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) {
  286. const LocationContext *Ctx = N->getLocationContext();
  287. const StackFrameContext *SCtx = Ctx->getStackFrame();
  288. if (!FramesModifyingCalculated.count(SCtx))
  289. findModifyingFrames(N);
  290. return FramesModifyingRegion.count(SCtx);
  291. }
  292. /// Write to \c FramesModifyingRegion all stack frames along
  293. /// the path in the current stack frame which modify \c RegionOfInterest.
  294. void findModifyingFrames(const ExplodedNode *N) {
  295. assert(N->getLocationAs<CallExitBegin>());
  296. ProgramStateRef LastReturnState = N->getState();
  297. SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
  298. const LocationContext *Ctx = N->getLocationContext();
  299. const StackFrameContext *OriginalSCtx = Ctx->getStackFrame();
  300. do {
  301. ProgramStateRef State = N->getState();
  302. auto CallExitLoc = N->getLocationAs<CallExitBegin>();
  303. if (CallExitLoc) {
  304. LastReturnState = State;
  305. ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
  306. }
  307. FramesModifyingCalculated.insert(
  308. N->getLocationContext()->getStackFrame());
  309. if (wasRegionOfInterestModifiedAt(N, LastReturnState, ValueAtReturn)) {
  310. const StackFrameContext *SCtx = N->getStackFrame();
  311. while (!SCtx->inTopFrame()) {
  312. auto p = FramesModifyingRegion.insert(SCtx);
  313. if (!p.second)
  314. break; // Frame and all its parents already inserted.
  315. SCtx = SCtx->getParent()->getStackFrame();
  316. }
  317. }
  318. // Stop calculation at the call to the current function.
  319. if (auto CE = N->getLocationAs<CallEnter>())
  320. if (CE->getCalleeContext() == OriginalSCtx)
  321. break;
  322. N = N->getFirstPred();
  323. } while (N);
  324. }
  325. /// \return Whether \c RegionOfInterest was modified at \p N,
  326. /// where \p ReturnState is a state associated with the return
  327. /// from the current frame.
  328. bool wasRegionOfInterestModifiedAt(const ExplodedNode *N,
  329. ProgramStateRef ReturnState,
  330. SVal ValueAtReturn) {
  331. if (!N->getLocationAs<PostStore>()
  332. && !N->getLocationAs<PostInitializer>()
  333. && !N->getLocationAs<PostStmt>())
  334. return false;
  335. // Writing into region of interest.
  336. if (auto PS = N->getLocationAs<PostStmt>())
  337. if (auto *BO = PS->getStmtAs<BinaryOperator>())
  338. if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
  339. N->getSVal(BO->getLHS()).getAsRegion()))
  340. return true;
  341. // SVal after the state is possibly different.
  342. SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
  343. if (!ReturnState->areEqual(ValueAtN, ValueAtReturn).isConstrainedTrue() &&
  344. (!ValueAtN.isUndef() || !ValueAtReturn.isUndef()))
  345. return true;
  346. return false;
  347. }
  348. /// Get parameters associated with runtime definition in order
  349. /// to get the correct parameter name.
  350. ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) {
  351. // Use runtime definition, if available.
  352. RuntimeDefinition RD = Call->getRuntimeDefinition();
  353. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl()))
  354. return FD->parameters();
  355. return Call->parameters();
  356. }
  357. /// \return whether \p Ty points to a const type, or is a const reference.
  358. bool isPointerToConst(QualType Ty) {
  359. return !Ty->getPointeeType().isNull() &&
  360. Ty->getPointeeType().getCanonicalType().isConstQualified();
  361. }
  362. std::shared_ptr<PathDiagnosticPiece> notModifiedInConstructorDiagnostics(
  363. const LocationContext *Ctx,
  364. const SourceManager &SM,
  365. const PrintingPolicy &PP,
  366. CallExitBegin &CallExitLoc,
  367. const CXXConstructorCall *Call,
  368. const MemRegion *ArgRegion) {
  369. SmallString<256> sbuf;
  370. llvm::raw_svector_ostream os(sbuf);
  371. os << DiagnosticsMsg;
  372. bool out = prettyPrintRegionName(
  373. "this", "->", /*IsReference=*/true,
  374. /*IndirectionLevel=*/1, ArgRegion, os, PP);
  375. // Return nothing if we have failed to pretty-print.
  376. if (!out)
  377. return nullptr;
  378. os << "'";
  379. PathDiagnosticLocation L =
  380. getPathDiagnosticLocation(nullptr, SM, Ctx, Call);
  381. return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
  382. }
  383. /// \p IndirectionLevel How many times \c ArgRegion has to be dereferenced
  384. /// before we get to the super region of \c RegionOfInterest
  385. std::shared_ptr<PathDiagnosticPiece>
  386. notModifiedDiagnostics(const LocationContext *Ctx,
  387. const SourceManager &SM,
  388. const PrintingPolicy &PP,
  389. CallExitBegin &CallExitLoc,
  390. CallEventRef<> Call,
  391. const ParmVarDecl *PVD,
  392. const MemRegion *ArgRegion,
  393. unsigned IndirectionLevel) {
  394. PathDiagnosticLocation L = getPathDiagnosticLocation(
  395. CallExitLoc.getReturnStmt(), SM, Ctx, Call);
  396. SmallString<256> sbuf;
  397. llvm::raw_svector_ostream os(sbuf);
  398. os << DiagnosticsMsg;
  399. bool IsReference = PVD->getType()->isReferenceType();
  400. const char *Sep = IsReference && IndirectionLevel == 1 ? "." : "->";
  401. bool Success = prettyPrintRegionName(
  402. PVD->getQualifiedNameAsString().c_str(),
  403. Sep, IsReference, IndirectionLevel, ArgRegion, os, PP);
  404. // Print the parameter name if the pretty-printing has failed.
  405. if (!Success)
  406. PVD->printQualifiedName(os);
  407. os << "'";
  408. return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
  409. }
  410. /// \return a path diagnostic location for the optionally
  411. /// present return statement \p RS.
  412. PathDiagnosticLocation getPathDiagnosticLocation(const ReturnStmt *RS,
  413. const SourceManager &SM,
  414. const LocationContext *Ctx,
  415. CallEventRef<> Call) {
  416. if (RS)
  417. return PathDiagnosticLocation::createBegin(RS, SM, Ctx);
  418. return PathDiagnosticLocation(
  419. Call->getRuntimeDefinition().getDecl()->getSourceRange().getEnd(), SM);
  420. }
  421. /// Pretty-print region \p ArgRegion starting from parent to \p os.
  422. /// \return whether printing has succeeded
  423. bool prettyPrintRegionName(const char *TopRegionName,
  424. const char *Sep,
  425. bool IsReference,
  426. int IndirectionLevel,
  427. const MemRegion *ArgRegion,
  428. llvm::raw_svector_ostream &os,
  429. const PrintingPolicy &PP) {
  430. SmallVector<const MemRegion *, 5> Subregions;
  431. const MemRegion *R = RegionOfInterest;
  432. while (R != ArgRegion) {
  433. if (!(isa<FieldRegion>(R) || isa<CXXBaseObjectRegion>(R)))
  434. return false; // Pattern-matching failed.
  435. Subregions.push_back(R);
  436. R = cast<SubRegion>(R)->getSuperRegion();
  437. }
  438. bool IndirectReference = !Subregions.empty();
  439. if (IndirectReference)
  440. IndirectionLevel--; // Due to "->" symbol.
  441. if (IsReference)
  442. IndirectionLevel--; // Due to reference semantics.
  443. bool ShouldSurround = IndirectReference && IndirectionLevel > 0;
  444. if (ShouldSurround)
  445. os << "(";
  446. for (int i = 0; i < IndirectionLevel; i++)
  447. os << "*";
  448. os << TopRegionName;
  449. if (ShouldSurround)
  450. os << ")";
  451. for (auto I = Subregions.rbegin(), E = Subregions.rend(); I != E; ++I) {
  452. if (const auto *FR = dyn_cast<FieldRegion>(*I)) {
  453. os << Sep;
  454. FR->getDecl()->getDeclName().print(os, PP);
  455. Sep = ".";
  456. } else if (isa<CXXBaseObjectRegion>(*I)) {
  457. continue; // Just keep going up to the base region.
  458. } else {
  459. llvm_unreachable("Previous check has missed an unexpected region");
  460. }
  461. }
  462. return true;
  463. }
  464. };
  465. class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor {
  466. const SubRegion *RegionOfInterest;
  467. public:
  468. MacroNullReturnSuppressionVisitor(const SubRegion *R) : RegionOfInterest(R) {}
  469. static void *getTag() {
  470. static int Tag = 0;
  471. return static_cast<void *>(&Tag);
  472. }
  473. void Profile(llvm::FoldingSetNodeID &ID) const override {
  474. ID.AddPointer(getTag());
  475. }
  476. std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
  477. const ExplodedNode *PrevN,
  478. BugReporterContext &BRC,
  479. BugReport &BR) override {
  480. auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
  481. if (!BugPoint)
  482. return nullptr;
  483. const SourceManager &SMgr = BRC.getSourceManager();
  484. if (auto Loc = matchAssignment(N, BRC)) {
  485. if (isFunctionMacroExpansion(*Loc, SMgr)) {
  486. std::string MacroName = getMacroName(*Loc, BRC);
  487. SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
  488. if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
  489. BR.markInvalid(getTag(), MacroName.c_str());
  490. }
  491. }
  492. return nullptr;
  493. }
  494. static void addMacroVisitorIfNecessary(
  495. const ExplodedNode *N, const MemRegion *R,
  496. bool EnableNullFPSuppression, BugReport &BR,
  497. const SVal V) {
  498. AnalyzerOptions &Options = N->getState()->getStateManager()
  499. .getOwningEngine()->getAnalysisManager().options;
  500. if (EnableNullFPSuppression && Options.shouldSuppressNullReturnPaths()
  501. && V.getAs<Loc>())
  502. BR.addVisitor(llvm::make_unique<MacroNullReturnSuppressionVisitor>(
  503. R->getAs<SubRegion>()));
  504. }
  505. private:
  506. /// \return Source location of right hand side of an assignment
  507. /// into \c RegionOfInterest, empty optional if none found.
  508. Optional<SourceLocation> matchAssignment(const ExplodedNode *N,
  509. BugReporterContext &BRC) {
  510. const Stmt *S = PathDiagnosticLocation::getStmt(N);
  511. ProgramStateRef State = N->getState();
  512. auto *LCtx = N->getLocationContext();
  513. if (!S)
  514. return None;
  515. if (const auto *DS = dyn_cast<DeclStmt>(S)) {
  516. if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
  517. if (const Expr *RHS = VD->getInit())
  518. if (RegionOfInterest->isSubRegionOf(
  519. State->getLValue(VD, LCtx).getAsRegion()))
  520. return RHS->getLocStart();
  521. } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
  522. const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
  523. const Expr *RHS = BO->getRHS();
  524. if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
  525. return RHS->getLocStart();
  526. }
  527. }
  528. return None;
  529. }
  530. };
  531. /// Emits an extra note at the return statement of an interesting stack frame.
  532. ///
  533. /// The returned value is marked as an interesting value, and if it's null,
  534. /// adds a visitor to track where it became null.
  535. ///
  536. /// This visitor is intended to be used when another visitor discovers that an
  537. /// interesting value comes from an inlined function call.
  538. class ReturnVisitor : public BugReporterVisitor {
  539. const StackFrameContext *StackFrame;
  540. enum {
  541. Initial,
  542. MaybeUnsuppress,
  543. Satisfied
  544. } Mode = Initial;
  545. bool EnableNullFPSuppression;
  546. bool ShouldInvalidate = true;
  547. public:
  548. ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
  549. : StackFrame(Frame), EnableNullFPSuppression(Suppressed) {}
  550. static void *getTag() {
  551. static int Tag = 0;
  552. return static_cast<void *>(&Tag);
  553. }
  554. void Profile(llvm::FoldingSetNodeID &ID) const override {
  555. ID.AddPointer(ReturnVisitor::getTag());
  556. ID.AddPointer(StackFrame);
  557. ID.AddBoolean(EnableNullFPSuppression);
  558. }
  559. /// Adds a ReturnVisitor if the given statement represents a call that was
  560. /// inlined.
  561. ///
  562. /// This will search back through the ExplodedGraph, starting from the given
  563. /// node, looking for when the given statement was processed. If it turns out
  564. /// the statement is a call that was inlined, we add the visitor to the
  565. /// bug report, so it can print a note later.
  566. static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
  567. BugReport &BR,
  568. bool InEnableNullFPSuppression) {
  569. if (!CallEvent::isCallStmt(S))
  570. return;
  571. // First, find when we processed the statement.
  572. do {
  573. if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
  574. if (CEE->getCalleeContext()->getCallSite() == S)
  575. break;
  576. if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
  577. if (SP->getStmt() == S)
  578. break;
  579. Node = Node->getFirstPred();
  580. } while (Node);
  581. // Next, step over any post-statement checks.
  582. while (Node && Node->getLocation().getAs<PostStmt>())
  583. Node = Node->getFirstPred();
  584. if (!Node)
  585. return;
  586. // Finally, see if we inlined the call.
  587. Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
  588. if (!CEE)
  589. return;
  590. const StackFrameContext *CalleeContext = CEE->getCalleeContext();
  591. if (CalleeContext->getCallSite() != S)
  592. return;
  593. // Check the return value.
  594. ProgramStateRef State = Node->getState();
  595. SVal RetVal = Node->getSVal(S);
  596. // Handle cases where a reference is returned and then immediately used.
  597. if (cast<Expr>(S)->isGLValue())
  598. if (Optional<Loc> LValue = RetVal.getAs<Loc>())
  599. RetVal = State->getSVal(*LValue);
  600. // See if the return value is NULL. If so, suppress the report.
  601. SubEngine *Eng = State->getStateManager().getOwningEngine();
  602. assert(Eng && "Cannot file a bug report without an owning engine");
  603. AnalyzerOptions &Options = Eng->getAnalysisManager().options;
  604. bool EnableNullFPSuppression = false;
  605. if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
  606. if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
  607. EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
  608. BR.markInteresting(CalleeContext);
  609. BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
  610. EnableNullFPSuppression));
  611. }
  612. /// Returns true if any counter-suppression heuristics are enabled for
  613. /// ReturnVisitor.
  614. static bool hasCounterSuppression(AnalyzerOptions &Options) {
  615. return Options.shouldAvoidSuppressingNullArgumentPaths();
  616. }
  617. std::shared_ptr<PathDiagnosticPiece>
  618. visitNodeInitial(const ExplodedNode *N, const ExplodedNode *PrevN,
  619. BugReporterContext &BRC, BugReport &BR) {
  620. // Only print a message at the interesting return statement.
  621. if (N->getLocationContext() != StackFrame)
  622. return nullptr;
  623. Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
  624. if (!SP)
  625. return nullptr;
  626. const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
  627. if (!Ret)
  628. return nullptr;
  629. // Okay, we're at the right return statement, but do we have the return
  630. // value available?
  631. ProgramStateRef State = N->getState();
  632. SVal V = State->getSVal(Ret, StackFrame);
  633. if (V.isUnknownOrUndef())
  634. return nullptr;
  635. // Don't print any more notes after this one.
  636. Mode = Satisfied;
  637. const Expr *RetE = Ret->getRetValue();
  638. assert(RetE && "Tracking a return value for a void function");
  639. // Handle cases where a reference is returned and then immediately used.
  640. Optional<Loc> LValue;
  641. if (RetE->isGLValue()) {
  642. if ((LValue = V.getAs<Loc>())) {
  643. SVal RValue = State->getRawSVal(*LValue, RetE->getType());
  644. if (RValue.getAs<DefinedSVal>())
  645. V = RValue;
  646. }
  647. }
  648. // Ignore aggregate rvalues.
  649. if (V.getAs<nonloc::LazyCompoundVal>() ||
  650. V.getAs<nonloc::CompoundVal>())
  651. return nullptr;
  652. RetE = RetE->IgnoreParenCasts();
  653. // If we can't prove the return value is 0, just mark it interesting, and
  654. // make sure to track it into any further inner functions.
  655. if (!State->isNull(V).isConstrainedTrue()) {
  656. BR.markInteresting(V);
  657. ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
  658. EnableNullFPSuppression);
  659. return nullptr;
  660. }
  661. // If we're returning 0, we should track where that 0 came from.
  662. bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
  663. EnableNullFPSuppression);
  664. // Build an appropriate message based on the return value.
  665. SmallString<64> Msg;
  666. llvm::raw_svector_ostream Out(Msg);
  667. if (V.getAs<Loc>()) {
  668. // If we have counter-suppression enabled, make sure we keep visiting
  669. // future nodes. We want to emit a path note as well, in case
  670. // the report is resurrected as valid later on.
  671. AnalyzerOptions &Options = BRC.getAnalyzerOptions();
  672. if (EnableNullFPSuppression && hasCounterSuppression(Options))
  673. Mode = MaybeUnsuppress;
  674. if (RetE->getType()->isObjCObjectPointerType())
  675. Out << "Returning nil";
  676. else
  677. Out << "Returning null pointer";
  678. } else {
  679. Out << "Returning zero";
  680. }
  681. if (LValue) {
  682. if (const MemRegion *MR = LValue->getAsRegion()) {
  683. if (MR->canPrintPretty()) {
  684. Out << " (reference to ";
  685. MR->printPretty(Out);
  686. Out << ")";
  687. }
  688. }
  689. } else {
  690. // FIXME: We should have a more generalized location printing mechanism.
  691. if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
  692. if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
  693. Out << " (loaded from '" << *DD << "')";
  694. }
  695. PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
  696. if (!L.isValid() || !L.asLocation().isValid())
  697. return nullptr;
  698. return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
  699. }
  700. std::shared_ptr<PathDiagnosticPiece>
  701. visitNodeMaybeUnsuppress(const ExplodedNode *N, const ExplodedNode *PrevN,
  702. BugReporterContext &BRC, BugReport &BR) {
  703. #ifndef NDEBUG
  704. AnalyzerOptions &Options = BRC.getAnalyzerOptions();
  705. assert(hasCounterSuppression(Options));
  706. #endif
  707. // Are we at the entry node for this call?
  708. Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
  709. if (!CE)
  710. return nullptr;
  711. if (CE->getCalleeContext() != StackFrame)
  712. return nullptr;
  713. Mode = Satisfied;
  714. // Don't automatically suppress a report if one of the arguments is
  715. // known to be a null pointer. Instead, start tracking /that/ null
  716. // value back to its origin.
  717. ProgramStateManager &StateMgr = BRC.getStateManager();
  718. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  719. ProgramStateRef State = N->getState();
  720. CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
  721. for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
  722. Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
  723. if (!ArgV)
  724. continue;
  725. const Expr *ArgE = Call->getArgExpr(I);
  726. if (!ArgE)
  727. continue;
  728. // Is it possible for this argument to be non-null?
  729. if (!State->isNull(*ArgV).isConstrainedTrue())
  730. continue;
  731. if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
  732. EnableNullFPSuppression))
  733. ShouldInvalidate = false;
  734. // If we /can't/ track the null pointer, we should err on the side of
  735. // false negatives, and continue towards marking this report invalid.
  736. // (We will still look at the other arguments, though.)
  737. }
  738. return nullptr;
  739. }
  740. std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
  741. const ExplodedNode *PrevN,
  742. BugReporterContext &BRC,
  743. BugReport &BR) override {
  744. switch (Mode) {
  745. case Initial:
  746. return visitNodeInitial(N, PrevN, BRC, BR);
  747. case MaybeUnsuppress:
  748. return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
  749. case Satisfied:
  750. return nullptr;
  751. }
  752. llvm_unreachable("Invalid visit mode!");
  753. }
  754. void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode *N,
  755. BugReport &BR) override {
  756. if (EnableNullFPSuppression && ShouldInvalidate)
  757. BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
  758. }
  759. };
  760. } // namespace
  761. void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  762. static int tag = 0;
  763. ID.AddPointer(&tag);
  764. ID.AddPointer(R);
  765. ID.Add(V);
  766. ID.AddBoolean(EnableNullFPSuppression);
  767. }
  768. /// Returns true if \p N represents the DeclStmt declaring and initializing
  769. /// \p VR.
  770. static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
  771. Optional<PostStmt> P = N->getLocationAs<PostStmt>();
  772. if (!P)
  773. return false;
  774. const DeclStmt *DS = P->getStmtAs<DeclStmt>();
  775. if (!DS)
  776. return false;
  777. if (DS->getSingleDecl() != VR->getDecl())
  778. return false;
  779. const MemSpaceRegion *VarSpace = VR->getMemorySpace();
  780. const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
  781. if (!FrameSpace) {
  782. // If we ever directly evaluate global DeclStmts, this assertion will be
  783. // invalid, but this still seems preferable to silently accepting an
  784. // initialization that may be for a path-sensitive variable.
  785. assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
  786. return true;
  787. }
  788. assert(VR->getDecl()->hasLocalStorage());
  789. const LocationContext *LCtx = N->getLocationContext();
  790. return FrameSpace->getStackFrame() == LCtx->getStackFrame();
  791. }
  792. /// Show diagnostics for initializing or declaring a region \p R with a bad value.
  793. static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os,
  794. const MemRegion *R, SVal V, const DeclStmt *DS) {
  795. if (R->canPrintPretty()) {
  796. R->printPretty(os);
  797. os << " ";
  798. }
  799. if (V.getAs<loc::ConcreteInt>()) {
  800. bool b = false;
  801. if (R->isBoundable()) {
  802. if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
  803. if (TR->getValueType()->isObjCObjectPointerType()) {
  804. os << action << "nil";
  805. b = true;
  806. }
  807. }
  808. }
  809. if (!b)
  810. os << action << "a null pointer value";
  811. } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) {
  812. os << action << CVal->getValue();
  813. } else if (DS) {
  814. if (V.isUndef()) {
  815. if (isa<VarRegion>(R)) {
  816. const auto *VD = cast<VarDecl>(DS->getSingleDecl());
  817. if (VD->getInit()) {
  818. os << (R->canPrintPretty() ? "initialized" : "Initializing")
  819. << " to a garbage value";
  820. } else {
  821. os << (R->canPrintPretty() ? "declared" : "Declaring")
  822. << " without an initial value";
  823. }
  824. }
  825. } else {
  826. os << (R->canPrintPretty() ? "initialized" : "Initialized")
  827. << " here";
  828. }
  829. }
  830. }
  831. /// Display diagnostics for passing bad region as a parameter.
  832. static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
  833. const VarRegion *VR,
  834. SVal V) {
  835. const auto *Param = cast<ParmVarDecl>(VR->getDecl());
  836. os << "Passing ";
  837. if (V.getAs<loc::ConcreteInt>()) {
  838. if (Param->getType()->isObjCObjectPointerType())
  839. os << "nil object reference";
  840. else
  841. os << "null pointer value";
  842. } else if (V.isUndef()) {
  843. os << "uninitialized value";
  844. } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
  845. os << "the value " << CI->getValue();
  846. } else {
  847. os << "value";
  848. }
  849. // Printed parameter indexes are 1-based, not 0-based.
  850. unsigned Idx = Param->getFunctionScopeIndex() + 1;
  851. os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
  852. if (VR->canPrintPretty()) {
  853. os << " ";
  854. VR->printPretty(os);
  855. }
  856. }
  857. /// Show default diagnostics for storing bad region.
  858. static void showBRDefaultDiagnostics(llvm::raw_svector_ostream& os,
  859. const MemRegion *R,
  860. SVal V) {
  861. if (V.getAs<loc::ConcreteInt>()) {
  862. bool b = false;
  863. if (R->isBoundable()) {
  864. if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
  865. if (TR->getValueType()->isObjCObjectPointerType()) {
  866. os << "nil object reference stored";
  867. b = true;
  868. }
  869. }
  870. }
  871. if (!b) {
  872. if (R->canPrintPretty())
  873. os << "Null pointer value stored";
  874. else
  875. os << "Storing null pointer value";
  876. }
  877. } else if (V.isUndef()) {
  878. if (R->canPrintPretty())
  879. os << "Uninitialized value stored";
  880. else
  881. os << "Storing uninitialized value";
  882. } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
  883. if (R->canPrintPretty())
  884. os << "The value " << CV->getValue() << " is assigned";
  885. else
  886. os << "Assigning " << CV->getValue();
  887. } else {
  888. if (R->canPrintPretty())
  889. os << "Value assigned";
  890. else
  891. os << "Assigning value";
  892. }
  893. if (R->canPrintPretty()) {
  894. os << " to ";
  895. R->printPretty(os);
  896. }
  897. }
  898. std::shared_ptr<PathDiagnosticPiece>
  899. FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
  900. const ExplodedNode *Pred,
  901. BugReporterContext &BRC, BugReport &BR) {
  902. if (Satisfied)
  903. return nullptr;
  904. const ExplodedNode *StoreSite = nullptr;
  905. const Expr *InitE = nullptr;
  906. bool IsParam = false;
  907. // First see if we reached the declaration of the region.
  908. if (const auto *VR = dyn_cast<VarRegion>(R)) {
  909. if (isInitializationOfVar(Pred, VR)) {
  910. StoreSite = Pred;
  911. InitE = VR->getDecl()->getInit();
  912. }
  913. }
  914. // If this is a post initializer expression, initializing the region, we
  915. // should track the initializer expression.
  916. if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
  917. const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
  918. if (FieldReg && FieldReg == R) {
  919. StoreSite = Pred;
  920. InitE = PIP->getInitializer()->getInit();
  921. }
  922. }
  923. // Otherwise, see if this is the store site:
  924. // (1) Succ has this binding and Pred does not, i.e. this is
  925. // where the binding first occurred.
  926. // (2) Succ has this binding and is a PostStore node for this region, i.e.
  927. // the same binding was re-assigned here.
  928. if (!StoreSite) {
  929. if (Succ->getState()->getSVal(R) != V)
  930. return nullptr;
  931. if (Pred->getState()->getSVal(R) == V) {
  932. Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
  933. if (!PS || PS->getLocationValue() != R)
  934. return nullptr;
  935. }
  936. StoreSite = Succ;
  937. // If this is an assignment expression, we can track the value
  938. // being assigned.
  939. if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
  940. if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
  941. if (BO->isAssignmentOp())
  942. InitE = BO->getRHS();
  943. // If this is a call entry, the variable should be a parameter.
  944. // FIXME: Handle CXXThisRegion as well. (This is not a priority because
  945. // 'this' should never be NULL, but this visitor isn't just for NULL and
  946. // UndefinedVal.)
  947. if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
  948. if (const auto *VR = dyn_cast<VarRegion>(R)) {
  949. const auto *Param = cast<ParmVarDecl>(VR->getDecl());
  950. ProgramStateManager &StateMgr = BRC.getStateManager();
  951. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  952. CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
  953. Succ->getState());
  954. InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
  955. IsParam = true;
  956. }
  957. }
  958. // If this is a CXXTempObjectRegion, the Expr responsible for its creation
  959. // is wrapped inside of it.
  960. if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
  961. InitE = TmpR->getExpr();
  962. }
  963. if (!StoreSite)
  964. return nullptr;
  965. Satisfied = true;
  966. // If we have an expression that provided the value, try to track where it
  967. // came from.
  968. if (InitE) {
  969. if (V.isUndef() ||
  970. V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  971. if (!IsParam)
  972. InitE = InitE->IgnoreParenCasts();
  973. bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
  974. EnableNullFPSuppression);
  975. } else {
  976. ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
  977. BR, EnableNullFPSuppression);
  978. }
  979. }
  980. // Okay, we've found the binding. Emit an appropriate message.
  981. SmallString<256> sbuf;
  982. llvm::raw_svector_ostream os(sbuf);
  983. if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
  984. const Stmt *S = PS->getStmt();
  985. const char *action = nullptr;
  986. const auto *DS = dyn_cast<DeclStmt>(S);
  987. const auto *VR = dyn_cast<VarRegion>(R);
  988. if (DS) {
  989. action = R->canPrintPretty() ? "initialized to " :
  990. "Initializing to ";
  991. } else if (isa<BlockExpr>(S)) {
  992. action = R->canPrintPretty() ? "captured by block as " :
  993. "Captured by block as ";
  994. if (VR) {
  995. // See if we can get the BlockVarRegion.
  996. ProgramStateRef State = StoreSite->getState();
  997. SVal V = StoreSite->getSVal(S);
  998. if (const auto *BDR =
  999. dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
  1000. if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
  1001. if (Optional<KnownSVal> KV =
  1002. State->getSVal(OriginalR).getAs<KnownSVal>())
  1003. BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  1004. *KV, OriginalR, EnableNullFPSuppression));
  1005. }
  1006. }
  1007. }
  1008. }
  1009. if (action)
  1010. showBRDiagnostics(action, os, R, V, DS);
  1011. } else if (StoreSite->getLocation().getAs<CallEnter>()) {
  1012. if (const auto *VR = dyn_cast<VarRegion>(R))
  1013. showBRParamDiagnostics(os, VR, V);
  1014. }
  1015. if (os.str().empty())
  1016. showBRDefaultDiagnostics(os, R, V);
  1017. // Construct a new PathDiagnosticPiece.
  1018. ProgramPoint P = StoreSite->getLocation();
  1019. PathDiagnosticLocation L;
  1020. if (P.getAs<CallEnter>() && InitE)
  1021. L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
  1022. P.getLocationContext());
  1023. if (!L.isValid() || !L.asLocation().isValid())
  1024. L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
  1025. if (!L.isValid() || !L.asLocation().isValid())
  1026. return nullptr;
  1027. return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
  1028. }
  1029. void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  1030. static int tag = 0;
  1031. ID.AddPointer(&tag);
  1032. ID.AddBoolean(Assumption);
  1033. ID.Add(Constraint);
  1034. }
  1035. /// Return the tag associated with this visitor. This tag will be used
  1036. /// to make all PathDiagnosticPieces created by this visitor.
  1037. const char *TrackConstraintBRVisitor::getTag() {
  1038. return "TrackConstraintBRVisitor";
  1039. }
  1040. bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
  1041. if (IsZeroCheck)
  1042. return N->getState()->isNull(Constraint).isUnderconstrained();
  1043. return (bool)N->getState()->assume(Constraint, !Assumption);
  1044. }
  1045. std::shared_ptr<PathDiagnosticPiece>
  1046. TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
  1047. const ExplodedNode *PrevN,
  1048. BugReporterContext &BRC, BugReport &BR) {
  1049. if (IsSatisfied)
  1050. return nullptr;
  1051. // Start tracking after we see the first state in which the value is
  1052. // constrained.
  1053. if (!IsTrackingTurnedOn)
  1054. if (!isUnderconstrained(N))
  1055. IsTrackingTurnedOn = true;
  1056. if (!IsTrackingTurnedOn)
  1057. return nullptr;
  1058. // Check if in the previous state it was feasible for this constraint
  1059. // to *not* be true.
  1060. if (isUnderconstrained(PrevN)) {
  1061. IsSatisfied = true;
  1062. // As a sanity check, make sure that the negation of the constraint
  1063. // was infeasible in the current state. If it is feasible, we somehow
  1064. // missed the transition point.
  1065. assert(!isUnderconstrained(N));
  1066. // We found the transition point for the constraint. We now need to
  1067. // pretty-print the constraint. (work-in-progress)
  1068. SmallString<64> sbuf;
  1069. llvm::raw_svector_ostream os(sbuf);
  1070. if (Constraint.getAs<Loc>()) {
  1071. os << "Assuming pointer value is ";
  1072. os << (Assumption ? "non-null" : "null");
  1073. }
  1074. if (os.str().empty())
  1075. return nullptr;
  1076. // Construct a new PathDiagnosticPiece.
  1077. ProgramPoint P = N->getLocation();
  1078. PathDiagnosticLocation L =
  1079. PathDiagnosticLocation::create(P, BRC.getSourceManager());
  1080. if (!L.isValid())
  1081. return nullptr;
  1082. auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
  1083. X->setTag(getTag());
  1084. return std::move(X);
  1085. }
  1086. return nullptr;
  1087. }
  1088. SuppressInlineDefensiveChecksVisitor::
  1089. SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
  1090. : V(Value) {
  1091. // Check if the visitor is disabled.
  1092. SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
  1093. assert(Eng && "Cannot file a bug report without an owning engine");
  1094. AnalyzerOptions &Options = Eng->getAnalysisManager().options;
  1095. if (!Options.shouldSuppressInlinedDefensiveChecks())
  1096. IsSatisfied = true;
  1097. assert(N->getState()->isNull(V).isConstrainedTrue() &&
  1098. "The visitor only tracks the cases where V is constrained to 0");
  1099. }
  1100. void SuppressInlineDefensiveChecksVisitor::Profile(
  1101. llvm::FoldingSetNodeID &ID) const {
  1102. static int id = 0;
  1103. ID.AddPointer(&id);
  1104. ID.Add(V);
  1105. }
  1106. const char *SuppressInlineDefensiveChecksVisitor::getTag() {
  1107. return "IDCVisitor";
  1108. }
  1109. std::shared_ptr<PathDiagnosticPiece>
  1110. SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
  1111. const ExplodedNode *Pred,
  1112. BugReporterContext &BRC,
  1113. BugReport &BR) {
  1114. if (IsSatisfied)
  1115. return nullptr;
  1116. // Start tracking after we see the first state in which the value is null.
  1117. if (!IsTrackingTurnedOn)
  1118. if (Succ->getState()->isNull(V).isConstrainedTrue())
  1119. IsTrackingTurnedOn = true;
  1120. if (!IsTrackingTurnedOn)
  1121. return nullptr;
  1122. // Check if in the previous state it was feasible for this value
  1123. // to *not* be null.
  1124. if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
  1125. IsSatisfied = true;
  1126. assert(Succ->getState()->isNull(V).isConstrainedTrue());
  1127. // Check if this is inlined defensive checks.
  1128. const LocationContext *CurLC =Succ->getLocationContext();
  1129. const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
  1130. if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
  1131. BR.markInvalid("Suppress IDC", CurLC);
  1132. return nullptr;
  1133. }
  1134. // Treat defensive checks in function-like macros as if they were an inlined
  1135. // defensive check. If the bug location is not in a macro and the
  1136. // terminator for the current location is in a macro then suppress the
  1137. // warning.
  1138. auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
  1139. if (!BugPoint)
  1140. return nullptr;
  1141. ProgramPoint CurPoint = Succ->getLocation();
  1142. const Stmt *CurTerminatorStmt = nullptr;
  1143. if (auto BE = CurPoint.getAs<BlockEdge>()) {
  1144. CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
  1145. } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
  1146. const Stmt *CurStmt = SP->getStmt();
  1147. if (!CurStmt->getLocStart().isMacroID())
  1148. return nullptr;
  1149. CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
  1150. CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
  1151. } else {
  1152. return nullptr;
  1153. }
  1154. if (!CurTerminatorStmt)
  1155. return nullptr;
  1156. SourceLocation TerminatorLoc = CurTerminatorStmt->getLocStart();
  1157. if (TerminatorLoc.isMacroID()) {
  1158. SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
  1159. // Suppress reports unless we are in that same macro.
  1160. if (!BugLoc.isMacroID() ||
  1161. getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
  1162. BR.markInvalid("Suppress Macro IDC", CurLC);
  1163. }
  1164. return nullptr;
  1165. }
  1166. }
  1167. return nullptr;
  1168. }
  1169. static const MemRegion *getLocationRegionIfReference(const Expr *E,
  1170. const ExplodedNode *N) {
  1171. if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
  1172. if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1173. if (!VD->getType()->isReferenceType())
  1174. return nullptr;
  1175. ProgramStateManager &StateMgr = N->getState()->getStateManager();
  1176. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  1177. return MRMgr.getVarRegion(VD, N->getLocationContext());
  1178. }
  1179. }
  1180. // FIXME: This does not handle other kinds of null references,
  1181. // for example, references from FieldRegions:
  1182. // struct Wrapper { int &ref; };
  1183. // Wrapper w = { *(int *)0 };
  1184. // w.ref = 1;
  1185. return nullptr;
  1186. }
  1187. static const Expr *peelOffOuterExpr(const Expr *Ex,
  1188. const ExplodedNode *N) {
  1189. Ex = Ex->IgnoreParenCasts();
  1190. if (const auto *EWC = dyn_cast<ExprWithCleanups>(Ex))
  1191. return peelOffOuterExpr(EWC->getSubExpr(), N);
  1192. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
  1193. return peelOffOuterExpr(OVE->getSourceExpr(), N);
  1194. if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
  1195. const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
  1196. if (PropRef && PropRef->isMessagingGetter()) {
  1197. const Expr *GetterMessageSend =
  1198. POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
  1199. assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
  1200. return peelOffOuterExpr(GetterMessageSend, N);
  1201. }
  1202. }
  1203. // Peel off the ternary operator.
  1204. if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
  1205. // Find a node where the branching occurred and find out which branch
  1206. // we took (true/false) by looking at the ExplodedGraph.
  1207. const ExplodedNode *NI = N;
  1208. do {
  1209. ProgramPoint ProgPoint = NI->getLocation();
  1210. if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
  1211. const CFGBlock *srcBlk = BE->getSrc();
  1212. if (const Stmt *term = srcBlk->getTerminator()) {
  1213. if (term == CO) {
  1214. bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
  1215. if (TookTrueBranch)
  1216. return peelOffOuterExpr(CO->getTrueExpr(), N);
  1217. else
  1218. return peelOffOuterExpr(CO->getFalseExpr(), N);
  1219. }
  1220. }
  1221. }
  1222. NI = NI->getFirstPred();
  1223. } while (NI);
  1224. }
  1225. if (auto *BO = dyn_cast<BinaryOperator>(Ex))
  1226. if (const Expr *SubEx = peelOffPointerArithmetic(BO))
  1227. return peelOffOuterExpr(SubEx, N);
  1228. return Ex;
  1229. }
  1230. /// Walk through nodes until we get one that matches the statement exactly.
  1231. /// Alternately, if we hit a known lvalue for the statement, we know we've
  1232. /// gone too far (though we can likely track the lvalue better anyway).
  1233. static const ExplodedNode* findNodeForStatement(const ExplodedNode *N,
  1234. const Stmt *S,
  1235. const Expr *Inner) {
  1236. do {
  1237. const ProgramPoint &pp = N->getLocation();
  1238. if (auto ps = pp.getAs<StmtPoint>()) {
  1239. if (ps->getStmt() == S || ps->getStmt() == Inner)
  1240. break;
  1241. } else if (auto CEE = pp.getAs<CallExitEnd>()) {
  1242. if (CEE->getCalleeContext()->getCallSite() == S ||
  1243. CEE->getCalleeContext()->getCallSite() == Inner)
  1244. break;
  1245. }
  1246. N = N->getFirstPred();
  1247. } while (N);
  1248. return N;
  1249. }
  1250. /// Find the ExplodedNode where the lvalue (the value of 'Ex')
  1251. /// was computed.
  1252. static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
  1253. const Expr *Inner) {
  1254. while (N) {
  1255. if (auto P = N->getLocation().getAs<PostStmt>()) {
  1256. if (P->getStmt() == Inner)
  1257. break;
  1258. }
  1259. N = N->getFirstPred();
  1260. }
  1261. assert(N && "Unable to find the lvalue node.");
  1262. return N;
  1263. }
  1264. /// Performing operator `&' on an lvalue expression is essentially a no-op.
  1265. /// Then, if we are taking addresses of fields or elements, these are also
  1266. /// unlikely to matter.
  1267. static const Expr* peelOfOuterAddrOf(const Expr* Ex) {
  1268. Ex = Ex->IgnoreParenCasts();
  1269. // FIXME: There's a hack in our Store implementation that always computes
  1270. // field offsets around null pointers as if they are always equal to 0.
  1271. // The idea here is to report accesses to fields as null dereferences
  1272. // even though the pointer value that's being dereferenced is actually
  1273. // the offset of the field rather than exactly 0.
  1274. // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
  1275. // This code interacts heavily with this hack; otherwise the value
  1276. // would not be null at all for most fields, so we'd be unable to track it.
  1277. if (const auto *Op = dyn_cast<UnaryOperator>(Ex))
  1278. if (Op->getOpcode() == UO_AddrOf && Op->getSubExpr()->isLValue())
  1279. if (const Expr *DerefEx = bugreporter::getDerefExpr(Op->getSubExpr()))
  1280. return DerefEx;
  1281. return Ex;
  1282. }
  1283. bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
  1284. const Stmt *S,
  1285. BugReport &report, bool IsArg,
  1286. bool EnableNullFPSuppression) {
  1287. if (!S || !N)
  1288. return false;
  1289. if (const auto *Ex = dyn_cast<Expr>(S))
  1290. S = peelOffOuterExpr(Ex, N);
  1291. const Expr *Inner = nullptr;
  1292. if (const auto *Ex = dyn_cast<Expr>(S)) {
  1293. Ex = peelOfOuterAddrOf(Ex);
  1294. Ex = Ex->IgnoreParenCasts();
  1295. if (Ex && (ExplodedGraph::isInterestingLValueExpr(Ex)
  1296. || CallEvent::isCallStmt(Ex)))
  1297. Inner = Ex;
  1298. }
  1299. if (IsArg && !Inner) {
  1300. assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
  1301. } else {
  1302. N = findNodeForStatement(N, S, Inner);
  1303. if (!N)
  1304. return false;
  1305. }
  1306. ProgramStateRef state = N->getState();
  1307. // The message send could be nil due to the receiver being nil.
  1308. // At this point in the path, the receiver should be live since we are at the
  1309. // message send expr. If it is nil, start tracking it.
  1310. if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
  1311. trackNullOrUndefValue(N, Receiver, report, /* IsArg=*/ false,
  1312. EnableNullFPSuppression);
  1313. // See if the expression we're interested refers to a variable.
  1314. // If so, we can track both its contents and constraints on its value.
  1315. if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
  1316. const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
  1317. ProgramStateRef LVState = LVNode->getState();
  1318. SVal LVal = LVNode->getSVal(Inner);
  1319. const MemRegion *RR = getLocationRegionIfReference(Inner, N);
  1320. bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
  1321. // If this is a C++ reference to a null pointer, we are tracking the
  1322. // pointer. In addition, we should find the store at which the reference
  1323. // got initialized.
  1324. if (RR && !LVIsNull) {
  1325. if (auto KV = LVal.getAs<KnownSVal>())
  1326. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  1327. *KV, RR, EnableNullFPSuppression));
  1328. }
  1329. // In case of C++ references, we want to differentiate between a null
  1330. // reference and reference to null pointer.
  1331. // If the LVal is null, check if we are dealing with null reference.
  1332. // For those, we want to track the location of the reference.
  1333. const MemRegion *R = (RR && LVIsNull) ? RR :
  1334. LVNode->getSVal(Inner).getAsRegion();
  1335. if (R) {
  1336. // Mark both the variable region and its contents as interesting.
  1337. SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
  1338. report.addVisitor(
  1339. llvm::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R)));
  1340. MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
  1341. N, R, EnableNullFPSuppression, report, V);
  1342. report.markInteresting(R);
  1343. report.markInteresting(V);
  1344. report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
  1345. // If the contents are symbolic, find out when they became null.
  1346. if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
  1347. report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
  1348. V.castAs<DefinedSVal>(), false));
  1349. // Add visitor, which will suppress inline defensive checks.
  1350. if (auto DV = V.getAs<DefinedSVal>()) {
  1351. if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
  1352. EnableNullFPSuppression) {
  1353. report.addVisitor(
  1354. llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
  1355. LVNode));
  1356. }
  1357. }
  1358. if (auto KV = V.getAs<KnownSVal>())
  1359. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  1360. *KV, R, EnableNullFPSuppression));
  1361. return true;
  1362. }
  1363. }
  1364. // If the expression is not an "lvalue expression", we can still
  1365. // track the constraints on its contents.
  1366. SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
  1367. // If the value came from an inlined function call, we should at least make
  1368. // sure that function isn't pruned in our output.
  1369. if (const auto *E = dyn_cast<Expr>(S))
  1370. S = E->IgnoreParenCasts();
  1371. ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
  1372. // Uncomment this to find cases where we aren't properly getting the
  1373. // base value that was dereferenced.
  1374. // assert(!V.isUnknownOrUndef());
  1375. // Is it a symbolic value?
  1376. if (auto L = V.getAs<loc::MemRegionVal>()) {
  1377. report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
  1378. // At this point we are dealing with the region's LValue.
  1379. // However, if the rvalue is a symbolic region, we should track it as well.
  1380. // Try to use the correct type when looking up the value.
  1381. SVal RVal;
  1382. if (const auto *E = dyn_cast<Expr>(S))
  1383. RVal = state->getRawSVal(L.getValue(), E->getType());
  1384. else
  1385. RVal = state->getSVal(L->getRegion());
  1386. if (auto KV = RVal.getAs<KnownSVal>())
  1387. report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  1388. *KV, L->getRegion(), EnableNullFPSuppression));
  1389. const MemRegion *RegionRVal = RVal.getAsRegion();
  1390. if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
  1391. report.markInteresting(RegionRVal);
  1392. report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
  1393. loc::MemRegionVal(RegionRVal), false));
  1394. }
  1395. }
  1396. return true;
  1397. }
  1398. const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
  1399. const ExplodedNode *N) {
  1400. const auto *ME = dyn_cast<ObjCMessageExpr>(S);
  1401. if (!ME)
  1402. return nullptr;
  1403. if (const Expr *Receiver = ME->getInstanceReceiver()) {
  1404. ProgramStateRef state = N->getState();
  1405. SVal V = N->getSVal(Receiver);
  1406. if (state->isNull(V).isConstrainedTrue())
  1407. return Receiver;
  1408. }
  1409. return nullptr;
  1410. }
  1411. std::shared_ptr<PathDiagnosticPiece>
  1412. NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
  1413. const ExplodedNode *PrevN,
  1414. BugReporterContext &BRC, BugReport &BR) {
  1415. Optional<PreStmt> P = N->getLocationAs<PreStmt>();
  1416. if (!P)
  1417. return nullptr;
  1418. const Stmt *S = P->getStmt();
  1419. const Expr *Receiver = getNilReceiver(S, N);
  1420. if (!Receiver)
  1421. return nullptr;
  1422. llvm::SmallString<256> Buf;
  1423. llvm::raw_svector_ostream OS(Buf);
  1424. if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
  1425. OS << "'";
  1426. ME->getSelector().print(OS);
  1427. OS << "' not called";
  1428. }
  1429. else {
  1430. OS << "No method is called";
  1431. }
  1432. OS << " because the receiver is nil";
  1433. // The receiver was nil, and hence the method was skipped.
  1434. // Register a BugReporterVisitor to issue a message telling us how
  1435. // the receiver was null.
  1436. bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
  1437. /*EnableNullFPSuppression*/ false);
  1438. // Issue a message saying that the method was skipped.
  1439. PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
  1440. N->getLocationContext());
  1441. return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
  1442. }
  1443. // Registers every VarDecl inside a Stmt with a last store visitor.
  1444. void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
  1445. const Stmt *S,
  1446. bool EnableNullFPSuppression) {
  1447. const ExplodedNode *N = BR.getErrorNode();
  1448. std::deque<const Stmt *> WorkList;
  1449. WorkList.push_back(S);
  1450. while (!WorkList.empty()) {
  1451. const Stmt *Head = WorkList.front();
  1452. WorkList.pop_front();
  1453. ProgramStateManager &StateMgr = N->getState()->getStateManager();
  1454. if (const auto *DR = dyn_cast<DeclRefExpr>(Head)) {
  1455. if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1456. const VarRegion *R =
  1457. StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
  1458. // What did we load?
  1459. SVal V = N->getSVal(S);
  1460. if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
  1461. // Register a new visitor with the BugReport.
  1462. BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
  1463. V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
  1464. }
  1465. }
  1466. }
  1467. for (const Stmt *SubStmt : Head->children())
  1468. WorkList.push_back(SubStmt);
  1469. }
  1470. }
  1471. //===----------------------------------------------------------------------===//
  1472. // Visitor that tries to report interesting diagnostics from conditions.
  1473. //===----------------------------------------------------------------------===//
  1474. /// Return the tag associated with this visitor. This tag will be used
  1475. /// to make all PathDiagnosticPieces created by this visitor.
  1476. const char *ConditionBRVisitor::getTag() {
  1477. return "ConditionBRVisitor";
  1478. }
  1479. std::shared_ptr<PathDiagnosticPiece>
  1480. ConditionBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *Prev,
  1481. BugReporterContext &BRC, BugReport &BR) {
  1482. auto piece = VisitNodeImpl(N, Prev, BRC, BR);
  1483. if (piece) {
  1484. piece->setTag(getTag());
  1485. if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
  1486. ev->setPrunable(true, /* override */ false);
  1487. }
  1488. return piece;
  1489. }
  1490. std::shared_ptr<PathDiagnosticPiece>
  1491. ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
  1492. const ExplodedNode *Prev,
  1493. BugReporterContext &BRC, BugReport &BR) {
  1494. ProgramPoint progPoint = N->getLocation();
  1495. ProgramStateRef CurrentState = N->getState();
  1496. ProgramStateRef PrevState = Prev->getState();
  1497. // Compare the GDMs of the state, because that is where constraints
  1498. // are managed. Note that ensure that we only look at nodes that
  1499. // were generated by the analyzer engine proper, not checkers.
  1500. if (CurrentState->getGDM().getRoot() ==
  1501. PrevState->getGDM().getRoot())
  1502. return nullptr;
  1503. // If an assumption was made on a branch, it should be caught
  1504. // here by looking at the state transition.
  1505. if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
  1506. const CFGBlock *srcBlk = BE->getSrc();
  1507. if (const Stmt *term = srcBlk->getTerminator())
  1508. return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
  1509. return nullptr;
  1510. }
  1511. if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
  1512. const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
  1513. ExprEngine::geteagerlyAssumeBinOpBifurcationTags();
  1514. const ProgramPointTag *tag = PS->getTag();
  1515. if (tag == tags.first)
  1516. return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
  1517. BRC, BR, N);
  1518. if (tag == tags.second)
  1519. return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
  1520. BRC, BR, N);
  1521. return nullptr;
  1522. }
  1523. return nullptr;
  1524. }
  1525. std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
  1526. const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
  1527. const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
  1528. const Expr *Cond = nullptr;
  1529. // In the code below, Term is a CFG terminator and Cond is a branch condition
  1530. // expression upon which the decision is made on this terminator.
  1531. //
  1532. // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
  1533. // and "x == 0" is the respective condition.
  1534. //
  1535. // Another example: in "if (x && y)", we've got two terminators and two
  1536. // conditions due to short-circuit nature of operator "&&":
  1537. // 1. The "if (x && y)" statement is a terminator,
  1538. // and "y" is the respective condition.
  1539. // 2. Also "x && ..." is another terminator,
  1540. // and "x" is its condition.
  1541. switch (Term->getStmtClass()) {
  1542. // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
  1543. // more tricky because there are more than two branches to account for.
  1544. default:
  1545. return nullptr;
  1546. case Stmt::IfStmtClass:
  1547. Cond = cast<IfStmt>(Term)->getCond();
  1548. break;
  1549. case Stmt::ConditionalOperatorClass:
  1550. Cond = cast<ConditionalOperator>(Term)->getCond();
  1551. break;
  1552. case Stmt::BinaryOperatorClass:
  1553. // When we encounter a logical operator (&& or ||) as a CFG terminator,
  1554. // then the condition is actually its LHS; otherwise, we'd encounter
  1555. // the parent, such as if-statement, as a terminator.
  1556. const auto *BO = cast<BinaryOperator>(Term);
  1557. assert(BO->isLogicalOp() &&
  1558. "CFG terminator is not a short-circuit operator!");
  1559. Cond = BO->getLHS();
  1560. break;
  1561. }
  1562. // However, when we encounter a logical operator as a branch condition,
  1563. // then the condition is actually its RHS, because LHS would be
  1564. // the condition for the logical operator terminator.
  1565. while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
  1566. if (!InnerBO->isLogicalOp())
  1567. break;
  1568. Cond = InnerBO->getRHS()->IgnoreParens();
  1569. }
  1570. assert(Cond);
  1571. assert(srcBlk->succ_size() == 2);
  1572. const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
  1573. return VisitTrueTest(Cond, tookTrue, BRC, R, N);
  1574. }
  1575. std::shared_ptr<PathDiagnosticPiece>
  1576. ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
  1577. BugReporterContext &BRC, BugReport &R,
  1578. const ExplodedNode *N) {
  1579. // These will be modified in code below, but we need to preserve the original
  1580. // values in case we want to throw the generic message.
  1581. const Expr *CondTmp = Cond;
  1582. bool tookTrueTmp = tookTrue;
  1583. while (true) {
  1584. CondTmp = CondTmp->IgnoreParenCasts();
  1585. switch (CondTmp->getStmtClass()) {
  1586. default:
  1587. break;
  1588. case Stmt::BinaryOperatorClass:
  1589. if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
  1590. tookTrueTmp, BRC, R, N))
  1591. return P;
  1592. break;
  1593. case Stmt::DeclRefExprClass:
  1594. if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
  1595. tookTrueTmp, BRC, R, N))
  1596. return P;
  1597. break;
  1598. case Stmt::UnaryOperatorClass: {
  1599. const auto *UO = cast<UnaryOperator>(CondTmp);
  1600. if (UO->getOpcode() == UO_LNot) {
  1601. tookTrueTmp = !tookTrueTmp;
  1602. CondTmp = UO->getSubExpr();
  1603. continue;
  1604. }
  1605. break;
  1606. }
  1607. }
  1608. break;
  1609. }
  1610. // Condition too complex to explain? Just say something so that the user
  1611. // knew we've made some path decision at this point.
  1612. const LocationContext *LCtx = N->getLocationContext();
  1613. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1614. if (!Loc.isValid() || !Loc.asLocation().isValid())
  1615. return nullptr;
  1616. return std::make_shared<PathDiagnosticEventPiece>(
  1617. Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
  1618. }
  1619. bool ConditionBRVisitor::patternMatch(const Expr *Ex,
  1620. const Expr *ParentEx,
  1621. raw_ostream &Out,
  1622. BugReporterContext &BRC,
  1623. BugReport &report,
  1624. const ExplodedNode *N,
  1625. Optional<bool> &prunable) {
  1626. const Expr *OriginalExpr = Ex;
  1627. Ex = Ex->IgnoreParenCasts();
  1628. // Use heuristics to determine if Ex is a macro expending to a literal and
  1629. // if so, use the macro's name.
  1630. SourceLocation LocStart = Ex->getLocStart();
  1631. SourceLocation LocEnd = Ex->getLocEnd();
  1632. if (LocStart.isMacroID() && LocEnd.isMacroID() &&
  1633. (isa<GNUNullExpr>(Ex) ||
  1634. isa<ObjCBoolLiteralExpr>(Ex) ||
  1635. isa<CXXBoolLiteralExpr>(Ex) ||
  1636. isa<IntegerLiteral>(Ex) ||
  1637. isa<FloatingLiteral>(Ex))) {
  1638. StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
  1639. BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
  1640. StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
  1641. BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
  1642. bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
  1643. bool partOfParentMacro = false;
  1644. if (ParentEx->getLocStart().isMacroID()) {
  1645. StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
  1646. ParentEx->getLocStart(), BRC.getSourceManager(),
  1647. BRC.getASTContext().getLangOpts());
  1648. partOfParentMacro = PName.equals(StartName);
  1649. }
  1650. if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
  1651. // Get the location of the macro name as written by the caller.
  1652. SourceLocation Loc = LocStart;
  1653. while (LocStart.isMacroID()) {
  1654. Loc = LocStart;
  1655. LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
  1656. }
  1657. StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
  1658. Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
  1659. // Return the macro name.
  1660. Out << MacroName;
  1661. return false;
  1662. }
  1663. }
  1664. if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
  1665. const bool quotes = isa<VarDecl>(DR->getDecl());
  1666. if (quotes) {
  1667. Out << '\'';
  1668. const LocationContext *LCtx = N->getLocationContext();
  1669. const ProgramState *state = N->getState().get();
  1670. if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
  1671. LCtx).getAsRegion()) {
  1672. if (report.isInteresting(R))
  1673. prunable = false;
  1674. else {
  1675. const ProgramState *state = N->getState().get();
  1676. SVal V = state->getSVal(R);
  1677. if (report.isInteresting(V))
  1678. prunable = false;
  1679. }
  1680. }
  1681. }
  1682. Out << DR->getDecl()->getDeclName().getAsString();
  1683. if (quotes)
  1684. Out << '\'';
  1685. return quotes;
  1686. }
  1687. if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
  1688. QualType OriginalTy = OriginalExpr->getType();
  1689. if (OriginalTy->isPointerType()) {
  1690. if (IL->getValue() == 0) {
  1691. Out << "null";
  1692. return false;
  1693. }
  1694. }
  1695. else if (OriginalTy->isObjCObjectPointerType()) {
  1696. if (IL->getValue() == 0) {
  1697. Out << "nil";
  1698. return false;
  1699. }
  1700. }
  1701. Out << IL->getValue();
  1702. return false;
  1703. }
  1704. return false;
  1705. }
  1706. std::shared_ptr<PathDiagnosticPiece>
  1707. ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
  1708. const bool tookTrue, BugReporterContext &BRC,
  1709. BugReport &R, const ExplodedNode *N) {
  1710. bool shouldInvert = false;
  1711. Optional<bool> shouldPrune;
  1712. SmallString<128> LhsString, RhsString;
  1713. {
  1714. llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
  1715. const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
  1716. BRC, R, N, shouldPrune);
  1717. const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
  1718. BRC, R, N, shouldPrune);
  1719. shouldInvert = !isVarLHS && isVarRHS;
  1720. }
  1721. BinaryOperator::Opcode Op = BExpr->getOpcode();
  1722. if (BinaryOperator::isAssignmentOp(Op)) {
  1723. // For assignment operators, all that we care about is that the LHS
  1724. // evaluates to "true" or "false".
  1725. return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
  1726. BRC, R, N);
  1727. }
  1728. // For non-assignment operations, we require that we can understand
  1729. // both the LHS and RHS.
  1730. if (LhsString.empty() || RhsString.empty() ||
  1731. !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
  1732. return nullptr;
  1733. // Should we invert the strings if the LHS is not a variable name?
  1734. SmallString<256> buf;
  1735. llvm::raw_svector_ostream Out(buf);
  1736. Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
  1737. // Do we need to invert the opcode?
  1738. if (shouldInvert)
  1739. switch (Op) {
  1740. default: break;
  1741. case BO_LT: Op = BO_GT; break;
  1742. case BO_GT: Op = BO_LT; break;
  1743. case BO_LE: Op = BO_GE; break;
  1744. case BO_GE: Op = BO_LE; break;
  1745. }
  1746. if (!tookTrue)
  1747. switch (Op) {
  1748. case BO_EQ: Op = BO_NE; break;
  1749. case BO_NE: Op = BO_EQ; break;
  1750. case BO_LT: Op = BO_GE; break;
  1751. case BO_GT: Op = BO_LE; break;
  1752. case BO_LE: Op = BO_GT; break;
  1753. case BO_GE: Op = BO_LT; break;
  1754. default:
  1755. return nullptr;
  1756. }
  1757. switch (Op) {
  1758. case BO_EQ:
  1759. Out << "equal to ";
  1760. break;
  1761. case BO_NE:
  1762. Out << "not equal to ";
  1763. break;
  1764. default:
  1765. Out << BinaryOperator::getOpcodeStr(Op) << ' ';
  1766. break;
  1767. }
  1768. Out << (shouldInvert ? LhsString : RhsString);
  1769. const LocationContext *LCtx = N->getLocationContext();
  1770. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1771. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  1772. if (shouldPrune.hasValue())
  1773. event->setPrunable(shouldPrune.getValue());
  1774. return event;
  1775. }
  1776. std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
  1777. StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
  1778. BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
  1779. // FIXME: If there's already a constraint tracker for this variable,
  1780. // we shouldn't emit anything here (c.f. the double note in
  1781. // test/Analysis/inlining/path-notes.c)
  1782. SmallString<256> buf;
  1783. llvm::raw_svector_ostream Out(buf);
  1784. Out << "Assuming " << LhsString << " is ";
  1785. QualType Ty = CondVarExpr->getType();
  1786. if (Ty->isPointerType())
  1787. Out << (tookTrue ? "not null" : "null");
  1788. else if (Ty->isObjCObjectPointerType())
  1789. Out << (tookTrue ? "not nil" : "nil");
  1790. else if (Ty->isBooleanType())
  1791. Out << (tookTrue ? "true" : "false");
  1792. else if (Ty->isIntegralOrEnumerationType())
  1793. Out << (tookTrue ? "non-zero" : "zero");
  1794. else
  1795. return nullptr;
  1796. const LocationContext *LCtx = N->getLocationContext();
  1797. PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
  1798. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  1799. if (const auto *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
  1800. if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1801. const ProgramState *state = N->getState().get();
  1802. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1803. if (report.isInteresting(R))
  1804. event->setPrunable(false);
  1805. }
  1806. }
  1807. }
  1808. return event;
  1809. }
  1810. std::shared_ptr<PathDiagnosticPiece>
  1811. ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
  1812. const bool tookTrue, BugReporterContext &BRC,
  1813. BugReport &report, const ExplodedNode *N) {
  1814. const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
  1815. if (!VD)
  1816. return nullptr;
  1817. SmallString<256> Buf;
  1818. llvm::raw_svector_ostream Out(Buf);
  1819. Out << "Assuming '" << VD->getDeclName() << "' is ";
  1820. QualType VDTy = VD->getType();
  1821. if (VDTy->isPointerType())
  1822. Out << (tookTrue ? "non-null" : "null");
  1823. else if (VDTy->isObjCObjectPointerType())
  1824. Out << (tookTrue ? "non-nil" : "nil");
  1825. else if (VDTy->isScalarType())
  1826. Out << (tookTrue ? "not equal to 0" : "0");
  1827. else
  1828. return nullptr;
  1829. const LocationContext *LCtx = N->getLocationContext();
  1830. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1831. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  1832. const ProgramState *state = N->getState().get();
  1833. if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
  1834. if (report.isInteresting(R))
  1835. event->setPrunable(false);
  1836. else {
  1837. SVal V = state->getSVal(R);
  1838. if (report.isInteresting(V))
  1839. event->setPrunable(false);
  1840. }
  1841. }
  1842. return std::move(event);
  1843. }
  1844. const char *const ConditionBRVisitor::GenericTrueMessage =
  1845. "Assuming the condition is true";
  1846. const char *const ConditionBRVisitor::GenericFalseMessage =
  1847. "Assuming the condition is false";
  1848. bool ConditionBRVisitor::isPieceMessageGeneric(
  1849. const PathDiagnosticPiece *Piece) {
  1850. return Piece->getString() == GenericTrueMessage ||
  1851. Piece->getString() == GenericFalseMessage;
  1852. }
  1853. void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
  1854. BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR) {
  1855. // Here we suppress false positives coming from system headers. This list is
  1856. // based on known issues.
  1857. AnalyzerOptions &Options = BRC.getAnalyzerOptions();
  1858. const Decl *D = N->getLocationContext()->getDecl();
  1859. if (AnalysisDeclContext::isInStdNamespace(D)) {
  1860. // Skip reports within the 'std' namespace. Although these can sometimes be
  1861. // the user's fault, we currently don't report them very well, and
  1862. // Note that this will not help for any other data structure libraries, like
  1863. // TR1, Boost, or llvm/ADT.
  1864. if (Options.shouldSuppressFromCXXStandardLibrary()) {
  1865. BR.markInvalid(getTag(), nullptr);
  1866. return;
  1867. } else {
  1868. // If the complete 'std' suppression is not enabled, suppress reports
  1869. // from the 'std' namespace that are known to produce false positives.
  1870. // The analyzer issues a false use-after-free when std::list::pop_front
  1871. // or std::list::pop_back are called multiple times because we cannot
  1872. // reason about the internal invariants of the data structure.
  1873. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  1874. const CXXRecordDecl *CD = MD->getParent();
  1875. if (CD->getName() == "list") {
  1876. BR.markInvalid(getTag(), nullptr);
  1877. return;
  1878. }
  1879. }
  1880. // The analyzer issues a false positive when the constructor of
  1881. // std::__independent_bits_engine from algorithms is used.
  1882. if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
  1883. const CXXRecordDecl *CD = MD->getParent();
  1884. if (CD->getName() == "__independent_bits_engine") {
  1885. BR.markInvalid(getTag(), nullptr);
  1886. return;
  1887. }
  1888. }
  1889. for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
  1890. LCtx = LCtx->getParent()) {
  1891. const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
  1892. if (!MD)
  1893. continue;
  1894. const CXXRecordDecl *CD = MD->getParent();
  1895. // The analyzer issues a false positive on
  1896. // std::basic_string<uint8_t> v; v.push_back(1);
  1897. // and
  1898. // std::u16string s; s += u'a';
  1899. // because we cannot reason about the internal invariants of the
  1900. // data structure.
  1901. if (CD->getName() == "basic_string") {
  1902. BR.markInvalid(getTag(), nullptr);
  1903. return;
  1904. }
  1905. // The analyzer issues a false positive on
  1906. // std::shared_ptr<int> p(new int(1)); p = nullptr;
  1907. // because it does not reason properly about temporary destructors.
  1908. if (CD->getName() == "shared_ptr") {
  1909. BR.markInvalid(getTag(), nullptr);
  1910. return;
  1911. }
  1912. }
  1913. }
  1914. }
  1915. // Skip reports within the sys/queue.h macros as we do not have the ability to
  1916. // reason about data structure shapes.
  1917. SourceManager &SM = BRC.getSourceManager();
  1918. FullSourceLoc Loc = BR.getLocation(SM).asLocation();
  1919. while (Loc.isMacroID()) {
  1920. Loc = Loc.getSpellingLoc();
  1921. if (SM.getFilename(Loc).endswith("sys/queue.h")) {
  1922. BR.markInvalid(getTag(), nullptr);
  1923. return;
  1924. }
  1925. }
  1926. }
  1927. std::shared_ptr<PathDiagnosticPiece>
  1928. UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
  1929. const ExplodedNode *PrevN,
  1930. BugReporterContext &BRC, BugReport &BR) {
  1931. ProgramStateRef State = N->getState();
  1932. ProgramPoint ProgLoc = N->getLocation();
  1933. // We are only interested in visiting CallEnter nodes.
  1934. Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
  1935. if (!CEnter)
  1936. return nullptr;
  1937. // Check if one of the arguments is the region the visitor is tracking.
  1938. CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
  1939. CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
  1940. unsigned Idx = 0;
  1941. ArrayRef<ParmVarDecl *> parms = Call->parameters();
  1942. for (const auto ParamDecl : parms) {
  1943. const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
  1944. ++Idx;
  1945. // Are we tracking the argument or its subregion?
  1946. if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
  1947. continue;
  1948. // Check the function parameter type.
  1949. assert(ParamDecl && "Formal parameter has no decl?");
  1950. QualType T = ParamDecl->getType();
  1951. if (!(T->isAnyPointerType() || T->isReferenceType())) {
  1952. // Function can only change the value passed in by address.
  1953. continue;
  1954. }
  1955. // If it is a const pointer value, the function does not intend to
  1956. // change the value.
  1957. if (T->getPointeeType().isConstQualified())
  1958. continue;
  1959. // Mark the call site (LocationContext) as interesting if the value of the
  1960. // argument is undefined or '0'/'NULL'.
  1961. SVal BoundVal = State->getSVal(R);
  1962. if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
  1963. BR.markInteresting(CEnter->getCalleeContext());
  1964. return nullptr;
  1965. }
  1966. }
  1967. return nullptr;
  1968. }
  1969. std::shared_ptr<PathDiagnosticPiece>
  1970. CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
  1971. const ExplodedNode *Pred,
  1972. BugReporterContext &BRC, BugReport &BR) {
  1973. if (Satisfied)
  1974. return nullptr;
  1975. const auto Edge = Succ->getLocation().getAs<BlockEdge>();
  1976. if (!Edge.hasValue())
  1977. return nullptr;
  1978. auto Tag = Edge->getTag();
  1979. if (!Tag)
  1980. return nullptr;
  1981. if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
  1982. return nullptr;
  1983. Satisfied = true;
  1984. const auto *Met =
  1985. dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
  1986. assert(Met && "Not a C++ method.");
  1987. assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
  1988. "Not a copy/move assignment operator.");
  1989. const auto *LCtx = Edge->getLocationContext();
  1990. const auto &State = Succ->getState();
  1991. auto &SVB = State->getStateManager().getSValBuilder();
  1992. const auto Param =
  1993. State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
  1994. const auto This =
  1995. State->getSVal(SVB.getCXXThis(Met, LCtx->getStackFrame()));
  1996. auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
  1997. if (!L.isValid() || !L.asLocation().isValid())
  1998. return nullptr;
  1999. SmallString<256> Buf;
  2000. llvm::raw_svector_ostream Out(Buf);
  2001. Out << "Assuming " << Met->getParamDecl(0)->getName() <<
  2002. ((Param == This) ? " == " : " != ") << "*this";
  2003. auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
  2004. Piece->addRange(Met->getSourceRange());
  2005. return std::move(Piece);
  2006. }
  2007. std::shared_ptr<PathDiagnosticPiece>
  2008. TaintBugVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN,
  2009. BugReporterContext &BRC, BugReport &BR) {
  2010. // Find the ExplodedNode where the taint was first introduced
  2011. if (!N->getState()->isTainted(V) || PrevN->getState()->isTainted(V))
  2012. return nullptr;
  2013. const Stmt *S = PathDiagnosticLocation::getStmt(N);
  2014. if (!S)
  2015. return nullptr;
  2016. const LocationContext *NCtx = N->getLocationContext();
  2017. PathDiagnosticLocation L =
  2018. PathDiagnosticLocation::createBegin(S, BRC.getSourceManager(), NCtx);
  2019. if (!L.isValid() || !L.asLocation().isValid())
  2020. return nullptr;
  2021. return std::make_shared<PathDiagnosticEventPiece>(L, "Taint originated here");
  2022. }
  2023. static bool
  2024. areConstraintsUnfeasible(BugReporterContext &BRC,
  2025. const llvm::SmallVector<ConstraintRangeTy, 32> &Cs) {
  2026. // Create a refutation manager
  2027. std::unique_ptr<ConstraintManager> RefutationMgr = CreateZ3ConstraintManager(
  2028. BRC.getStateManager(), BRC.getStateManager().getOwningEngine());
  2029. SMTConstraintManager *SMTRefutationMgr =
  2030. static_cast<SMTConstraintManager *>(RefutationMgr.get());
  2031. // Add constraints to the solver
  2032. for (const auto &C : Cs)
  2033. SMTRefutationMgr->addRangeConstraints(C);
  2034. // And check for satisfiability
  2035. return SMTRefutationMgr->isModelFeasible().isConstrainedFalse();
  2036. }
  2037. std::shared_ptr<PathDiagnosticPiece>
  2038. FalsePositiveRefutationBRVisitor::VisitNode(const ExplodedNode *N,
  2039. const ExplodedNode *PrevN,
  2040. BugReporterContext &BRC,
  2041. BugReport &BR) {
  2042. // Collect the constraint for the current state
  2043. const ConstraintRangeTy &CR = N->getState()->get<ConstraintRange>();
  2044. Constraints.push_back(CR);
  2045. // If there are no predecessor, we reached the root node. In this point,
  2046. // a new refutation manager will be created and the path will be checked
  2047. // for reachability
  2048. if (PrevN->pred_size() == 0 && areConstraintsUnfeasible(BRC, Constraints)) {
  2049. BR.markInvalid("Infeasible constraints", N->getLocationContext());
  2050. }
  2051. return nullptr;
  2052. }
  2053. void FalsePositiveRefutationBRVisitor::Profile(
  2054. llvm::FoldingSetNodeID &ID) const {
  2055. static int Tag = 0;
  2056. ID.AddPointer(&Tag);
  2057. }