BugReporterVisitors.cpp 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906
  1. //===- BugReporterVisitors.cpp - Helpers for reporting bugs ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines a set of BugReporter "visitors" which can be used to
  10. // enhance the diagnostics reported for a bug.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Decl.h"
  16. #include "clang/AST/DeclBase.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/ExprObjC.h"
  21. #include "clang/AST/Stmt.h"
  22. #include "clang/AST/Type.h"
  23. #include "clang/ASTMatchers/ASTMatchFinder.h"
  24. #include "clang/Analysis/Analyses/Dominators.h"
  25. #include "clang/Analysis/AnalysisDeclContext.h"
  26. #include "clang/Analysis/CFG.h"
  27. #include "clang/Analysis/CFGStmtMap.h"
  28. #include "clang/Analysis/PathDiagnostic.h"
  29. #include "clang/Analysis/ProgramPoint.h"
  30. #include "clang/Basic/IdentifierTable.h"
  31. #include "clang/Basic/LLVM.h"
  32. #include "clang/Basic/SourceLocation.h"
  33. #include "clang/Basic/SourceManager.h"
  34. #include "clang/Lex/Lexer.h"
  35. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  36. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  37. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  38. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  39. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  40. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  41. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  42. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  43. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
  44. #include "clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h"
  45. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  46. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  47. #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
  48. #include "llvm/ADT/ArrayRef.h"
  49. #include "llvm/ADT/None.h"
  50. #include "llvm/ADT/Optional.h"
  51. #include "llvm/ADT/STLExtras.h"
  52. #include "llvm/ADT/SmallPtrSet.h"
  53. #include "llvm/ADT/SmallString.h"
  54. #include "llvm/ADT/SmallVector.h"
  55. #include "llvm/ADT/StringExtras.h"
  56. #include "llvm/ADT/StringRef.h"
  57. #include "llvm/Support/Casting.h"
  58. #include "llvm/Support/ErrorHandling.h"
  59. #include "llvm/Support/raw_ostream.h"
  60. #include <cassert>
  61. #include <deque>
  62. #include <memory>
  63. #include <string>
  64. #include <utility>
  65. using namespace clang;
  66. using namespace ento;
  67. //===----------------------------------------------------------------------===//
  68. // Utility functions.
  69. //===----------------------------------------------------------------------===//
  70. static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
  71. if (B->isAdditiveOp() && B->getType()->isPointerType()) {
  72. if (B->getLHS()->getType()->isPointerType()) {
  73. return B->getLHS();
  74. } else if (B->getRHS()->getType()->isPointerType()) {
  75. return B->getRHS();
  76. }
  77. }
  78. return nullptr;
  79. }
  80. /// Given that expression S represents a pointer that would be dereferenced,
  81. /// try to find a sub-expression from which the pointer came from.
  82. /// This is used for tracking down origins of a null or undefined value:
  83. /// "this is null because that is null because that is null" etc.
  84. /// We wipe away field and element offsets because they merely add offsets.
  85. /// We also wipe away all casts except lvalue-to-rvalue casts, because the
  86. /// latter represent an actual pointer dereference; however, we remove
  87. /// the final lvalue-to-rvalue cast before returning from this function
  88. /// because it demonstrates more clearly from where the pointer rvalue was
  89. /// loaded. Examples:
  90. /// x->y.z ==> x (lvalue)
  91. /// foo()->y.z ==> foo() (rvalue)
  92. const Expr *bugreporter::getDerefExpr(const Stmt *S) {
  93. const auto *E = dyn_cast<Expr>(S);
  94. if (!E)
  95. return nullptr;
  96. while (true) {
  97. if (const auto *CE = dyn_cast<CastExpr>(E)) {
  98. if (CE->getCastKind() == CK_LValueToRValue) {
  99. // This cast represents the load we're looking for.
  100. break;
  101. }
  102. E = CE->getSubExpr();
  103. } else if (const auto *B = dyn_cast<BinaryOperator>(E)) {
  104. // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
  105. if (const Expr *Inner = peelOffPointerArithmetic(B)) {
  106. E = Inner;
  107. } else {
  108. // Probably more arithmetic can be pattern-matched here,
  109. // but for now give up.
  110. break;
  111. }
  112. } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
  113. if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf ||
  114. (U->isIncrementDecrementOp() && U->getType()->isPointerType())) {
  115. // Operators '*' and '&' don't actually mean anything.
  116. // We look at casts instead.
  117. E = U->getSubExpr();
  118. } else {
  119. // Probably more arithmetic can be pattern-matched here,
  120. // but for now give up.
  121. break;
  122. }
  123. }
  124. // Pattern match for a few useful cases: a[0], p->f, *p etc.
  125. else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
  126. E = ME->getBase();
  127. } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
  128. E = IvarRef->getBase();
  129. } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
  130. E = AE->getBase();
  131. } else if (const auto *PE = dyn_cast<ParenExpr>(E)) {
  132. E = PE->getSubExpr();
  133. } else if (const auto *FE = dyn_cast<FullExpr>(E)) {
  134. E = FE->getSubExpr();
  135. } else {
  136. // Other arbitrary stuff.
  137. break;
  138. }
  139. }
  140. // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
  141. // deeper into the sub-expression. This way we return the lvalue from which
  142. // our pointer rvalue was loaded.
  143. if (const auto *CE = dyn_cast<ImplicitCastExpr>(E))
  144. if (CE->getCastKind() == CK_LValueToRValue)
  145. E = CE->getSubExpr();
  146. return E;
  147. }
  148. /// Comparing internal representations of symbolic values (via
  149. /// SVal::operator==()) is a valid way to check if the value was updated,
  150. /// unless it's a LazyCompoundVal that may have a different internal
  151. /// representation every time it is loaded from the state. In this function we
  152. /// do an approximate comparison for lazy compound values, checking that they
  153. /// are the immediate snapshots of the tracked region's bindings within the
  154. /// node's respective states but not really checking that these snapshots
  155. /// actually contain the same set of bindings.
  156. static bool hasVisibleUpdate(const ExplodedNode *LeftNode, SVal LeftVal,
  157. const ExplodedNode *RightNode, SVal RightVal) {
  158. if (LeftVal == RightVal)
  159. return true;
  160. const auto LLCV = LeftVal.getAs<nonloc::LazyCompoundVal>();
  161. if (!LLCV)
  162. return false;
  163. const auto RLCV = RightVal.getAs<nonloc::LazyCompoundVal>();
  164. if (!RLCV)
  165. return false;
  166. return LLCV->getRegion() == RLCV->getRegion() &&
  167. LLCV->getStore() == LeftNode->getState()->getStore() &&
  168. RLCV->getStore() == RightNode->getState()->getStore();
  169. }
  170. static Optional<SVal> getSValForVar(const Expr *CondVarExpr,
  171. const ExplodedNode *N) {
  172. ProgramStateRef State = N->getState();
  173. const LocationContext *LCtx = N->getLocationContext();
  174. assert(CondVarExpr);
  175. CondVarExpr = CondVarExpr->IgnoreImpCasts();
  176. // The declaration of the value may rely on a pointer so take its l-value.
  177. // FIXME: As seen in VisitCommonDeclRefExpr, sometimes DeclRefExpr may
  178. // evaluate to a FieldRegion when it refers to a declaration of a lambda
  179. // capture variable. We most likely need to duplicate that logic here.
  180. if (const auto *DRE = dyn_cast<DeclRefExpr>(CondVarExpr))
  181. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  182. return State->getSVal(State->getLValue(VD, LCtx));
  183. if (const auto *ME = dyn_cast<MemberExpr>(CondVarExpr))
  184. if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
  185. if (auto FieldL = State->getSVal(ME, LCtx).getAs<Loc>())
  186. return State->getRawSVal(*FieldL, FD->getType());
  187. return None;
  188. }
  189. static Optional<const llvm::APSInt *>
  190. getConcreteIntegerValue(const Expr *CondVarExpr, const ExplodedNode *N) {
  191. if (Optional<SVal> V = getSValForVar(CondVarExpr, N))
  192. if (auto CI = V->getAs<nonloc::ConcreteInt>())
  193. return &CI->getValue();
  194. return None;
  195. }
  196. static bool isVarAnInterestingCondition(const Expr *CondVarExpr,
  197. const ExplodedNode *N,
  198. const PathSensitiveBugReport *B) {
  199. // Even if this condition is marked as interesting, it isn't *that*
  200. // interesting if it didn't happen in a nested stackframe, the user could just
  201. // follow the arrows.
  202. if (!B->getErrorNode()->getStackFrame()->isParentOf(N->getStackFrame()))
  203. return false;
  204. if (Optional<SVal> V = getSValForVar(CondVarExpr, N))
  205. if (Optional<bugreporter::TrackingKind> K = B->getInterestingnessKind(*V))
  206. return *K == bugreporter::TrackingKind::Condition;
  207. return false;
  208. }
  209. static bool isInterestingExpr(const Expr *E, const ExplodedNode *N,
  210. const PathSensitiveBugReport *B) {
  211. if (Optional<SVal> V = getSValForVar(E, N))
  212. return B->getInterestingnessKind(*V).hasValue();
  213. return false;
  214. }
  215. /// \return name of the macro inside the location \p Loc.
  216. static StringRef getMacroName(SourceLocation Loc,
  217. BugReporterContext &BRC) {
  218. return Lexer::getImmediateMacroName(
  219. Loc,
  220. BRC.getSourceManager(),
  221. BRC.getASTContext().getLangOpts());
  222. }
  223. /// \return Whether given spelling location corresponds to an expansion
  224. /// of a function-like macro.
  225. static bool isFunctionMacroExpansion(SourceLocation Loc,
  226. const SourceManager &SM) {
  227. if (!Loc.isMacroID())
  228. return false;
  229. while (SM.isMacroArgExpansion(Loc))
  230. Loc = SM.getImmediateExpansionRange(Loc).getBegin();
  231. std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
  232. SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
  233. const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
  234. return EInfo.isFunctionMacroExpansion();
  235. }
  236. /// \return Whether \c RegionOfInterest was modified at \p N,
  237. /// where \p ValueAfter is \c RegionOfInterest's value at the end of the
  238. /// stack frame.
  239. static bool wasRegionOfInterestModifiedAt(const SubRegion *RegionOfInterest,
  240. const ExplodedNode *N,
  241. SVal ValueAfter) {
  242. ProgramStateRef State = N->getState();
  243. ProgramStateManager &Mgr = N->getState()->getStateManager();
  244. if (!N->getLocationAs<PostStore>() && !N->getLocationAs<PostInitializer>() &&
  245. !N->getLocationAs<PostStmt>())
  246. return false;
  247. // Writing into region of interest.
  248. if (auto PS = N->getLocationAs<PostStmt>())
  249. if (auto *BO = PS->getStmtAs<BinaryOperator>())
  250. if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
  251. N->getSVal(BO->getLHS()).getAsRegion()))
  252. return true;
  253. // SVal after the state is possibly different.
  254. SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
  255. if (!Mgr.getSValBuilder()
  256. .areEqual(State, ValueAtN, ValueAfter)
  257. .isConstrainedTrue() &&
  258. (!ValueAtN.isUndef() || !ValueAfter.isUndef()))
  259. return true;
  260. return false;
  261. }
  262. //===----------------------------------------------------------------------===//
  263. // Implementation of BugReporterVisitor.
  264. //===----------------------------------------------------------------------===//
  265. PathDiagnosticPieceRef BugReporterVisitor::getEndPath(BugReporterContext &,
  266. const ExplodedNode *,
  267. PathSensitiveBugReport &) {
  268. return nullptr;
  269. }
  270. void BugReporterVisitor::finalizeVisitor(BugReporterContext &,
  271. const ExplodedNode *,
  272. PathSensitiveBugReport &) {}
  273. PathDiagnosticPieceRef
  274. BugReporterVisitor::getDefaultEndPath(const BugReporterContext &BRC,
  275. const ExplodedNode *EndPathNode,
  276. const PathSensitiveBugReport &BR) {
  277. PathDiagnosticLocation L = BR.getLocation();
  278. const auto &Ranges = BR.getRanges();
  279. // Only add the statement itself as a range if we didn't specify any
  280. // special ranges for this report.
  281. auto P = std::make_shared<PathDiagnosticEventPiece>(
  282. L, BR.getDescription(), Ranges.begin() == Ranges.end());
  283. for (SourceRange Range : Ranges)
  284. P->addRange(Range);
  285. return P;
  286. }
  287. //===----------------------------------------------------------------------===//
  288. // Implementation of NoStoreFuncVisitor.
  289. //===----------------------------------------------------------------------===//
  290. namespace {
  291. /// Put a diagnostic on return statement of all inlined functions
  292. /// for which the region of interest \p RegionOfInterest was passed into,
  293. /// but not written inside, and it has caused an undefined read or a null
  294. /// pointer dereference outside.
  295. class NoStoreFuncVisitor final : public BugReporterVisitor {
  296. const SubRegion *RegionOfInterest;
  297. MemRegionManager &MmrMgr;
  298. const SourceManager &SM;
  299. const PrintingPolicy &PP;
  300. bugreporter::TrackingKind TKind;
  301. /// Recursion limit for dereferencing fields when looking for the
  302. /// region of interest.
  303. /// The limit of two indicates that we will dereference fields only once.
  304. static const unsigned DEREFERENCE_LIMIT = 2;
  305. /// Frames writing into \c RegionOfInterest.
  306. /// This visitor generates a note only if a function does not write into
  307. /// a region of interest. This information is not immediately available
  308. /// by looking at the node associated with the exit from the function
  309. /// (usually the return statement). To avoid recomputing the same information
  310. /// many times (going up the path for each node and checking whether the
  311. /// region was written into) we instead lazily compute the
  312. /// stack frames along the path which write into the region of interest.
  313. llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion;
  314. llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated;
  315. using RegionVector = SmallVector<const MemRegion *, 5>;
  316. public:
  317. NoStoreFuncVisitor(const SubRegion *R, bugreporter::TrackingKind TKind)
  318. : RegionOfInterest(R), MmrMgr(*R->getMemRegionManager()),
  319. SM(MmrMgr.getContext().getSourceManager()),
  320. PP(MmrMgr.getContext().getPrintingPolicy()), TKind(TKind) {}
  321. void Profile(llvm::FoldingSetNodeID &ID) const override {
  322. static int Tag = 0;
  323. ID.AddPointer(&Tag);
  324. ID.AddPointer(RegionOfInterest);
  325. }
  326. void *getTag() const {
  327. static int Tag = 0;
  328. return static_cast<void *>(&Tag);
  329. }
  330. PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
  331. BugReporterContext &BR,
  332. PathSensitiveBugReport &R) override;
  333. private:
  334. /// Attempts to find the region of interest in a given record decl,
  335. /// by either following the base classes or fields.
  336. /// Dereferences fields up to a given recursion limit.
  337. /// Note that \p Vec is passed by value, leading to quadratic copying cost,
  338. /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
  339. /// \return A chain fields leading to the region of interest or None.
  340. const Optional<RegionVector>
  341. findRegionOfInterestInRecord(const RecordDecl *RD, ProgramStateRef State,
  342. const MemRegion *R, const RegionVector &Vec = {},
  343. int depth = 0);
  344. /// Check and lazily calculate whether the region of interest is
  345. /// modified in the stack frame to which \p N belongs.
  346. /// The calculation is cached in FramesModifyingRegion.
  347. bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) {
  348. const LocationContext *Ctx = N->getLocationContext();
  349. const StackFrameContext *SCtx = Ctx->getStackFrame();
  350. if (!FramesModifyingCalculated.count(SCtx))
  351. findModifyingFrames(N);
  352. return FramesModifyingRegion.count(SCtx);
  353. }
  354. /// Write to \c FramesModifyingRegion all stack frames along
  355. /// the path in the current stack frame which modify \c RegionOfInterest.
  356. void findModifyingFrames(const ExplodedNode *N);
  357. /// Consume the information on the no-store stack frame in order to
  358. /// either emit a note or suppress the report enirely.
  359. /// \return Diagnostics piece for region not modified in the current function,
  360. /// if it decides to emit one.
  361. PathDiagnosticPieceRef
  362. maybeEmitNote(PathSensitiveBugReport &R, const CallEvent &Call,
  363. const ExplodedNode *N, const RegionVector &FieldChain,
  364. const MemRegion *MatchedRegion, StringRef FirstElement,
  365. bool FirstIsReferenceType, unsigned IndirectionLevel);
  366. /// Pretty-print region \p MatchedRegion to \p os.
  367. /// \return Whether printing succeeded.
  368. bool prettyPrintRegionName(StringRef FirstElement, bool FirstIsReferenceType,
  369. const MemRegion *MatchedRegion,
  370. const RegionVector &FieldChain,
  371. int IndirectionLevel,
  372. llvm::raw_svector_ostream &os);
  373. /// Print first item in the chain, return new separator.
  374. static StringRef prettyPrintFirstElement(StringRef FirstElement,
  375. bool MoreItemsExpected,
  376. int IndirectionLevel,
  377. llvm::raw_svector_ostream &os);
  378. };
  379. } // end of anonymous namespace
  380. /// \return Whether the method declaration \p Parent
  381. /// syntactically has a binary operation writing into the ivar \p Ivar.
  382. static bool potentiallyWritesIntoIvar(const Decl *Parent,
  383. const ObjCIvarDecl *Ivar) {
  384. using namespace ast_matchers;
  385. const char *IvarBind = "Ivar";
  386. if (!Parent || !Parent->hasBody())
  387. return false;
  388. StatementMatcher WriteIntoIvarM = binaryOperator(
  389. hasOperatorName("="),
  390. hasLHS(ignoringParenImpCasts(
  391. objcIvarRefExpr(hasDeclaration(equalsNode(Ivar))).bind(IvarBind))));
  392. StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
  393. auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
  394. for (BoundNodes &Match : Matches) {
  395. auto IvarRef = Match.getNodeAs<ObjCIvarRefExpr>(IvarBind);
  396. if (IvarRef->isFreeIvar())
  397. return true;
  398. const Expr *Base = IvarRef->getBase();
  399. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Base))
  400. Base = ICE->getSubExpr();
  401. if (const auto *DRE = dyn_cast<DeclRefExpr>(Base))
  402. if (const auto *ID = dyn_cast<ImplicitParamDecl>(DRE->getDecl()))
  403. if (ID->getParameterKind() == ImplicitParamDecl::ObjCSelf)
  404. return true;
  405. return false;
  406. }
  407. return false;
  408. }
  409. /// Get parameters associated with runtime definition in order
  410. /// to get the correct parameter name.
  411. static ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) {
  412. // Use runtime definition, if available.
  413. RuntimeDefinition RD = Call->getRuntimeDefinition();
  414. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl()))
  415. return FD->parameters();
  416. if (const auto *MD = dyn_cast_or_null<ObjCMethodDecl>(RD.getDecl()))
  417. return MD->parameters();
  418. return Call->parameters();
  419. }
  420. /// \return whether \p Ty points to a const type, or is a const reference.
  421. static bool isPointerToConst(QualType Ty) {
  422. return !Ty->getPointeeType().isNull() &&
  423. Ty->getPointeeType().getCanonicalType().isConstQualified();
  424. }
  425. /// Attempts to find the region of interest in a given CXX decl,
  426. /// by either following the base classes or fields.
  427. /// Dereferences fields up to a given recursion limit.
  428. /// Note that \p Vec is passed by value, leading to quadratic copying cost,
  429. /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
  430. /// \return A chain fields leading to the region of interest or None.
  431. const Optional<NoStoreFuncVisitor::RegionVector>
  432. NoStoreFuncVisitor::findRegionOfInterestInRecord(
  433. const RecordDecl *RD, ProgramStateRef State, const MemRegion *R,
  434. const NoStoreFuncVisitor::RegionVector &Vec /* = {} */,
  435. int depth /* = 0 */) {
  436. if (depth == DEREFERENCE_LIMIT) // Limit the recursion depth.
  437. return None;
  438. if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
  439. if (!RDX->hasDefinition())
  440. return None;
  441. // Recursively examine the base classes.
  442. // Note that following base classes does not increase the recursion depth.
  443. if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
  444. for (const auto II : RDX->bases())
  445. if (const RecordDecl *RRD = II.getType()->getAsRecordDecl())
  446. if (Optional<RegionVector> Out =
  447. findRegionOfInterestInRecord(RRD, State, R, Vec, depth))
  448. return Out;
  449. for (const FieldDecl *I : RD->fields()) {
  450. QualType FT = I->getType();
  451. const FieldRegion *FR = MmrMgr.getFieldRegion(I, cast<SubRegion>(R));
  452. const SVal V = State->getSVal(FR);
  453. const MemRegion *VR = V.getAsRegion();
  454. RegionVector VecF = Vec;
  455. VecF.push_back(FR);
  456. if (RegionOfInterest == VR)
  457. return VecF;
  458. if (const RecordDecl *RRD = FT->getAsRecordDecl())
  459. if (auto Out =
  460. findRegionOfInterestInRecord(RRD, State, FR, VecF, depth + 1))
  461. return Out;
  462. QualType PT = FT->getPointeeType();
  463. if (PT.isNull() || PT->isVoidType() || !VR)
  464. continue;
  465. if (const RecordDecl *RRD = PT->getAsRecordDecl())
  466. if (Optional<RegionVector> Out =
  467. findRegionOfInterestInRecord(RRD, State, VR, VecF, depth + 1))
  468. return Out;
  469. }
  470. return None;
  471. }
  472. PathDiagnosticPieceRef
  473. NoStoreFuncVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BR,
  474. PathSensitiveBugReport &R) {
  475. const LocationContext *Ctx = N->getLocationContext();
  476. const StackFrameContext *SCtx = Ctx->getStackFrame();
  477. ProgramStateRef State = N->getState();
  478. auto CallExitLoc = N->getLocationAs<CallExitBegin>();
  479. // No diagnostic if region was modified inside the frame.
  480. if (!CallExitLoc || isRegionOfInterestModifiedInFrame(N))
  481. return nullptr;
  482. CallEventRef<> Call =
  483. BR.getStateManager().getCallEventManager().getCaller(SCtx, State);
  484. // Region of interest corresponds to an IVar, exiting a method
  485. // which could have written into that IVar, but did not.
  486. if (const auto *MC = dyn_cast<ObjCMethodCall>(Call)) {
  487. if (const auto *IvarR = dyn_cast<ObjCIvarRegion>(RegionOfInterest)) {
  488. const MemRegion *SelfRegion = MC->getReceiverSVal().getAsRegion();
  489. if (RegionOfInterest->isSubRegionOf(SelfRegion) &&
  490. potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
  491. IvarR->getDecl()))
  492. return maybeEmitNote(R, *Call, N, {}, SelfRegion, "self",
  493. /*FirstIsReferenceType=*/false, 1);
  494. }
  495. }
  496. if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
  497. const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion();
  498. if (RegionOfInterest->isSubRegionOf(ThisR) &&
  499. !CCall->getDecl()->isImplicit())
  500. return maybeEmitNote(R, *Call, N, {}, ThisR, "this",
  501. /*FirstIsReferenceType=*/false, 1);
  502. // Do not generate diagnostics for not modified parameters in
  503. // constructors.
  504. return nullptr;
  505. }
  506. ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call);
  507. for (unsigned I = 0; I < Call->getNumArgs() && I < parameters.size(); ++I) {
  508. const ParmVarDecl *PVD = parameters[I];
  509. SVal V = Call->getArgSVal(I);
  510. bool ParamIsReferenceType = PVD->getType()->isReferenceType();
  511. std::string ParamName = PVD->getNameAsString();
  512. int IndirectionLevel = 1;
  513. QualType T = PVD->getType();
  514. while (const MemRegion *MR = V.getAsRegion()) {
  515. if (RegionOfInterest->isSubRegionOf(MR) && !isPointerToConst(T))
  516. return maybeEmitNote(R, *Call, N, {}, MR, ParamName,
  517. ParamIsReferenceType, IndirectionLevel);
  518. QualType PT = T->getPointeeType();
  519. if (PT.isNull() || PT->isVoidType())
  520. break;
  521. if (const RecordDecl *RD = PT->getAsRecordDecl())
  522. if (Optional<RegionVector> P =
  523. findRegionOfInterestInRecord(RD, State, MR))
  524. return maybeEmitNote(R, *Call, N, *P, RegionOfInterest, ParamName,
  525. ParamIsReferenceType, IndirectionLevel);
  526. V = State->getSVal(MR, PT);
  527. T = PT;
  528. IndirectionLevel++;
  529. }
  530. }
  531. return nullptr;
  532. }
  533. void NoStoreFuncVisitor::findModifyingFrames(const ExplodedNode *N) {
  534. assert(N->getLocationAs<CallExitBegin>());
  535. ProgramStateRef LastReturnState = N->getState();
  536. SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
  537. const LocationContext *Ctx = N->getLocationContext();
  538. const StackFrameContext *OriginalSCtx = Ctx->getStackFrame();
  539. do {
  540. ProgramStateRef State = N->getState();
  541. auto CallExitLoc = N->getLocationAs<CallExitBegin>();
  542. if (CallExitLoc) {
  543. LastReturnState = State;
  544. ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
  545. }
  546. FramesModifyingCalculated.insert(N->getLocationContext()->getStackFrame());
  547. if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtReturn)) {
  548. const StackFrameContext *SCtx = N->getStackFrame();
  549. while (!SCtx->inTopFrame()) {
  550. auto p = FramesModifyingRegion.insert(SCtx);
  551. if (!p.second)
  552. break; // Frame and all its parents already inserted.
  553. SCtx = SCtx->getParent()->getStackFrame();
  554. }
  555. }
  556. // Stop calculation at the call to the current function.
  557. if (auto CE = N->getLocationAs<CallEnter>())
  558. if (CE->getCalleeContext() == OriginalSCtx)
  559. break;
  560. N = N->getFirstPred();
  561. } while (N);
  562. }
  563. static llvm::StringLiteral WillBeUsedForACondition =
  564. ", which participates in a condition later";
  565. PathDiagnosticPieceRef NoStoreFuncVisitor::maybeEmitNote(
  566. PathSensitiveBugReport &R, const CallEvent &Call, const ExplodedNode *N,
  567. const RegionVector &FieldChain, const MemRegion *MatchedRegion,
  568. StringRef FirstElement, bool FirstIsReferenceType,
  569. unsigned IndirectionLevel) {
  570. // Optimistically suppress uninitialized value bugs that result
  571. // from system headers having a chance to initialize the value
  572. // but failing to do so. It's too unlikely a system header's fault.
  573. // It's much more likely a situation in which the function has a failure
  574. // mode that the user decided not to check. If we want to hunt such
  575. // omitted checks, we should provide an explicit function-specific note
  576. // describing the precondition under which the function isn't supposed to
  577. // initialize its out-parameter, and additionally check that such
  578. // precondition can actually be fulfilled on the current path.
  579. if (Call.isInSystemHeader()) {
  580. // We make an exception for system header functions that have no branches.
  581. // Such functions unconditionally fail to initialize the variable.
  582. // If they call other functions that have more paths within them,
  583. // this suppression would still apply when we visit these inner functions.
  584. // One common example of a standard function that doesn't ever initialize
  585. // its out parameter is operator placement new; it's up to the follow-up
  586. // constructor (if any) to initialize the memory.
  587. if (!N->getStackFrame()->getCFG()->isLinear())
  588. R.markInvalid(getTag(), nullptr);
  589. return nullptr;
  590. }
  591. PathDiagnosticLocation L =
  592. PathDiagnosticLocation::create(N->getLocation(), SM);
  593. // For now this shouldn't trigger, but once it does (as we add more
  594. // functions to the body farm), we'll need to decide if these reports
  595. // are worth suppressing as well.
  596. if (!L.hasValidLocation())
  597. return nullptr;
  598. SmallString<256> sbuf;
  599. llvm::raw_svector_ostream os(sbuf);
  600. os << "Returning without writing to '";
  601. // Do not generate the note if failed to pretty-print.
  602. if (!prettyPrintRegionName(FirstElement, FirstIsReferenceType, MatchedRegion,
  603. FieldChain, IndirectionLevel, os))
  604. return nullptr;
  605. os << "'";
  606. if (TKind == bugreporter::TrackingKind::Condition)
  607. os << WillBeUsedForACondition;
  608. return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
  609. }
  610. bool NoStoreFuncVisitor::prettyPrintRegionName(StringRef FirstElement,
  611. bool FirstIsReferenceType,
  612. const MemRegion *MatchedRegion,
  613. const RegionVector &FieldChain,
  614. int IndirectionLevel,
  615. llvm::raw_svector_ostream &os) {
  616. if (FirstIsReferenceType)
  617. IndirectionLevel--;
  618. RegionVector RegionSequence;
  619. // Add the regions in the reverse order, then reverse the resulting array.
  620. assert(RegionOfInterest->isSubRegionOf(MatchedRegion));
  621. const MemRegion *R = RegionOfInterest;
  622. while (R != MatchedRegion) {
  623. RegionSequence.push_back(R);
  624. R = cast<SubRegion>(R)->getSuperRegion();
  625. }
  626. std::reverse(RegionSequence.begin(), RegionSequence.end());
  627. RegionSequence.append(FieldChain.begin(), FieldChain.end());
  628. StringRef Sep;
  629. for (const MemRegion *R : RegionSequence) {
  630. // Just keep going up to the base region.
  631. // Element regions may appear due to casts.
  632. if (isa<CXXBaseObjectRegion>(R) || isa<CXXTempObjectRegion>(R))
  633. continue;
  634. if (Sep.empty())
  635. Sep = prettyPrintFirstElement(FirstElement,
  636. /*MoreItemsExpected=*/true,
  637. IndirectionLevel, os);
  638. os << Sep;
  639. // Can only reasonably pretty-print DeclRegions.
  640. if (!isa<DeclRegion>(R))
  641. return false;
  642. const auto *DR = cast<DeclRegion>(R);
  643. Sep = DR->getValueType()->isAnyPointerType() ? "->" : ".";
  644. DR->getDecl()->getDeclName().print(os, PP);
  645. }
  646. if (Sep.empty())
  647. prettyPrintFirstElement(FirstElement,
  648. /*MoreItemsExpected=*/false, IndirectionLevel, os);
  649. return true;
  650. }
  651. StringRef NoStoreFuncVisitor::prettyPrintFirstElement(
  652. StringRef FirstElement, bool MoreItemsExpected, int IndirectionLevel,
  653. llvm::raw_svector_ostream &os) {
  654. StringRef Out = ".";
  655. if (IndirectionLevel > 0 && MoreItemsExpected) {
  656. IndirectionLevel--;
  657. Out = "->";
  658. }
  659. if (IndirectionLevel > 0 && MoreItemsExpected)
  660. os << "(";
  661. for (int i = 0; i < IndirectionLevel; i++)
  662. os << "*";
  663. os << FirstElement;
  664. if (IndirectionLevel > 0 && MoreItemsExpected)
  665. os << ")";
  666. return Out;
  667. }
  668. //===----------------------------------------------------------------------===//
  669. // Implementation of MacroNullReturnSuppressionVisitor.
  670. //===----------------------------------------------------------------------===//
  671. namespace {
  672. /// Suppress null-pointer-dereference bugs where dereferenced null was returned
  673. /// the macro.
  674. class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor {
  675. const SubRegion *RegionOfInterest;
  676. const SVal ValueAtDereference;
  677. // Do not invalidate the reports where the value was modified
  678. // after it got assigned to from the macro.
  679. bool WasModified = false;
  680. public:
  681. MacroNullReturnSuppressionVisitor(const SubRegion *R, const SVal V)
  682. : RegionOfInterest(R), ValueAtDereference(V) {}
  683. PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
  684. BugReporterContext &BRC,
  685. PathSensitiveBugReport &BR) override {
  686. if (WasModified)
  687. return nullptr;
  688. auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
  689. if (!BugPoint)
  690. return nullptr;
  691. const SourceManager &SMgr = BRC.getSourceManager();
  692. if (auto Loc = matchAssignment(N)) {
  693. if (isFunctionMacroExpansion(*Loc, SMgr)) {
  694. std::string MacroName = getMacroName(*Loc, BRC);
  695. SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
  696. if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
  697. BR.markInvalid(getTag(), MacroName.c_str());
  698. }
  699. }
  700. if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtDereference))
  701. WasModified = true;
  702. return nullptr;
  703. }
  704. static void addMacroVisitorIfNecessary(
  705. const ExplodedNode *N, const MemRegion *R,
  706. bool EnableNullFPSuppression, PathSensitiveBugReport &BR,
  707. const SVal V) {
  708. AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
  709. if (EnableNullFPSuppression &&
  710. Options.ShouldSuppressNullReturnPaths && V.getAs<Loc>())
  711. BR.addVisitor(std::make_unique<MacroNullReturnSuppressionVisitor>(
  712. R->getAs<SubRegion>(), V));
  713. }
  714. void* getTag() const {
  715. static int Tag = 0;
  716. return static_cast<void *>(&Tag);
  717. }
  718. void Profile(llvm::FoldingSetNodeID &ID) const override {
  719. ID.AddPointer(getTag());
  720. }
  721. private:
  722. /// \return Source location of right hand side of an assignment
  723. /// into \c RegionOfInterest, empty optional if none found.
  724. Optional<SourceLocation> matchAssignment(const ExplodedNode *N) {
  725. const Stmt *S = N->getStmtForDiagnostics();
  726. ProgramStateRef State = N->getState();
  727. auto *LCtx = N->getLocationContext();
  728. if (!S)
  729. return None;
  730. if (const auto *DS = dyn_cast<DeclStmt>(S)) {
  731. if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
  732. if (const Expr *RHS = VD->getInit())
  733. if (RegionOfInterest->isSubRegionOf(
  734. State->getLValue(VD, LCtx).getAsRegion()))
  735. return RHS->getBeginLoc();
  736. } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
  737. const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
  738. const Expr *RHS = BO->getRHS();
  739. if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
  740. return RHS->getBeginLoc();
  741. }
  742. }
  743. return None;
  744. }
  745. };
  746. } // end of anonymous namespace
  747. namespace {
  748. /// Emits an extra note at the return statement of an interesting stack frame.
  749. ///
  750. /// The returned value is marked as an interesting value, and if it's null,
  751. /// adds a visitor to track where it became null.
  752. ///
  753. /// This visitor is intended to be used when another visitor discovers that an
  754. /// interesting value comes from an inlined function call.
  755. class ReturnVisitor : public BugReporterVisitor {
  756. const StackFrameContext *CalleeSFC;
  757. enum {
  758. Initial,
  759. MaybeUnsuppress,
  760. Satisfied
  761. } Mode = Initial;
  762. bool EnableNullFPSuppression;
  763. bool ShouldInvalidate = true;
  764. AnalyzerOptions& Options;
  765. bugreporter::TrackingKind TKind;
  766. public:
  767. ReturnVisitor(const StackFrameContext *Frame, bool Suppressed,
  768. AnalyzerOptions &Options, bugreporter::TrackingKind TKind)
  769. : CalleeSFC(Frame), EnableNullFPSuppression(Suppressed),
  770. Options(Options), TKind(TKind) {}
  771. static void *getTag() {
  772. static int Tag = 0;
  773. return static_cast<void *>(&Tag);
  774. }
  775. void Profile(llvm::FoldingSetNodeID &ID) const override {
  776. ID.AddPointer(ReturnVisitor::getTag());
  777. ID.AddPointer(CalleeSFC);
  778. ID.AddBoolean(EnableNullFPSuppression);
  779. }
  780. /// Adds a ReturnVisitor if the given statement represents a call that was
  781. /// inlined.
  782. ///
  783. /// This will search back through the ExplodedGraph, starting from the given
  784. /// node, looking for when the given statement was processed. If it turns out
  785. /// the statement is a call that was inlined, we add the visitor to the
  786. /// bug report, so it can print a note later.
  787. static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
  788. PathSensitiveBugReport &BR,
  789. bool InEnableNullFPSuppression,
  790. bugreporter::TrackingKind TKind) {
  791. if (!CallEvent::isCallStmt(S))
  792. return;
  793. // First, find when we processed the statement.
  794. // If we work with a 'CXXNewExpr' that is going to be purged away before
  795. // its call take place. We would catch that purge in the last condition
  796. // as a 'StmtPoint' so we have to bypass it.
  797. const bool BypassCXXNewExprEval = isa<CXXNewExpr>(S);
  798. // This is moving forward when we enter into another context.
  799. const StackFrameContext *CurrentSFC = Node->getStackFrame();
  800. do {
  801. // If that is satisfied we found our statement as an inlined call.
  802. if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
  803. if (CEE->getCalleeContext()->getCallSite() == S)
  804. break;
  805. // Try to move forward to the end of the call-chain.
  806. Node = Node->getFirstPred();
  807. if (!Node)
  808. break;
  809. const StackFrameContext *PredSFC = Node->getStackFrame();
  810. // If that is satisfied we found our statement.
  811. // FIXME: This code currently bypasses the call site for the
  812. // conservatively evaluated allocator.
  813. if (!BypassCXXNewExprEval)
  814. if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
  815. // See if we do not enter into another context.
  816. if (SP->getStmt() == S && CurrentSFC == PredSFC)
  817. break;
  818. CurrentSFC = PredSFC;
  819. } while (Node->getStackFrame() == CurrentSFC);
  820. // Next, step over any post-statement checks.
  821. while (Node && Node->getLocation().getAs<PostStmt>())
  822. Node = Node->getFirstPred();
  823. if (!Node)
  824. return;
  825. // Finally, see if we inlined the call.
  826. Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
  827. if (!CEE)
  828. return;
  829. const StackFrameContext *CalleeContext = CEE->getCalleeContext();
  830. if (CalleeContext->getCallSite() != S)
  831. return;
  832. // Check the return value.
  833. ProgramStateRef State = Node->getState();
  834. SVal RetVal = Node->getSVal(S);
  835. // Handle cases where a reference is returned and then immediately used.
  836. if (cast<Expr>(S)->isGLValue())
  837. if (Optional<Loc> LValue = RetVal.getAs<Loc>())
  838. RetVal = State->getSVal(*LValue);
  839. // See if the return value is NULL. If so, suppress the report.
  840. AnalyzerOptions &Options = State->getAnalysisManager().options;
  841. bool EnableNullFPSuppression = false;
  842. if (InEnableNullFPSuppression &&
  843. Options.ShouldSuppressNullReturnPaths)
  844. if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
  845. EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
  846. BR.addVisitor(std::make_unique<ReturnVisitor>(CalleeContext,
  847. EnableNullFPSuppression,
  848. Options, TKind));
  849. }
  850. PathDiagnosticPieceRef visitNodeInitial(const ExplodedNode *N,
  851. BugReporterContext &BRC,
  852. PathSensitiveBugReport &BR) {
  853. // Only print a message at the interesting return statement.
  854. if (N->getLocationContext() != CalleeSFC)
  855. return nullptr;
  856. Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
  857. if (!SP)
  858. return nullptr;
  859. const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
  860. if (!Ret)
  861. return nullptr;
  862. // Okay, we're at the right return statement, but do we have the return
  863. // value available?
  864. ProgramStateRef State = N->getState();
  865. SVal V = State->getSVal(Ret, CalleeSFC);
  866. if (V.isUnknownOrUndef())
  867. return nullptr;
  868. // Don't print any more notes after this one.
  869. Mode = Satisfied;
  870. const Expr *RetE = Ret->getRetValue();
  871. assert(RetE && "Tracking a return value for a void function");
  872. // Handle cases where a reference is returned and then immediately used.
  873. Optional<Loc> LValue;
  874. if (RetE->isGLValue()) {
  875. if ((LValue = V.getAs<Loc>())) {
  876. SVal RValue = State->getRawSVal(*LValue, RetE->getType());
  877. if (RValue.getAs<DefinedSVal>())
  878. V = RValue;
  879. }
  880. }
  881. // Ignore aggregate rvalues.
  882. if (V.getAs<nonloc::LazyCompoundVal>() ||
  883. V.getAs<nonloc::CompoundVal>())
  884. return nullptr;
  885. RetE = RetE->IgnoreParenCasts();
  886. // Let's track the return value.
  887. bugreporter::trackExpressionValue(
  888. N, RetE, BR, TKind, EnableNullFPSuppression);
  889. // Build an appropriate message based on the return value.
  890. SmallString<64> Msg;
  891. llvm::raw_svector_ostream Out(Msg);
  892. bool WouldEventBeMeaningless = false;
  893. if (State->isNull(V).isConstrainedTrue()) {
  894. if (V.getAs<Loc>()) {
  895. // If we have counter-suppression enabled, make sure we keep visiting
  896. // future nodes. We want to emit a path note as well, in case
  897. // the report is resurrected as valid later on.
  898. if (EnableNullFPSuppression &&
  899. Options.ShouldAvoidSuppressingNullArgumentPaths)
  900. Mode = MaybeUnsuppress;
  901. if (RetE->getType()->isObjCObjectPointerType()) {
  902. Out << "Returning nil";
  903. } else {
  904. Out << "Returning null pointer";
  905. }
  906. } else {
  907. Out << "Returning zero";
  908. }
  909. } else {
  910. if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
  911. Out << "Returning the value " << CI->getValue();
  912. } else {
  913. // There is nothing interesting about returning a value, when it is
  914. // plain value without any constraints, and the function is guaranteed
  915. // to return that every time. We could use CFG::isLinear() here, but
  916. // constexpr branches are obvious to the compiler, not necesserily to
  917. // the programmer.
  918. if (N->getCFG().size() == 3)
  919. WouldEventBeMeaningless = true;
  920. if (V.getAs<Loc>())
  921. Out << "Returning pointer";
  922. else
  923. Out << "Returning value";
  924. }
  925. }
  926. if (LValue) {
  927. if (const MemRegion *MR = LValue->getAsRegion()) {
  928. if (MR->canPrintPretty()) {
  929. Out << " (reference to ";
  930. MR->printPretty(Out);
  931. Out << ")";
  932. }
  933. }
  934. } else {
  935. // FIXME: We should have a more generalized location printing mechanism.
  936. if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
  937. if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
  938. Out << " (loaded from '" << *DD << "')";
  939. }
  940. PathDiagnosticLocation L(Ret, BRC.getSourceManager(), CalleeSFC);
  941. if (!L.isValid() || !L.asLocation().isValid())
  942. return nullptr;
  943. if (TKind == bugreporter::TrackingKind::Condition)
  944. Out << WillBeUsedForACondition;
  945. auto EventPiece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
  946. // If we determined that the note is meaningless, make it prunable, and
  947. // don't mark the stackframe interesting.
  948. if (WouldEventBeMeaningless)
  949. EventPiece->setPrunable(true);
  950. else
  951. BR.markInteresting(CalleeSFC);
  952. return EventPiece;
  953. }
  954. PathDiagnosticPieceRef visitNodeMaybeUnsuppress(const ExplodedNode *N,
  955. BugReporterContext &BRC,
  956. PathSensitiveBugReport &BR) {
  957. assert(Options.ShouldAvoidSuppressingNullArgumentPaths);
  958. // Are we at the entry node for this call?
  959. Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
  960. if (!CE)
  961. return nullptr;
  962. if (CE->getCalleeContext() != CalleeSFC)
  963. return nullptr;
  964. Mode = Satisfied;
  965. // Don't automatically suppress a report if one of the arguments is
  966. // known to be a null pointer. Instead, start tracking /that/ null
  967. // value back to its origin.
  968. ProgramStateManager &StateMgr = BRC.getStateManager();
  969. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  970. ProgramStateRef State = N->getState();
  971. CallEventRef<> Call = CallMgr.getCaller(CalleeSFC, State);
  972. for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
  973. Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
  974. if (!ArgV)
  975. continue;
  976. const Expr *ArgE = Call->getArgExpr(I);
  977. if (!ArgE)
  978. continue;
  979. // Is it possible for this argument to be non-null?
  980. if (!State->isNull(*ArgV).isConstrainedTrue())
  981. continue;
  982. if (trackExpressionValue(N, ArgE, BR, TKind, EnableNullFPSuppression))
  983. ShouldInvalidate = false;
  984. // If we /can't/ track the null pointer, we should err on the side of
  985. // false negatives, and continue towards marking this report invalid.
  986. // (We will still look at the other arguments, though.)
  987. }
  988. return nullptr;
  989. }
  990. PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
  991. BugReporterContext &BRC,
  992. PathSensitiveBugReport &BR) override {
  993. switch (Mode) {
  994. case Initial:
  995. return visitNodeInitial(N, BRC, BR);
  996. case MaybeUnsuppress:
  997. return visitNodeMaybeUnsuppress(N, BRC, BR);
  998. case Satisfied:
  999. return nullptr;
  1000. }
  1001. llvm_unreachable("Invalid visit mode!");
  1002. }
  1003. void finalizeVisitor(BugReporterContext &, const ExplodedNode *,
  1004. PathSensitiveBugReport &BR) override {
  1005. if (EnableNullFPSuppression && ShouldInvalidate)
  1006. BR.markInvalid(ReturnVisitor::getTag(), CalleeSFC);
  1007. }
  1008. };
  1009. } // end of anonymous namespace
  1010. //===----------------------------------------------------------------------===//
  1011. // Implementation of FindLastStoreBRVisitor.
  1012. //===----------------------------------------------------------------------===//
  1013. void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  1014. static int tag = 0;
  1015. ID.AddPointer(&tag);
  1016. ID.AddPointer(R);
  1017. ID.Add(V);
  1018. ID.AddInteger(static_cast<int>(TKind));
  1019. ID.AddBoolean(EnableNullFPSuppression);
  1020. }
  1021. /// Returns true if \p N represents the DeclStmt declaring and initializing
  1022. /// \p VR.
  1023. static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
  1024. Optional<PostStmt> P = N->getLocationAs<PostStmt>();
  1025. if (!P)
  1026. return false;
  1027. const DeclStmt *DS = P->getStmtAs<DeclStmt>();
  1028. if (!DS)
  1029. return false;
  1030. if (DS->getSingleDecl() != VR->getDecl())
  1031. return false;
  1032. const MemSpaceRegion *VarSpace = VR->getMemorySpace();
  1033. const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
  1034. if (!FrameSpace) {
  1035. // If we ever directly evaluate global DeclStmts, this assertion will be
  1036. // invalid, but this still seems preferable to silently accepting an
  1037. // initialization that may be for a path-sensitive variable.
  1038. assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
  1039. return true;
  1040. }
  1041. assert(VR->getDecl()->hasLocalStorage());
  1042. const LocationContext *LCtx = N->getLocationContext();
  1043. return FrameSpace->getStackFrame() == LCtx->getStackFrame();
  1044. }
  1045. /// Show diagnostics for initializing or declaring a region \p R with a bad value.
  1046. static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os,
  1047. const MemRegion *R, SVal V, const DeclStmt *DS) {
  1048. if (R->canPrintPretty()) {
  1049. R->printPretty(os);
  1050. os << " ";
  1051. }
  1052. if (V.getAs<loc::ConcreteInt>()) {
  1053. bool b = false;
  1054. if (R->isBoundable()) {
  1055. if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
  1056. if (TR->getValueType()->isObjCObjectPointerType()) {
  1057. os << action << "nil";
  1058. b = true;
  1059. }
  1060. }
  1061. }
  1062. if (!b)
  1063. os << action << "a null pointer value";
  1064. } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) {
  1065. os << action << CVal->getValue();
  1066. } else if (DS) {
  1067. if (V.isUndef()) {
  1068. if (isa<VarRegion>(R)) {
  1069. const auto *VD = cast<VarDecl>(DS->getSingleDecl());
  1070. if (VD->getInit()) {
  1071. os << (R->canPrintPretty() ? "initialized" : "Initializing")
  1072. << " to a garbage value";
  1073. } else {
  1074. os << (R->canPrintPretty() ? "declared" : "Declaring")
  1075. << " without an initial value";
  1076. }
  1077. }
  1078. } else {
  1079. os << (R->canPrintPretty() ? "initialized" : "Initialized")
  1080. << " here";
  1081. }
  1082. }
  1083. }
  1084. /// Display diagnostics for passing bad region as a parameter.
  1085. static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
  1086. const VarRegion *VR,
  1087. SVal V) {
  1088. const auto *Param = cast<ParmVarDecl>(VR->getDecl());
  1089. os << "Passing ";
  1090. if (V.getAs<loc::ConcreteInt>()) {
  1091. if (Param->getType()->isObjCObjectPointerType())
  1092. os << "nil object reference";
  1093. else
  1094. os << "null pointer value";
  1095. } else if (V.isUndef()) {
  1096. os << "uninitialized value";
  1097. } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
  1098. os << "the value " << CI->getValue();
  1099. } else {
  1100. os << "value";
  1101. }
  1102. // Printed parameter indexes are 1-based, not 0-based.
  1103. unsigned Idx = Param->getFunctionScopeIndex() + 1;
  1104. os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
  1105. if (VR->canPrintPretty()) {
  1106. os << " ";
  1107. VR->printPretty(os);
  1108. }
  1109. }
  1110. /// Show default diagnostics for storing bad region.
  1111. static void showBRDefaultDiagnostics(llvm::raw_svector_ostream &os,
  1112. const MemRegion *R, SVal V) {
  1113. if (V.getAs<loc::ConcreteInt>()) {
  1114. bool b = false;
  1115. if (R->isBoundable()) {
  1116. if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
  1117. if (TR->getValueType()->isObjCObjectPointerType()) {
  1118. os << "nil object reference stored";
  1119. b = true;
  1120. }
  1121. }
  1122. }
  1123. if (!b) {
  1124. if (R->canPrintPretty())
  1125. os << "Null pointer value stored";
  1126. else
  1127. os << "Storing null pointer value";
  1128. }
  1129. } else if (V.isUndef()) {
  1130. if (R->canPrintPretty())
  1131. os << "Uninitialized value stored";
  1132. else
  1133. os << "Storing uninitialized value";
  1134. } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
  1135. if (R->canPrintPretty())
  1136. os << "The value " << CV->getValue() << " is assigned";
  1137. else
  1138. os << "Assigning " << CV->getValue();
  1139. } else {
  1140. if (R->canPrintPretty())
  1141. os << "Value assigned";
  1142. else
  1143. os << "Assigning value";
  1144. }
  1145. if (R->canPrintPretty()) {
  1146. os << " to ";
  1147. R->printPretty(os);
  1148. }
  1149. }
  1150. PathDiagnosticPieceRef
  1151. FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
  1152. BugReporterContext &BRC,
  1153. PathSensitiveBugReport &BR) {
  1154. if (Satisfied)
  1155. return nullptr;
  1156. const ExplodedNode *StoreSite = nullptr;
  1157. const ExplodedNode *Pred = Succ->getFirstPred();
  1158. const Expr *InitE = nullptr;
  1159. bool IsParam = false;
  1160. // First see if we reached the declaration of the region.
  1161. if (const auto *VR = dyn_cast<VarRegion>(R)) {
  1162. if (isInitializationOfVar(Pred, VR)) {
  1163. StoreSite = Pred;
  1164. InitE = VR->getDecl()->getInit();
  1165. }
  1166. }
  1167. // If this is a post initializer expression, initializing the region, we
  1168. // should track the initializer expression.
  1169. if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
  1170. const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
  1171. if (FieldReg == R) {
  1172. StoreSite = Pred;
  1173. InitE = PIP->getInitializer()->getInit();
  1174. }
  1175. }
  1176. // Otherwise, see if this is the store site:
  1177. // (1) Succ has this binding and Pred does not, i.e. this is
  1178. // where the binding first occurred.
  1179. // (2) Succ has this binding and is a PostStore node for this region, i.e.
  1180. // the same binding was re-assigned here.
  1181. if (!StoreSite) {
  1182. if (Succ->getState()->getSVal(R) != V)
  1183. return nullptr;
  1184. if (hasVisibleUpdate(Pred, Pred->getState()->getSVal(R), Succ, V)) {
  1185. Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
  1186. if (!PS || PS->getLocationValue() != R)
  1187. return nullptr;
  1188. }
  1189. StoreSite = Succ;
  1190. // If this is an assignment expression, we can track the value
  1191. // being assigned.
  1192. if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
  1193. if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
  1194. if (BO->isAssignmentOp())
  1195. InitE = BO->getRHS();
  1196. // If this is a call entry, the variable should be a parameter.
  1197. // FIXME: Handle CXXThisRegion as well. (This is not a priority because
  1198. // 'this' should never be NULL, but this visitor isn't just for NULL and
  1199. // UndefinedVal.)
  1200. if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
  1201. if (const auto *VR = dyn_cast<VarRegion>(R)) {
  1202. if (const auto *Param = dyn_cast<ParmVarDecl>(VR->getDecl())) {
  1203. ProgramStateManager &StateMgr = BRC.getStateManager();
  1204. CallEventManager &CallMgr = StateMgr.getCallEventManager();
  1205. CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
  1206. Succ->getState());
  1207. InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
  1208. } else {
  1209. // Handle Objective-C 'self'.
  1210. assert(isa<ImplicitParamDecl>(VR->getDecl()));
  1211. InitE = cast<ObjCMessageExpr>(CE->getCalleeContext()->getCallSite())
  1212. ->getInstanceReceiver()->IgnoreParenCasts();
  1213. }
  1214. IsParam = true;
  1215. }
  1216. }
  1217. // If this is a CXXTempObjectRegion, the Expr responsible for its creation
  1218. // is wrapped inside of it.
  1219. if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
  1220. InitE = TmpR->getExpr();
  1221. }
  1222. if (!StoreSite)
  1223. return nullptr;
  1224. Satisfied = true;
  1225. // If we have an expression that provided the value, try to track where it
  1226. // came from.
  1227. if (InitE) {
  1228. if (!IsParam)
  1229. InitE = InitE->IgnoreParenCasts();
  1230. bugreporter::trackExpressionValue(
  1231. StoreSite, InitE, BR, TKind, EnableNullFPSuppression);
  1232. }
  1233. if (TKind == TrackingKind::Condition &&
  1234. !OriginSFC->isParentOf(StoreSite->getStackFrame()))
  1235. return nullptr;
  1236. // Okay, we've found the binding. Emit an appropriate message.
  1237. SmallString<256> sbuf;
  1238. llvm::raw_svector_ostream os(sbuf);
  1239. if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
  1240. const Stmt *S = PS->getStmt();
  1241. const char *action = nullptr;
  1242. const auto *DS = dyn_cast<DeclStmt>(S);
  1243. const auto *VR = dyn_cast<VarRegion>(R);
  1244. if (DS) {
  1245. action = R->canPrintPretty() ? "initialized to " :
  1246. "Initializing to ";
  1247. } else if (isa<BlockExpr>(S)) {
  1248. action = R->canPrintPretty() ? "captured by block as " :
  1249. "Captured by block as ";
  1250. if (VR) {
  1251. // See if we can get the BlockVarRegion.
  1252. ProgramStateRef State = StoreSite->getState();
  1253. SVal V = StoreSite->getSVal(S);
  1254. if (const auto *BDR =
  1255. dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
  1256. if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
  1257. if (auto KV = State->getSVal(OriginalR).getAs<KnownSVal>())
  1258. BR.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
  1259. *KV, OriginalR, EnableNullFPSuppression, TKind, OriginSFC));
  1260. }
  1261. }
  1262. }
  1263. }
  1264. if (action)
  1265. showBRDiagnostics(action, os, R, V, DS);
  1266. } else if (StoreSite->getLocation().getAs<CallEnter>()) {
  1267. if (const auto *VR = dyn_cast<VarRegion>(R))
  1268. showBRParamDiagnostics(os, VR, V);
  1269. }
  1270. if (os.str().empty())
  1271. showBRDefaultDiagnostics(os, R, V);
  1272. if (TKind == bugreporter::TrackingKind::Condition)
  1273. os << WillBeUsedForACondition;
  1274. // Construct a new PathDiagnosticPiece.
  1275. ProgramPoint P = StoreSite->getLocation();
  1276. PathDiagnosticLocation L;
  1277. if (P.getAs<CallEnter>() && InitE)
  1278. L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
  1279. P.getLocationContext());
  1280. if (!L.isValid() || !L.asLocation().isValid())
  1281. L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
  1282. if (!L.isValid() || !L.asLocation().isValid())
  1283. return nullptr;
  1284. return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
  1285. }
  1286. //===----------------------------------------------------------------------===//
  1287. // Implementation of TrackConstraintBRVisitor.
  1288. //===----------------------------------------------------------------------===//
  1289. void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  1290. static int tag = 0;
  1291. ID.AddPointer(&tag);
  1292. ID.AddBoolean(Assumption);
  1293. ID.Add(Constraint);
  1294. }
  1295. /// Return the tag associated with this visitor. This tag will be used
  1296. /// to make all PathDiagnosticPieces created by this visitor.
  1297. const char *TrackConstraintBRVisitor::getTag() {
  1298. return "TrackConstraintBRVisitor";
  1299. }
  1300. bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
  1301. if (IsZeroCheck)
  1302. return N->getState()->isNull(Constraint).isUnderconstrained();
  1303. return (bool)N->getState()->assume(Constraint, !Assumption);
  1304. }
  1305. PathDiagnosticPieceRef TrackConstraintBRVisitor::VisitNode(
  1306. const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &) {
  1307. const ExplodedNode *PrevN = N->getFirstPred();
  1308. if (IsSatisfied)
  1309. return nullptr;
  1310. // Start tracking after we see the first state in which the value is
  1311. // constrained.
  1312. if (!IsTrackingTurnedOn)
  1313. if (!isUnderconstrained(N))
  1314. IsTrackingTurnedOn = true;
  1315. if (!IsTrackingTurnedOn)
  1316. return nullptr;
  1317. // Check if in the previous state it was feasible for this constraint
  1318. // to *not* be true.
  1319. if (isUnderconstrained(PrevN)) {
  1320. IsSatisfied = true;
  1321. // As a sanity check, make sure that the negation of the constraint
  1322. // was infeasible in the current state. If it is feasible, we somehow
  1323. // missed the transition point.
  1324. assert(!isUnderconstrained(N));
  1325. // We found the transition point for the constraint. We now need to
  1326. // pretty-print the constraint. (work-in-progress)
  1327. SmallString<64> sbuf;
  1328. llvm::raw_svector_ostream os(sbuf);
  1329. if (Constraint.getAs<Loc>()) {
  1330. os << "Assuming pointer value is ";
  1331. os << (Assumption ? "non-null" : "null");
  1332. }
  1333. if (os.str().empty())
  1334. return nullptr;
  1335. // Construct a new PathDiagnosticPiece.
  1336. ProgramPoint P = N->getLocation();
  1337. PathDiagnosticLocation L =
  1338. PathDiagnosticLocation::create(P, BRC.getSourceManager());
  1339. if (!L.isValid())
  1340. return nullptr;
  1341. auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
  1342. X->setTag(getTag());
  1343. return std::move(X);
  1344. }
  1345. return nullptr;
  1346. }
  1347. //===----------------------------------------------------------------------===//
  1348. // Implementation of SuppressInlineDefensiveChecksVisitor.
  1349. //===----------------------------------------------------------------------===//
  1350. SuppressInlineDefensiveChecksVisitor::
  1351. SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
  1352. : V(Value) {
  1353. // Check if the visitor is disabled.
  1354. AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
  1355. if (!Options.ShouldSuppressInlinedDefensiveChecks)
  1356. IsSatisfied = true;
  1357. assert(N->getState()->isNull(V).isConstrainedTrue() &&
  1358. "The visitor only tracks the cases where V is constrained to 0");
  1359. }
  1360. void SuppressInlineDefensiveChecksVisitor::Profile(
  1361. llvm::FoldingSetNodeID &ID) const {
  1362. static int id = 0;
  1363. ID.AddPointer(&id);
  1364. ID.Add(V);
  1365. }
  1366. const char *SuppressInlineDefensiveChecksVisitor::getTag() {
  1367. return "IDCVisitor";
  1368. }
  1369. PathDiagnosticPieceRef
  1370. SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
  1371. BugReporterContext &BRC,
  1372. PathSensitiveBugReport &BR) {
  1373. const ExplodedNode *Pred = Succ->getFirstPred();
  1374. if (IsSatisfied)
  1375. return nullptr;
  1376. // Start tracking after we see the first state in which the value is null.
  1377. if (!IsTrackingTurnedOn)
  1378. if (Succ->getState()->isNull(V).isConstrainedTrue())
  1379. IsTrackingTurnedOn = true;
  1380. if (!IsTrackingTurnedOn)
  1381. return nullptr;
  1382. // Check if in the previous state it was feasible for this value
  1383. // to *not* be null.
  1384. if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
  1385. IsSatisfied = true;
  1386. assert(Succ->getState()->isNull(V).isConstrainedTrue());
  1387. // Check if this is inlined defensive checks.
  1388. const LocationContext *CurLC =Succ->getLocationContext();
  1389. const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
  1390. if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
  1391. BR.markInvalid("Suppress IDC", CurLC);
  1392. return nullptr;
  1393. }
  1394. // Treat defensive checks in function-like macros as if they were an inlined
  1395. // defensive check. If the bug location is not in a macro and the
  1396. // terminator for the current location is in a macro then suppress the
  1397. // warning.
  1398. auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
  1399. if (!BugPoint)
  1400. return nullptr;
  1401. ProgramPoint CurPoint = Succ->getLocation();
  1402. const Stmt *CurTerminatorStmt = nullptr;
  1403. if (auto BE = CurPoint.getAs<BlockEdge>()) {
  1404. CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
  1405. } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
  1406. const Stmt *CurStmt = SP->getStmt();
  1407. if (!CurStmt->getBeginLoc().isMacroID())
  1408. return nullptr;
  1409. CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
  1410. CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminatorStmt();
  1411. } else {
  1412. return nullptr;
  1413. }
  1414. if (!CurTerminatorStmt)
  1415. return nullptr;
  1416. SourceLocation TerminatorLoc = CurTerminatorStmt->getBeginLoc();
  1417. if (TerminatorLoc.isMacroID()) {
  1418. SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
  1419. // Suppress reports unless we are in that same macro.
  1420. if (!BugLoc.isMacroID() ||
  1421. getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
  1422. BR.markInvalid("Suppress Macro IDC", CurLC);
  1423. }
  1424. return nullptr;
  1425. }
  1426. }
  1427. return nullptr;
  1428. }
  1429. //===----------------------------------------------------------------------===//
  1430. // TrackControlDependencyCondBRVisitor.
  1431. //===----------------------------------------------------------------------===//
  1432. namespace {
  1433. /// Tracks the expressions that are a control dependency of the node that was
  1434. /// supplied to the constructor.
  1435. /// For example:
  1436. ///
  1437. /// cond = 1;
  1438. /// if (cond)
  1439. /// 10 / 0;
  1440. ///
  1441. /// An error is emitted at line 3. This visitor realizes that the branch
  1442. /// on line 2 is a control dependency of line 3, and tracks it's condition via
  1443. /// trackExpressionValue().
  1444. class TrackControlDependencyCondBRVisitor final : public BugReporterVisitor {
  1445. const ExplodedNode *Origin;
  1446. ControlDependencyCalculator ControlDeps;
  1447. llvm::SmallSet<const CFGBlock *, 32> VisitedBlocks;
  1448. public:
  1449. TrackControlDependencyCondBRVisitor(const ExplodedNode *O)
  1450. : Origin(O), ControlDeps(&O->getCFG()) {}
  1451. void Profile(llvm::FoldingSetNodeID &ID) const override {
  1452. static int x = 0;
  1453. ID.AddPointer(&x);
  1454. }
  1455. PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
  1456. BugReporterContext &BRC,
  1457. PathSensitiveBugReport &BR) override;
  1458. };
  1459. } // end of anonymous namespace
  1460. static std::shared_ptr<PathDiagnosticEventPiece>
  1461. constructDebugPieceForTrackedCondition(const Expr *Cond,
  1462. const ExplodedNode *N,
  1463. BugReporterContext &BRC) {
  1464. if (BRC.getAnalyzerOptions().AnalysisDiagOpt == PD_NONE ||
  1465. !BRC.getAnalyzerOptions().ShouldTrackConditionsDebug)
  1466. return nullptr;
  1467. std::string ConditionText = Lexer::getSourceText(
  1468. CharSourceRange::getTokenRange(Cond->getSourceRange()),
  1469. BRC.getSourceManager(),
  1470. BRC.getASTContext().getLangOpts());
  1471. return std::make_shared<PathDiagnosticEventPiece>(
  1472. PathDiagnosticLocation::createBegin(
  1473. Cond, BRC.getSourceManager(), N->getLocationContext()),
  1474. (Twine() + "Tracking condition '" + ConditionText + "'").str());
  1475. }
  1476. static bool isAssertlikeBlock(const CFGBlock *B, ASTContext &Context) {
  1477. if (B->succ_size() != 2)
  1478. return false;
  1479. const CFGBlock *Then = B->succ_begin()->getReachableBlock();
  1480. const CFGBlock *Else = (B->succ_begin() + 1)->getReachableBlock();
  1481. if (!Then || !Else)
  1482. return false;
  1483. if (Then->isInevitablySinking() != Else->isInevitablySinking())
  1484. return true;
  1485. // For the following condition the following CFG would be built:
  1486. //
  1487. // ------------->
  1488. // / \
  1489. // [B1] -> [B2] -> [B3] -> [sink]
  1490. // assert(A && B || C); \ \
  1491. // -----------> [go on with the execution]
  1492. //
  1493. // It so happens that CFGBlock::getTerminatorCondition returns 'A' for block
  1494. // B1, 'A && B' for B2, and 'A && B || C' for B3. Let's check whether we
  1495. // reached the end of the condition!
  1496. if (const Stmt *ElseCond = Else->getTerminatorCondition())
  1497. if (const auto *BinOp = dyn_cast<BinaryOperator>(ElseCond))
  1498. if (BinOp->isLogicalOp())
  1499. return isAssertlikeBlock(Else, Context);
  1500. return false;
  1501. }
  1502. PathDiagnosticPieceRef
  1503. TrackControlDependencyCondBRVisitor::VisitNode(const ExplodedNode *N,
  1504. BugReporterContext &BRC,
  1505. PathSensitiveBugReport &BR) {
  1506. // We can only reason about control dependencies within the same stack frame.
  1507. if (Origin->getStackFrame() != N->getStackFrame())
  1508. return nullptr;
  1509. CFGBlock *NB = const_cast<CFGBlock *>(N->getCFGBlock());
  1510. // Skip if we already inspected this block.
  1511. if (!VisitedBlocks.insert(NB).second)
  1512. return nullptr;
  1513. CFGBlock *OriginB = const_cast<CFGBlock *>(Origin->getCFGBlock());
  1514. // TODO: Cache CFGBlocks for each ExplodedNode.
  1515. if (!OriginB || !NB)
  1516. return nullptr;
  1517. if (isAssertlikeBlock(NB, BRC.getASTContext()))
  1518. return nullptr;
  1519. if (ControlDeps.isControlDependent(OriginB, NB)) {
  1520. // We don't really want to explain for range loops. Evidence suggests that
  1521. // the only thing that leads to is the addition of calls to operator!=.
  1522. if (llvm::isa_and_nonnull<CXXForRangeStmt>(NB->getTerminatorStmt()))
  1523. return nullptr;
  1524. if (const Expr *Condition = NB->getLastCondition()) {
  1525. // Keeping track of the already tracked conditions on a visitor level
  1526. // isn't sufficient, because a new visitor is created for each tracked
  1527. // expression, hence the BugReport level set.
  1528. if (BR.addTrackedCondition(N)) {
  1529. bugreporter::trackExpressionValue(
  1530. N, Condition, BR, bugreporter::TrackingKind::Condition,
  1531. /*EnableNullFPSuppression=*/false);
  1532. return constructDebugPieceForTrackedCondition(Condition, N, BRC);
  1533. }
  1534. }
  1535. }
  1536. return nullptr;
  1537. }
  1538. //===----------------------------------------------------------------------===//
  1539. // Implementation of trackExpressionValue.
  1540. //===----------------------------------------------------------------------===//
  1541. static const MemRegion *getLocationRegionIfReference(const Expr *E,
  1542. const ExplodedNode *N) {
  1543. if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
  1544. if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1545. if (!VD->getType()->isReferenceType())
  1546. return nullptr;
  1547. ProgramStateManager &StateMgr = N->getState()->getStateManager();
  1548. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  1549. return MRMgr.getVarRegion(VD, N->getLocationContext());
  1550. }
  1551. }
  1552. // FIXME: This does not handle other kinds of null references,
  1553. // for example, references from FieldRegions:
  1554. // struct Wrapper { int &ref; };
  1555. // Wrapper w = { *(int *)0 };
  1556. // w.ref = 1;
  1557. return nullptr;
  1558. }
  1559. /// \return A subexpression of {@code Ex} which represents the
  1560. /// expression-of-interest.
  1561. static const Expr *peelOffOuterExpr(const Expr *Ex,
  1562. const ExplodedNode *N) {
  1563. Ex = Ex->IgnoreParenCasts();
  1564. if (const auto *FE = dyn_cast<FullExpr>(Ex))
  1565. return peelOffOuterExpr(FE->getSubExpr(), N);
  1566. if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
  1567. return peelOffOuterExpr(OVE->getSourceExpr(), N);
  1568. if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
  1569. const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
  1570. if (PropRef && PropRef->isMessagingGetter()) {
  1571. const Expr *GetterMessageSend =
  1572. POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
  1573. assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
  1574. return peelOffOuterExpr(GetterMessageSend, N);
  1575. }
  1576. }
  1577. // Peel off the ternary operator.
  1578. if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
  1579. // Find a node where the branching occurred and find out which branch
  1580. // we took (true/false) by looking at the ExplodedGraph.
  1581. const ExplodedNode *NI = N;
  1582. do {
  1583. ProgramPoint ProgPoint = NI->getLocation();
  1584. if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
  1585. const CFGBlock *srcBlk = BE->getSrc();
  1586. if (const Stmt *term = srcBlk->getTerminatorStmt()) {
  1587. if (term == CO) {
  1588. bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
  1589. if (TookTrueBranch)
  1590. return peelOffOuterExpr(CO->getTrueExpr(), N);
  1591. else
  1592. return peelOffOuterExpr(CO->getFalseExpr(), N);
  1593. }
  1594. }
  1595. }
  1596. NI = NI->getFirstPred();
  1597. } while (NI);
  1598. }
  1599. if (auto *BO = dyn_cast<BinaryOperator>(Ex))
  1600. if (const Expr *SubEx = peelOffPointerArithmetic(BO))
  1601. return peelOffOuterExpr(SubEx, N);
  1602. if (auto *UO = dyn_cast<UnaryOperator>(Ex)) {
  1603. if (UO->getOpcode() == UO_LNot)
  1604. return peelOffOuterExpr(UO->getSubExpr(), N);
  1605. // FIXME: There's a hack in our Store implementation that always computes
  1606. // field offsets around null pointers as if they are always equal to 0.
  1607. // The idea here is to report accesses to fields as null dereferences
  1608. // even though the pointer value that's being dereferenced is actually
  1609. // the offset of the field rather than exactly 0.
  1610. // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
  1611. // This code interacts heavily with this hack; otherwise the value
  1612. // would not be null at all for most fields, so we'd be unable to track it.
  1613. if (UO->getOpcode() == UO_AddrOf && UO->getSubExpr()->isLValue())
  1614. if (const Expr *DerefEx = bugreporter::getDerefExpr(UO->getSubExpr()))
  1615. return peelOffOuterExpr(DerefEx, N);
  1616. }
  1617. return Ex;
  1618. }
  1619. /// Find the ExplodedNode where the lvalue (the value of 'Ex')
  1620. /// was computed.
  1621. static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
  1622. const Expr *Inner) {
  1623. while (N) {
  1624. if (N->getStmtForDiagnostics() == Inner)
  1625. return N;
  1626. N = N->getFirstPred();
  1627. }
  1628. return N;
  1629. }
  1630. bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
  1631. const Expr *E,
  1632. PathSensitiveBugReport &report,
  1633. bugreporter::TrackingKind TKind,
  1634. bool EnableNullFPSuppression) {
  1635. if (!E || !InputNode)
  1636. return false;
  1637. const Expr *Inner = peelOffOuterExpr(E, InputNode);
  1638. const ExplodedNode *LVNode = findNodeForExpression(InputNode, Inner);
  1639. if (!LVNode)
  1640. return false;
  1641. ProgramStateRef LVState = LVNode->getState();
  1642. const StackFrameContext *SFC = LVNode->getStackFrame();
  1643. // We only track expressions if we believe that they are important. Chances
  1644. // are good that control dependencies to the tracking point are also improtant
  1645. // because of this, let's explain why we believe control reached this point.
  1646. // TODO: Shouldn't we track control dependencies of every bug location, rather
  1647. // than only tracked expressions?
  1648. if (LVState->getAnalysisManager().getAnalyzerOptions().ShouldTrackConditions)
  1649. report.addVisitor(std::make_unique<TrackControlDependencyCondBRVisitor>(
  1650. InputNode));
  1651. // The message send could be nil due to the receiver being nil.
  1652. // At this point in the path, the receiver should be live since we are at the
  1653. // message send expr. If it is nil, start tracking it.
  1654. if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(Inner, LVNode))
  1655. trackExpressionValue(
  1656. LVNode, Receiver, report, TKind, EnableNullFPSuppression);
  1657. // Track the index if this is an array subscript.
  1658. if (const auto *Arr = dyn_cast<ArraySubscriptExpr>(Inner))
  1659. trackExpressionValue(
  1660. LVNode, Arr->getIdx(), report, TKind, /*EnableNullFPSuppression*/false);
  1661. // See if the expression we're interested refers to a variable.
  1662. // If so, we can track both its contents and constraints on its value.
  1663. if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
  1664. SVal LVal = LVNode->getSVal(Inner);
  1665. const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
  1666. bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
  1667. // If this is a C++ reference to a null pointer, we are tracking the
  1668. // pointer. In addition, we should find the store at which the reference
  1669. // got initialized.
  1670. if (RR && !LVIsNull)
  1671. if (auto KV = LVal.getAs<KnownSVal>())
  1672. report.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
  1673. *KV, RR, EnableNullFPSuppression, TKind, SFC));
  1674. // In case of C++ references, we want to differentiate between a null
  1675. // reference and reference to null pointer.
  1676. // If the LVal is null, check if we are dealing with null reference.
  1677. // For those, we want to track the location of the reference.
  1678. const MemRegion *R = (RR && LVIsNull) ? RR :
  1679. LVNode->getSVal(Inner).getAsRegion();
  1680. if (R) {
  1681. // Mark both the variable region and its contents as interesting.
  1682. SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
  1683. report.addVisitor(
  1684. std::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R), TKind));
  1685. MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
  1686. LVNode, R, EnableNullFPSuppression, report, V);
  1687. report.markInteresting(V, TKind);
  1688. report.addVisitor(std::make_unique<UndefOrNullArgVisitor>(R));
  1689. // If the contents are symbolic and null, find out when they became null.
  1690. if (V.getAsLocSymbol(/*IncludeBaseRegions=*/true))
  1691. if (LVState->isNull(V).isConstrainedTrue())
  1692. report.addVisitor(std::make_unique<TrackConstraintBRVisitor>(
  1693. V.castAs<DefinedSVal>(), false));
  1694. // Add visitor, which will suppress inline defensive checks.
  1695. if (auto DV = V.getAs<DefinedSVal>())
  1696. if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
  1697. EnableNullFPSuppression)
  1698. report.addVisitor(
  1699. std::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
  1700. LVNode));
  1701. if (auto KV = V.getAs<KnownSVal>())
  1702. report.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
  1703. *KV, R, EnableNullFPSuppression, TKind, SFC));
  1704. return true;
  1705. }
  1706. }
  1707. // If the expression is not an "lvalue expression", we can still
  1708. // track the constraints on its contents.
  1709. SVal V = LVState->getSValAsScalarOrLoc(Inner, LVNode->getLocationContext());
  1710. ReturnVisitor::addVisitorIfNecessary(
  1711. LVNode, Inner, report, EnableNullFPSuppression, TKind);
  1712. // Is it a symbolic value?
  1713. if (auto L = V.getAs<loc::MemRegionVal>()) {
  1714. report.addVisitor(std::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
  1715. // FIXME: this is a hack for fixing a later crash when attempting to
  1716. // dereference a void* pointer.
  1717. // We should not try to dereference pointers at all when we don't care
  1718. // what is written inside the pointer.
  1719. bool CanDereference = true;
  1720. if (const auto *SR = L->getRegionAs<SymbolicRegion>()) {
  1721. if (SR->getSymbol()->getType()->getPointeeType()->isVoidType())
  1722. CanDereference = false;
  1723. } else if (L->getRegionAs<AllocaRegion>())
  1724. CanDereference = false;
  1725. // At this point we are dealing with the region's LValue.
  1726. // However, if the rvalue is a symbolic region, we should track it as well.
  1727. // Try to use the correct type when looking up the value.
  1728. SVal RVal;
  1729. if (ExplodedGraph::isInterestingLValueExpr(Inner))
  1730. RVal = LVState->getRawSVal(L.getValue(), Inner->getType());
  1731. else if (CanDereference)
  1732. RVal = LVState->getSVal(L->getRegion());
  1733. if (CanDereference)
  1734. if (auto KV = RVal.getAs<KnownSVal>())
  1735. report.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
  1736. *KV, L->getRegion(), EnableNullFPSuppression, TKind, SFC));
  1737. const MemRegion *RegionRVal = RVal.getAsRegion();
  1738. if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
  1739. report.markInteresting(RegionRVal, TKind);
  1740. report.addVisitor(std::make_unique<TrackConstraintBRVisitor>(
  1741. loc::MemRegionVal(RegionRVal), /*assumption=*/false));
  1742. }
  1743. }
  1744. return true;
  1745. }
  1746. //===----------------------------------------------------------------------===//
  1747. // Implementation of NulReceiverBRVisitor.
  1748. //===----------------------------------------------------------------------===//
  1749. const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
  1750. const ExplodedNode *N) {
  1751. const auto *ME = dyn_cast<ObjCMessageExpr>(S);
  1752. if (!ME)
  1753. return nullptr;
  1754. if (const Expr *Receiver = ME->getInstanceReceiver()) {
  1755. ProgramStateRef state = N->getState();
  1756. SVal V = N->getSVal(Receiver);
  1757. if (state->isNull(V).isConstrainedTrue())
  1758. return Receiver;
  1759. }
  1760. return nullptr;
  1761. }
  1762. PathDiagnosticPieceRef
  1763. NilReceiverBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
  1764. PathSensitiveBugReport &BR) {
  1765. Optional<PreStmt> P = N->getLocationAs<PreStmt>();
  1766. if (!P)
  1767. return nullptr;
  1768. const Stmt *S = P->getStmt();
  1769. const Expr *Receiver = getNilReceiver(S, N);
  1770. if (!Receiver)
  1771. return nullptr;
  1772. llvm::SmallString<256> Buf;
  1773. llvm::raw_svector_ostream OS(Buf);
  1774. if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
  1775. OS << "'";
  1776. ME->getSelector().print(OS);
  1777. OS << "' not called";
  1778. }
  1779. else {
  1780. OS << "No method is called";
  1781. }
  1782. OS << " because the receiver is nil";
  1783. // The receiver was nil, and hence the method was skipped.
  1784. // Register a BugReporterVisitor to issue a message telling us how
  1785. // the receiver was null.
  1786. bugreporter::trackExpressionValue(
  1787. N, Receiver, BR, bugreporter::TrackingKind::Thorough,
  1788. /*EnableNullFPSuppression*/ false);
  1789. // Issue a message saying that the method was skipped.
  1790. PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
  1791. N->getLocationContext());
  1792. return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
  1793. }
  1794. //===----------------------------------------------------------------------===//
  1795. // Visitor that tries to report interesting diagnostics from conditions.
  1796. //===----------------------------------------------------------------------===//
  1797. /// Return the tag associated with this visitor. This tag will be used
  1798. /// to make all PathDiagnosticPieces created by this visitor.
  1799. const char *ConditionBRVisitor::getTag() { return "ConditionBRVisitor"; }
  1800. PathDiagnosticPieceRef
  1801. ConditionBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
  1802. PathSensitiveBugReport &BR) {
  1803. auto piece = VisitNodeImpl(N, BRC, BR);
  1804. if (piece) {
  1805. piece->setTag(getTag());
  1806. if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
  1807. ev->setPrunable(true, /* override */ false);
  1808. }
  1809. return piece;
  1810. }
  1811. PathDiagnosticPieceRef
  1812. ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
  1813. BugReporterContext &BRC,
  1814. PathSensitiveBugReport &BR) {
  1815. ProgramPoint ProgPoint = N->getLocation();
  1816. const std::pair<const ProgramPointTag *, const ProgramPointTag *> &Tags =
  1817. ExprEngine::geteagerlyAssumeBinOpBifurcationTags();
  1818. // If an assumption was made on a branch, it should be caught
  1819. // here by looking at the state transition.
  1820. if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
  1821. const CFGBlock *SrcBlock = BE->getSrc();
  1822. if (const Stmt *Term = SrcBlock->getTerminatorStmt()) {
  1823. // If the tag of the previous node is 'Eagerly Assume...' the current
  1824. // 'BlockEdge' has the same constraint information. We do not want to
  1825. // report the value as it is just an assumption on the predecessor node
  1826. // which will be caught in the next VisitNode() iteration as a 'PostStmt'.
  1827. const ProgramPointTag *PreviousNodeTag =
  1828. N->getFirstPred()->getLocation().getTag();
  1829. if (PreviousNodeTag == Tags.first || PreviousNodeTag == Tags.second)
  1830. return nullptr;
  1831. return VisitTerminator(Term, N, SrcBlock, BE->getDst(), BR, BRC);
  1832. }
  1833. return nullptr;
  1834. }
  1835. if (Optional<PostStmt> PS = ProgPoint.getAs<PostStmt>()) {
  1836. const ProgramPointTag *CurrentNodeTag = PS->getTag();
  1837. if (CurrentNodeTag != Tags.first && CurrentNodeTag != Tags.second)
  1838. return nullptr;
  1839. bool TookTrue = CurrentNodeTag == Tags.first;
  1840. return VisitTrueTest(cast<Expr>(PS->getStmt()), BRC, BR, N, TookTrue);
  1841. }
  1842. return nullptr;
  1843. }
  1844. PathDiagnosticPieceRef ConditionBRVisitor::VisitTerminator(
  1845. const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
  1846. const CFGBlock *dstBlk, PathSensitiveBugReport &R,
  1847. BugReporterContext &BRC) {
  1848. const Expr *Cond = nullptr;
  1849. // In the code below, Term is a CFG terminator and Cond is a branch condition
  1850. // expression upon which the decision is made on this terminator.
  1851. //
  1852. // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
  1853. // and "x == 0" is the respective condition.
  1854. //
  1855. // Another example: in "if (x && y)", we've got two terminators and two
  1856. // conditions due to short-circuit nature of operator "&&":
  1857. // 1. The "if (x && y)" statement is a terminator,
  1858. // and "y" is the respective condition.
  1859. // 2. Also "x && ..." is another terminator,
  1860. // and "x" is its condition.
  1861. switch (Term->getStmtClass()) {
  1862. // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
  1863. // more tricky because there are more than two branches to account for.
  1864. default:
  1865. return nullptr;
  1866. case Stmt::IfStmtClass:
  1867. Cond = cast<IfStmt>(Term)->getCond();
  1868. break;
  1869. case Stmt::ConditionalOperatorClass:
  1870. Cond = cast<ConditionalOperator>(Term)->getCond();
  1871. break;
  1872. case Stmt::BinaryOperatorClass:
  1873. // When we encounter a logical operator (&& or ||) as a CFG terminator,
  1874. // then the condition is actually its LHS; otherwise, we'd encounter
  1875. // the parent, such as if-statement, as a terminator.
  1876. const auto *BO = cast<BinaryOperator>(Term);
  1877. assert(BO->isLogicalOp() &&
  1878. "CFG terminator is not a short-circuit operator!");
  1879. Cond = BO->getLHS();
  1880. break;
  1881. }
  1882. Cond = Cond->IgnoreParens();
  1883. // However, when we encounter a logical operator as a branch condition,
  1884. // then the condition is actually its RHS, because LHS would be
  1885. // the condition for the logical operator terminator.
  1886. while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
  1887. if (!InnerBO->isLogicalOp())
  1888. break;
  1889. Cond = InnerBO->getRHS()->IgnoreParens();
  1890. }
  1891. assert(Cond);
  1892. assert(srcBlk->succ_size() == 2);
  1893. const bool TookTrue = *(srcBlk->succ_begin()) == dstBlk;
  1894. return VisitTrueTest(Cond, BRC, R, N, TookTrue);
  1895. }
  1896. PathDiagnosticPieceRef
  1897. ConditionBRVisitor::VisitTrueTest(const Expr *Cond, BugReporterContext &BRC,
  1898. PathSensitiveBugReport &R,
  1899. const ExplodedNode *N, bool TookTrue) {
  1900. ProgramStateRef CurrentState = N->getState();
  1901. ProgramStateRef PrevState = N->getFirstPred()->getState();
  1902. const LocationContext *LCtx = N->getLocationContext();
  1903. // If the constraint information is changed between the current and the
  1904. // previous program state we assuming the newly seen constraint information.
  1905. // If we cannot evaluate the condition (and the constraints are the same)
  1906. // the analyzer has no information about the value and just assuming it.
  1907. bool IsAssuming =
  1908. !BRC.getStateManager().haveEqualConstraints(CurrentState, PrevState) ||
  1909. CurrentState->getSVal(Cond, LCtx).isUnknownOrUndef();
  1910. // These will be modified in code below, but we need to preserve the original
  1911. // values in case we want to throw the generic message.
  1912. const Expr *CondTmp = Cond;
  1913. bool TookTrueTmp = TookTrue;
  1914. while (true) {
  1915. CondTmp = CondTmp->IgnoreParenCasts();
  1916. switch (CondTmp->getStmtClass()) {
  1917. default:
  1918. break;
  1919. case Stmt::BinaryOperatorClass:
  1920. if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
  1921. BRC, R, N, TookTrueTmp, IsAssuming))
  1922. return P;
  1923. break;
  1924. case Stmt::DeclRefExprClass:
  1925. if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
  1926. BRC, R, N, TookTrueTmp, IsAssuming))
  1927. return P;
  1928. break;
  1929. case Stmt::MemberExprClass:
  1930. if (auto P = VisitTrueTest(Cond, cast<MemberExpr>(CondTmp),
  1931. BRC, R, N, TookTrueTmp, IsAssuming))
  1932. return P;
  1933. break;
  1934. case Stmt::UnaryOperatorClass: {
  1935. const auto *UO = cast<UnaryOperator>(CondTmp);
  1936. if (UO->getOpcode() == UO_LNot) {
  1937. TookTrueTmp = !TookTrueTmp;
  1938. CondTmp = UO->getSubExpr();
  1939. continue;
  1940. }
  1941. break;
  1942. }
  1943. }
  1944. break;
  1945. }
  1946. // Condition too complex to explain? Just say something so that the user
  1947. // knew we've made some path decision at this point.
  1948. // If it is too complex and we know the evaluation of the condition do not
  1949. // repeat the note from 'BugReporter.cpp'
  1950. if (!IsAssuming)
  1951. return nullptr;
  1952. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1953. if (!Loc.isValid() || !Loc.asLocation().isValid())
  1954. return nullptr;
  1955. return std::make_shared<PathDiagnosticEventPiece>(
  1956. Loc, TookTrue ? GenericTrueMessage : GenericFalseMessage);
  1957. }
  1958. bool ConditionBRVisitor::patternMatch(const Expr *Ex,
  1959. const Expr *ParentEx,
  1960. raw_ostream &Out,
  1961. BugReporterContext &BRC,
  1962. PathSensitiveBugReport &report,
  1963. const ExplodedNode *N,
  1964. Optional<bool> &prunable,
  1965. bool IsSameFieldName) {
  1966. const Expr *OriginalExpr = Ex;
  1967. Ex = Ex->IgnoreParenCasts();
  1968. if (isa<GNUNullExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) ||
  1969. isa<CXXBoolLiteralExpr>(Ex) || isa<IntegerLiteral>(Ex) ||
  1970. isa<FloatingLiteral>(Ex)) {
  1971. // Use heuristics to determine if the expression is a macro
  1972. // expanding to a literal and if so, use the macro's name.
  1973. SourceLocation BeginLoc = OriginalExpr->getBeginLoc();
  1974. SourceLocation EndLoc = OriginalExpr->getEndLoc();
  1975. if (BeginLoc.isMacroID() && EndLoc.isMacroID()) {
  1976. const SourceManager &SM = BRC.getSourceManager();
  1977. const LangOptions &LO = BRC.getASTContext().getLangOpts();
  1978. if (Lexer::isAtStartOfMacroExpansion(BeginLoc, SM, LO) &&
  1979. Lexer::isAtEndOfMacroExpansion(EndLoc, SM, LO)) {
  1980. CharSourceRange R = Lexer::getAsCharRange({BeginLoc, EndLoc}, SM, LO);
  1981. Out << Lexer::getSourceText(R, SM, LO);
  1982. return false;
  1983. }
  1984. }
  1985. }
  1986. if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
  1987. const bool quotes = isa<VarDecl>(DR->getDecl());
  1988. if (quotes) {
  1989. Out << '\'';
  1990. const LocationContext *LCtx = N->getLocationContext();
  1991. const ProgramState *state = N->getState().get();
  1992. if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
  1993. LCtx).getAsRegion()) {
  1994. if (report.isInteresting(R))
  1995. prunable = false;
  1996. else {
  1997. const ProgramState *state = N->getState().get();
  1998. SVal V = state->getSVal(R);
  1999. if (report.isInteresting(V))
  2000. prunable = false;
  2001. }
  2002. }
  2003. }
  2004. Out << DR->getDecl()->getDeclName().getAsString();
  2005. if (quotes)
  2006. Out << '\'';
  2007. return quotes;
  2008. }
  2009. if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
  2010. QualType OriginalTy = OriginalExpr->getType();
  2011. if (OriginalTy->isPointerType()) {
  2012. if (IL->getValue() == 0) {
  2013. Out << "null";
  2014. return false;
  2015. }
  2016. }
  2017. else if (OriginalTy->isObjCObjectPointerType()) {
  2018. if (IL->getValue() == 0) {
  2019. Out << "nil";
  2020. return false;
  2021. }
  2022. }
  2023. Out << IL->getValue();
  2024. return false;
  2025. }
  2026. if (const auto *ME = dyn_cast<MemberExpr>(Ex)) {
  2027. if (!IsSameFieldName)
  2028. Out << "field '" << ME->getMemberDecl()->getName() << '\'';
  2029. else
  2030. Out << '\''
  2031. << Lexer::getSourceText(
  2032. CharSourceRange::getTokenRange(Ex->getSourceRange()),
  2033. BRC.getSourceManager(), BRC.getASTContext().getLangOpts(), 0)
  2034. << '\'';
  2035. }
  2036. return false;
  2037. }
  2038. PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
  2039. const Expr *Cond, const BinaryOperator *BExpr, BugReporterContext &BRC,
  2040. PathSensitiveBugReport &R, const ExplodedNode *N, bool TookTrue,
  2041. bool IsAssuming) {
  2042. bool shouldInvert = false;
  2043. Optional<bool> shouldPrune;
  2044. // Check if the field name of the MemberExprs is ambiguous. Example:
  2045. // " 'a.d' is equal to 'h.d' " in 'test/Analysis/null-deref-path-notes.cpp'.
  2046. bool IsSameFieldName = false;
  2047. const auto *LhsME = dyn_cast<MemberExpr>(BExpr->getLHS()->IgnoreParenCasts());
  2048. const auto *RhsME = dyn_cast<MemberExpr>(BExpr->getRHS()->IgnoreParenCasts());
  2049. if (LhsME && RhsME)
  2050. IsSameFieldName =
  2051. LhsME->getMemberDecl()->getName() == RhsME->getMemberDecl()->getName();
  2052. SmallString<128> LhsString, RhsString;
  2053. {
  2054. llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
  2055. const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS, BRC, R,
  2056. N, shouldPrune, IsSameFieldName);
  2057. const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS, BRC, R,
  2058. N, shouldPrune, IsSameFieldName);
  2059. shouldInvert = !isVarLHS && isVarRHS;
  2060. }
  2061. BinaryOperator::Opcode Op = BExpr->getOpcode();
  2062. if (BinaryOperator::isAssignmentOp(Op)) {
  2063. // For assignment operators, all that we care about is that the LHS
  2064. // evaluates to "true" or "false".
  2065. return VisitConditionVariable(LhsString, BExpr->getLHS(), BRC, R, N,
  2066. TookTrue);
  2067. }
  2068. // For non-assignment operations, we require that we can understand
  2069. // both the LHS and RHS.
  2070. if (LhsString.empty() || RhsString.empty() ||
  2071. !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
  2072. return nullptr;
  2073. // Should we invert the strings if the LHS is not a variable name?
  2074. SmallString<256> buf;
  2075. llvm::raw_svector_ostream Out(buf);
  2076. Out << (IsAssuming ? "Assuming " : "")
  2077. << (shouldInvert ? RhsString : LhsString) << " is ";
  2078. // Do we need to invert the opcode?
  2079. if (shouldInvert)
  2080. switch (Op) {
  2081. default: break;
  2082. case BO_LT: Op = BO_GT; break;
  2083. case BO_GT: Op = BO_LT; break;
  2084. case BO_LE: Op = BO_GE; break;
  2085. case BO_GE: Op = BO_LE; break;
  2086. }
  2087. if (!TookTrue)
  2088. switch (Op) {
  2089. case BO_EQ: Op = BO_NE; break;
  2090. case BO_NE: Op = BO_EQ; break;
  2091. case BO_LT: Op = BO_GE; break;
  2092. case BO_GT: Op = BO_LE; break;
  2093. case BO_LE: Op = BO_GT; break;
  2094. case BO_GE: Op = BO_LT; break;
  2095. default:
  2096. return nullptr;
  2097. }
  2098. switch (Op) {
  2099. case BO_EQ:
  2100. Out << "equal to ";
  2101. break;
  2102. case BO_NE:
  2103. Out << "not equal to ";
  2104. break;
  2105. default:
  2106. Out << BinaryOperator::getOpcodeStr(Op) << ' ';
  2107. break;
  2108. }
  2109. Out << (shouldInvert ? LhsString : RhsString);
  2110. const LocationContext *LCtx = N->getLocationContext();
  2111. const SourceManager &SM = BRC.getSourceManager();
  2112. if (isVarAnInterestingCondition(BExpr->getLHS(), N, &R) ||
  2113. isVarAnInterestingCondition(BExpr->getRHS(), N, &R))
  2114. Out << WillBeUsedForACondition;
  2115. // Convert 'field ...' to 'Field ...' if it is a MemberExpr.
  2116. std::string Message = Out.str();
  2117. Message[0] = toupper(Message[0]);
  2118. // If we know the value create a pop-up note to the value part of 'BExpr'.
  2119. if (!IsAssuming) {
  2120. PathDiagnosticLocation Loc;
  2121. if (!shouldInvert) {
  2122. if (LhsME && LhsME->getMemberLoc().isValid())
  2123. Loc = PathDiagnosticLocation(LhsME->getMemberLoc(), SM);
  2124. else
  2125. Loc = PathDiagnosticLocation(BExpr->getLHS(), SM, LCtx);
  2126. } else {
  2127. if (RhsME && RhsME->getMemberLoc().isValid())
  2128. Loc = PathDiagnosticLocation(RhsME->getMemberLoc(), SM);
  2129. else
  2130. Loc = PathDiagnosticLocation(BExpr->getRHS(), SM, LCtx);
  2131. }
  2132. return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Message);
  2133. }
  2134. PathDiagnosticLocation Loc(Cond, SM, LCtx);
  2135. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Message);
  2136. if (shouldPrune.hasValue())
  2137. event->setPrunable(shouldPrune.getValue());
  2138. return event;
  2139. }
  2140. PathDiagnosticPieceRef ConditionBRVisitor::VisitConditionVariable(
  2141. StringRef LhsString, const Expr *CondVarExpr, BugReporterContext &BRC,
  2142. PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue) {
  2143. // FIXME: If there's already a constraint tracker for this variable,
  2144. // we shouldn't emit anything here (c.f. the double note in
  2145. // test/Analysis/inlining/path-notes.c)
  2146. SmallString<256> buf;
  2147. llvm::raw_svector_ostream Out(buf);
  2148. Out << "Assuming " << LhsString << " is ";
  2149. if (!printValue(CondVarExpr, Out, N, TookTrue, /*IsAssuming=*/true))
  2150. return nullptr;
  2151. const LocationContext *LCtx = N->getLocationContext();
  2152. PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
  2153. if (isVarAnInterestingCondition(CondVarExpr, N, &report))
  2154. Out << WillBeUsedForACondition;
  2155. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  2156. if (isInterestingExpr(CondVarExpr, N, &report))
  2157. event->setPrunable(false);
  2158. return event;
  2159. }
  2160. PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
  2161. const Expr *Cond, const DeclRefExpr *DRE, BugReporterContext &BRC,
  2162. PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
  2163. bool IsAssuming) {
  2164. const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
  2165. if (!VD)
  2166. return nullptr;
  2167. SmallString<256> Buf;
  2168. llvm::raw_svector_ostream Out(Buf);
  2169. Out << (IsAssuming ? "Assuming '" : "'") << VD->getDeclName() << "' is ";
  2170. if (!printValue(DRE, Out, N, TookTrue, IsAssuming))
  2171. return nullptr;
  2172. const LocationContext *LCtx = N->getLocationContext();
  2173. if (isVarAnInterestingCondition(DRE, N, &report))
  2174. Out << WillBeUsedForACondition;
  2175. // If we know the value create a pop-up note to the 'DRE'.
  2176. if (!IsAssuming) {
  2177. PathDiagnosticLocation Loc(DRE, BRC.getSourceManager(), LCtx);
  2178. return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
  2179. }
  2180. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  2181. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  2182. if (isInterestingExpr(DRE, N, &report))
  2183. event->setPrunable(false);
  2184. return std::move(event);
  2185. }
  2186. PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
  2187. const Expr *Cond, const MemberExpr *ME, BugReporterContext &BRC,
  2188. PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
  2189. bool IsAssuming) {
  2190. SmallString<256> Buf;
  2191. llvm::raw_svector_ostream Out(Buf);
  2192. Out << (IsAssuming ? "Assuming field '" : "Field '")
  2193. << ME->getMemberDecl()->getName() << "' is ";
  2194. if (!printValue(ME, Out, N, TookTrue, IsAssuming))
  2195. return nullptr;
  2196. const LocationContext *LCtx = N->getLocationContext();
  2197. PathDiagnosticLocation Loc;
  2198. // If we know the value create a pop-up note to the member of the MemberExpr.
  2199. if (!IsAssuming && ME->getMemberLoc().isValid())
  2200. Loc = PathDiagnosticLocation(ME->getMemberLoc(), BRC.getSourceManager());
  2201. else
  2202. Loc = PathDiagnosticLocation(Cond, BRC.getSourceManager(), LCtx);
  2203. if (!Loc.isValid() || !Loc.asLocation().isValid())
  2204. return nullptr;
  2205. if (isVarAnInterestingCondition(ME, N, &report))
  2206. Out << WillBeUsedForACondition;
  2207. // If we know the value create a pop-up note.
  2208. if (!IsAssuming)
  2209. return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
  2210. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  2211. if (isInterestingExpr(ME, N, &report))
  2212. event->setPrunable(false);
  2213. return event;
  2214. }
  2215. bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out,
  2216. const ExplodedNode *N, bool TookTrue,
  2217. bool IsAssuming) {
  2218. QualType Ty = CondVarExpr->getType();
  2219. if (Ty->isPointerType()) {
  2220. Out << (TookTrue ? "non-null" : "null");
  2221. return true;
  2222. }
  2223. if (Ty->isObjCObjectPointerType()) {
  2224. Out << (TookTrue ? "non-nil" : "nil");
  2225. return true;
  2226. }
  2227. if (!Ty->isIntegralOrEnumerationType())
  2228. return false;
  2229. Optional<const llvm::APSInt *> IntValue;
  2230. if (!IsAssuming)
  2231. IntValue = getConcreteIntegerValue(CondVarExpr, N);
  2232. if (IsAssuming || !IntValue.hasValue()) {
  2233. if (Ty->isBooleanType())
  2234. Out << (TookTrue ? "true" : "false");
  2235. else
  2236. Out << (TookTrue ? "not equal to 0" : "0");
  2237. } else {
  2238. if (Ty->isBooleanType())
  2239. Out << (IntValue.getValue()->getBoolValue() ? "true" : "false");
  2240. else
  2241. Out << *IntValue.getValue();
  2242. }
  2243. return true;
  2244. }
  2245. constexpr llvm::StringLiteral ConditionBRVisitor::GenericTrueMessage;
  2246. constexpr llvm::StringLiteral ConditionBRVisitor::GenericFalseMessage;
  2247. bool ConditionBRVisitor::isPieceMessageGeneric(
  2248. const PathDiagnosticPiece *Piece) {
  2249. return Piece->getString() == GenericTrueMessage ||
  2250. Piece->getString() == GenericFalseMessage;
  2251. }
  2252. //===----------------------------------------------------------------------===//
  2253. // Implementation of LikelyFalsePositiveSuppressionBRVisitor.
  2254. //===----------------------------------------------------------------------===//
  2255. void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
  2256. BugReporterContext &BRC, const ExplodedNode *N,
  2257. PathSensitiveBugReport &BR) {
  2258. // Here we suppress false positives coming from system headers. This list is
  2259. // based on known issues.
  2260. const AnalyzerOptions &Options = BRC.getAnalyzerOptions();
  2261. const Decl *D = N->getLocationContext()->getDecl();
  2262. if (AnalysisDeclContext::isInStdNamespace(D)) {
  2263. // Skip reports within the 'std' namespace. Although these can sometimes be
  2264. // the user's fault, we currently don't report them very well, and
  2265. // Note that this will not help for any other data structure libraries, like
  2266. // TR1, Boost, or llvm/ADT.
  2267. if (Options.ShouldSuppressFromCXXStandardLibrary) {
  2268. BR.markInvalid(getTag(), nullptr);
  2269. return;
  2270. } else {
  2271. // If the complete 'std' suppression is not enabled, suppress reports
  2272. // from the 'std' namespace that are known to produce false positives.
  2273. // The analyzer issues a false use-after-free when std::list::pop_front
  2274. // or std::list::pop_back are called multiple times because we cannot
  2275. // reason about the internal invariants of the data structure.
  2276. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  2277. const CXXRecordDecl *CD = MD->getParent();
  2278. if (CD->getName() == "list") {
  2279. BR.markInvalid(getTag(), nullptr);
  2280. return;
  2281. }
  2282. }
  2283. // The analyzer issues a false positive when the constructor of
  2284. // std::__independent_bits_engine from algorithms is used.
  2285. if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
  2286. const CXXRecordDecl *CD = MD->getParent();
  2287. if (CD->getName() == "__independent_bits_engine") {
  2288. BR.markInvalid(getTag(), nullptr);
  2289. return;
  2290. }
  2291. }
  2292. for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
  2293. LCtx = LCtx->getParent()) {
  2294. const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
  2295. if (!MD)
  2296. continue;
  2297. const CXXRecordDecl *CD = MD->getParent();
  2298. // The analyzer issues a false positive on
  2299. // std::basic_string<uint8_t> v; v.push_back(1);
  2300. // and
  2301. // std::u16string s; s += u'a';
  2302. // because we cannot reason about the internal invariants of the
  2303. // data structure.
  2304. if (CD->getName() == "basic_string") {
  2305. BR.markInvalid(getTag(), nullptr);
  2306. return;
  2307. }
  2308. // The analyzer issues a false positive on
  2309. // std::shared_ptr<int> p(new int(1)); p = nullptr;
  2310. // because it does not reason properly about temporary destructors.
  2311. if (CD->getName() == "shared_ptr") {
  2312. BR.markInvalid(getTag(), nullptr);
  2313. return;
  2314. }
  2315. }
  2316. }
  2317. }
  2318. // Skip reports within the sys/queue.h macros as we do not have the ability to
  2319. // reason about data structure shapes.
  2320. const SourceManager &SM = BRC.getSourceManager();
  2321. FullSourceLoc Loc = BR.getLocation().asLocation();
  2322. while (Loc.isMacroID()) {
  2323. Loc = Loc.getSpellingLoc();
  2324. if (SM.getFilename(Loc).endswith("sys/queue.h")) {
  2325. BR.markInvalid(getTag(), nullptr);
  2326. return;
  2327. }
  2328. }
  2329. }
  2330. //===----------------------------------------------------------------------===//
  2331. // Implementation of UndefOrNullArgVisitor.
  2332. //===----------------------------------------------------------------------===//
  2333. PathDiagnosticPieceRef
  2334. UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
  2335. PathSensitiveBugReport &BR) {
  2336. ProgramStateRef State = N->getState();
  2337. ProgramPoint ProgLoc = N->getLocation();
  2338. // We are only interested in visiting CallEnter nodes.
  2339. Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
  2340. if (!CEnter)
  2341. return nullptr;
  2342. // Check if one of the arguments is the region the visitor is tracking.
  2343. CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
  2344. CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
  2345. unsigned Idx = 0;
  2346. ArrayRef<ParmVarDecl *> parms = Call->parameters();
  2347. for (const auto ParamDecl : parms) {
  2348. const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
  2349. ++Idx;
  2350. // Are we tracking the argument or its subregion?
  2351. if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
  2352. continue;
  2353. // Check the function parameter type.
  2354. assert(ParamDecl && "Formal parameter has no decl?");
  2355. QualType T = ParamDecl->getType();
  2356. if (!(T->isAnyPointerType() || T->isReferenceType())) {
  2357. // Function can only change the value passed in by address.
  2358. continue;
  2359. }
  2360. // If it is a const pointer value, the function does not intend to
  2361. // change the value.
  2362. if (T->getPointeeType().isConstQualified())
  2363. continue;
  2364. // Mark the call site (LocationContext) as interesting if the value of the
  2365. // argument is undefined or '0'/'NULL'.
  2366. SVal BoundVal = State->getSVal(R);
  2367. if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
  2368. BR.markInteresting(CEnter->getCalleeContext());
  2369. return nullptr;
  2370. }
  2371. }
  2372. return nullptr;
  2373. }
  2374. //===----------------------------------------------------------------------===//
  2375. // Implementation of FalsePositiveRefutationBRVisitor.
  2376. //===----------------------------------------------------------------------===//
  2377. FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor()
  2378. : Constraints(ConstraintRangeTy::Factory().getEmptyMap()) {}
  2379. void FalsePositiveRefutationBRVisitor::finalizeVisitor(
  2380. BugReporterContext &BRC, const ExplodedNode *EndPathNode,
  2381. PathSensitiveBugReport &BR) {
  2382. // Collect new constraints
  2383. VisitNode(EndPathNode, BRC, BR);
  2384. // Create a refutation manager
  2385. llvm::SMTSolverRef RefutationSolver = llvm::CreateZ3Solver();
  2386. ASTContext &Ctx = BRC.getASTContext();
  2387. // Add constraints to the solver
  2388. for (const auto &I : Constraints) {
  2389. const SymbolRef Sym = I.first;
  2390. auto RangeIt = I.second.begin();
  2391. llvm::SMTExprRef Constraints = SMTConv::getRangeExpr(
  2392. RefutationSolver, Ctx, Sym, RangeIt->From(), RangeIt->To(),
  2393. /*InRange=*/true);
  2394. while ((++RangeIt) != I.second.end()) {
  2395. Constraints = RefutationSolver->mkOr(
  2396. Constraints, SMTConv::getRangeExpr(RefutationSolver, Ctx, Sym,
  2397. RangeIt->From(), RangeIt->To(),
  2398. /*InRange=*/true));
  2399. }
  2400. RefutationSolver->addConstraint(Constraints);
  2401. }
  2402. // And check for satisfiability
  2403. Optional<bool> isSat = RefutationSolver->check();
  2404. if (!isSat.hasValue())
  2405. return;
  2406. if (!isSat.getValue())
  2407. BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext());
  2408. }
  2409. PathDiagnosticPieceRef FalsePositiveRefutationBRVisitor::VisitNode(
  2410. const ExplodedNode *N, BugReporterContext &, PathSensitiveBugReport &) {
  2411. // Collect new constraints
  2412. const ConstraintRangeTy &NewCs = N->getState()->get<ConstraintRange>();
  2413. ConstraintRangeTy::Factory &CF =
  2414. N->getState()->get_context<ConstraintRange>();
  2415. // Add constraints if we don't have them yet
  2416. for (auto const &C : NewCs) {
  2417. const SymbolRef &Sym = C.first;
  2418. if (!Constraints.contains(Sym)) {
  2419. Constraints = CF.add(Constraints, Sym, C.second);
  2420. }
  2421. }
  2422. return nullptr;
  2423. }
  2424. void FalsePositiveRefutationBRVisitor::Profile(
  2425. llvm::FoldingSetNodeID &ID) const {
  2426. static int Tag = 0;
  2427. ID.AddPointer(&Tag);
  2428. }
  2429. //===----------------------------------------------------------------------===//
  2430. // Implementation of TagVisitor.
  2431. //===----------------------------------------------------------------------===//
  2432. int NoteTag::Kind = 0;
  2433. void TagVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  2434. static int Tag = 0;
  2435. ID.AddPointer(&Tag);
  2436. }
  2437. PathDiagnosticPieceRef TagVisitor::VisitNode(const ExplodedNode *N,
  2438. BugReporterContext &BRC,
  2439. PathSensitiveBugReport &R) {
  2440. ProgramPoint PP = N->getLocation();
  2441. const NoteTag *T = dyn_cast_or_null<NoteTag>(PP.getTag());
  2442. if (!T)
  2443. return nullptr;
  2444. if (Optional<std::string> Msg = T->generateMessage(BRC, R)) {
  2445. PathDiagnosticLocation Loc =
  2446. PathDiagnosticLocation::create(PP, BRC.getSourceManager());
  2447. auto Piece = std::make_shared<PathDiagnosticEventPiece>(Loc, *Msg);
  2448. Piece->setPrunable(T->isPrunable());
  2449. return Piece;
  2450. }
  2451. return nullptr;
  2452. }