BugReporterVisitors.cpp 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908
  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. // FIXME: this is a hack for fixing a later crash when attempting to
  1715. // dereference a void* pointer.
  1716. // We should not try to dereference pointers at all when we don't care
  1717. // what is written inside the pointer.
  1718. bool CanDereference = true;
  1719. if (const auto *SR = L->getRegionAs<SymbolicRegion>()) {
  1720. if (SR->getSymbol()->getType()->getPointeeType()->isVoidType())
  1721. CanDereference = false;
  1722. } else if (L->getRegionAs<AllocaRegion>())
  1723. CanDereference = false;
  1724. // At this point we are dealing with the region's LValue.
  1725. // However, if the rvalue is a symbolic region, we should track it as well.
  1726. // Try to use the correct type when looking up the value.
  1727. SVal RVal;
  1728. if (ExplodedGraph::isInterestingLValueExpr(Inner))
  1729. RVal = LVState->getRawSVal(L.getValue(), Inner->getType());
  1730. else if (CanDereference)
  1731. RVal = LVState->getSVal(L->getRegion());
  1732. if (CanDereference) {
  1733. report.addVisitor(
  1734. std::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
  1735. if (auto KV = RVal.getAs<KnownSVal>())
  1736. report.addVisitor(std::make_unique<FindLastStoreBRVisitor>(
  1737. *KV, L->getRegion(), EnableNullFPSuppression, TKind, SFC));
  1738. }
  1739. const MemRegion *RegionRVal = RVal.getAsRegion();
  1740. if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
  1741. report.markInteresting(RegionRVal, TKind);
  1742. report.addVisitor(std::make_unique<TrackConstraintBRVisitor>(
  1743. loc::MemRegionVal(RegionRVal), /*assumption=*/false));
  1744. }
  1745. }
  1746. return true;
  1747. }
  1748. //===----------------------------------------------------------------------===//
  1749. // Implementation of NulReceiverBRVisitor.
  1750. //===----------------------------------------------------------------------===//
  1751. const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
  1752. const ExplodedNode *N) {
  1753. const auto *ME = dyn_cast<ObjCMessageExpr>(S);
  1754. if (!ME)
  1755. return nullptr;
  1756. if (const Expr *Receiver = ME->getInstanceReceiver()) {
  1757. ProgramStateRef state = N->getState();
  1758. SVal V = N->getSVal(Receiver);
  1759. if (state->isNull(V).isConstrainedTrue())
  1760. return Receiver;
  1761. }
  1762. return nullptr;
  1763. }
  1764. PathDiagnosticPieceRef
  1765. NilReceiverBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
  1766. PathSensitiveBugReport &BR) {
  1767. Optional<PreStmt> P = N->getLocationAs<PreStmt>();
  1768. if (!P)
  1769. return nullptr;
  1770. const Stmt *S = P->getStmt();
  1771. const Expr *Receiver = getNilReceiver(S, N);
  1772. if (!Receiver)
  1773. return nullptr;
  1774. llvm::SmallString<256> Buf;
  1775. llvm::raw_svector_ostream OS(Buf);
  1776. if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
  1777. OS << "'";
  1778. ME->getSelector().print(OS);
  1779. OS << "' not called";
  1780. }
  1781. else {
  1782. OS << "No method is called";
  1783. }
  1784. OS << " because the receiver is nil";
  1785. // The receiver was nil, and hence the method was skipped.
  1786. // Register a BugReporterVisitor to issue a message telling us how
  1787. // the receiver was null.
  1788. bugreporter::trackExpressionValue(
  1789. N, Receiver, BR, bugreporter::TrackingKind::Thorough,
  1790. /*EnableNullFPSuppression*/ false);
  1791. // Issue a message saying that the method was skipped.
  1792. PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
  1793. N->getLocationContext());
  1794. return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
  1795. }
  1796. //===----------------------------------------------------------------------===//
  1797. // Visitor that tries to report interesting diagnostics from conditions.
  1798. //===----------------------------------------------------------------------===//
  1799. /// Return the tag associated with this visitor. This tag will be used
  1800. /// to make all PathDiagnosticPieces created by this visitor.
  1801. const char *ConditionBRVisitor::getTag() { return "ConditionBRVisitor"; }
  1802. PathDiagnosticPieceRef
  1803. ConditionBRVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
  1804. PathSensitiveBugReport &BR) {
  1805. auto piece = VisitNodeImpl(N, BRC, BR);
  1806. if (piece) {
  1807. piece->setTag(getTag());
  1808. if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
  1809. ev->setPrunable(true, /* override */ false);
  1810. }
  1811. return piece;
  1812. }
  1813. PathDiagnosticPieceRef
  1814. ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
  1815. BugReporterContext &BRC,
  1816. PathSensitiveBugReport &BR) {
  1817. ProgramPoint ProgPoint = N->getLocation();
  1818. const std::pair<const ProgramPointTag *, const ProgramPointTag *> &Tags =
  1819. ExprEngine::geteagerlyAssumeBinOpBifurcationTags();
  1820. // If an assumption was made on a branch, it should be caught
  1821. // here by looking at the state transition.
  1822. if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
  1823. const CFGBlock *SrcBlock = BE->getSrc();
  1824. if (const Stmt *Term = SrcBlock->getTerminatorStmt()) {
  1825. // If the tag of the previous node is 'Eagerly Assume...' the current
  1826. // 'BlockEdge' has the same constraint information. We do not want to
  1827. // report the value as it is just an assumption on the predecessor node
  1828. // which will be caught in the next VisitNode() iteration as a 'PostStmt'.
  1829. const ProgramPointTag *PreviousNodeTag =
  1830. N->getFirstPred()->getLocation().getTag();
  1831. if (PreviousNodeTag == Tags.first || PreviousNodeTag == Tags.second)
  1832. return nullptr;
  1833. return VisitTerminator(Term, N, SrcBlock, BE->getDst(), BR, BRC);
  1834. }
  1835. return nullptr;
  1836. }
  1837. if (Optional<PostStmt> PS = ProgPoint.getAs<PostStmt>()) {
  1838. const ProgramPointTag *CurrentNodeTag = PS->getTag();
  1839. if (CurrentNodeTag != Tags.first && CurrentNodeTag != Tags.second)
  1840. return nullptr;
  1841. bool TookTrue = CurrentNodeTag == Tags.first;
  1842. return VisitTrueTest(cast<Expr>(PS->getStmt()), BRC, BR, N, TookTrue);
  1843. }
  1844. return nullptr;
  1845. }
  1846. PathDiagnosticPieceRef ConditionBRVisitor::VisitTerminator(
  1847. const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
  1848. const CFGBlock *dstBlk, PathSensitiveBugReport &R,
  1849. BugReporterContext &BRC) {
  1850. const Expr *Cond = nullptr;
  1851. // In the code below, Term is a CFG terminator and Cond is a branch condition
  1852. // expression upon which the decision is made on this terminator.
  1853. //
  1854. // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
  1855. // and "x == 0" is the respective condition.
  1856. //
  1857. // Another example: in "if (x && y)", we've got two terminators and two
  1858. // conditions due to short-circuit nature of operator "&&":
  1859. // 1. The "if (x && y)" statement is a terminator,
  1860. // and "y" is the respective condition.
  1861. // 2. Also "x && ..." is another terminator,
  1862. // and "x" is its condition.
  1863. switch (Term->getStmtClass()) {
  1864. // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
  1865. // more tricky because there are more than two branches to account for.
  1866. default:
  1867. return nullptr;
  1868. case Stmt::IfStmtClass:
  1869. Cond = cast<IfStmt>(Term)->getCond();
  1870. break;
  1871. case Stmt::ConditionalOperatorClass:
  1872. Cond = cast<ConditionalOperator>(Term)->getCond();
  1873. break;
  1874. case Stmt::BinaryOperatorClass:
  1875. // When we encounter a logical operator (&& or ||) as a CFG terminator,
  1876. // then the condition is actually its LHS; otherwise, we'd encounter
  1877. // the parent, such as if-statement, as a terminator.
  1878. const auto *BO = cast<BinaryOperator>(Term);
  1879. assert(BO->isLogicalOp() &&
  1880. "CFG terminator is not a short-circuit operator!");
  1881. Cond = BO->getLHS();
  1882. break;
  1883. }
  1884. Cond = Cond->IgnoreParens();
  1885. // However, when we encounter a logical operator as a branch condition,
  1886. // then the condition is actually its RHS, because LHS would be
  1887. // the condition for the logical operator terminator.
  1888. while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
  1889. if (!InnerBO->isLogicalOp())
  1890. break;
  1891. Cond = InnerBO->getRHS()->IgnoreParens();
  1892. }
  1893. assert(Cond);
  1894. assert(srcBlk->succ_size() == 2);
  1895. const bool TookTrue = *(srcBlk->succ_begin()) == dstBlk;
  1896. return VisitTrueTest(Cond, BRC, R, N, TookTrue);
  1897. }
  1898. PathDiagnosticPieceRef
  1899. ConditionBRVisitor::VisitTrueTest(const Expr *Cond, BugReporterContext &BRC,
  1900. PathSensitiveBugReport &R,
  1901. const ExplodedNode *N, bool TookTrue) {
  1902. ProgramStateRef CurrentState = N->getState();
  1903. ProgramStateRef PrevState = N->getFirstPred()->getState();
  1904. const LocationContext *LCtx = N->getLocationContext();
  1905. // If the constraint information is changed between the current and the
  1906. // previous program state we assuming the newly seen constraint information.
  1907. // If we cannot evaluate the condition (and the constraints are the same)
  1908. // the analyzer has no information about the value and just assuming it.
  1909. bool IsAssuming =
  1910. !BRC.getStateManager().haveEqualConstraints(CurrentState, PrevState) ||
  1911. CurrentState->getSVal(Cond, LCtx).isUnknownOrUndef();
  1912. // These will be modified in code below, but we need to preserve the original
  1913. // values in case we want to throw the generic message.
  1914. const Expr *CondTmp = Cond;
  1915. bool TookTrueTmp = TookTrue;
  1916. while (true) {
  1917. CondTmp = CondTmp->IgnoreParenCasts();
  1918. switch (CondTmp->getStmtClass()) {
  1919. default:
  1920. break;
  1921. case Stmt::BinaryOperatorClass:
  1922. if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
  1923. BRC, R, N, TookTrueTmp, IsAssuming))
  1924. return P;
  1925. break;
  1926. case Stmt::DeclRefExprClass:
  1927. if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
  1928. BRC, R, N, TookTrueTmp, IsAssuming))
  1929. return P;
  1930. break;
  1931. case Stmt::MemberExprClass:
  1932. if (auto P = VisitTrueTest(Cond, cast<MemberExpr>(CondTmp),
  1933. BRC, R, N, TookTrueTmp, IsAssuming))
  1934. return P;
  1935. break;
  1936. case Stmt::UnaryOperatorClass: {
  1937. const auto *UO = cast<UnaryOperator>(CondTmp);
  1938. if (UO->getOpcode() == UO_LNot) {
  1939. TookTrueTmp = !TookTrueTmp;
  1940. CondTmp = UO->getSubExpr();
  1941. continue;
  1942. }
  1943. break;
  1944. }
  1945. }
  1946. break;
  1947. }
  1948. // Condition too complex to explain? Just say something so that the user
  1949. // knew we've made some path decision at this point.
  1950. // If it is too complex and we know the evaluation of the condition do not
  1951. // repeat the note from 'BugReporter.cpp'
  1952. if (!IsAssuming)
  1953. return nullptr;
  1954. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  1955. if (!Loc.isValid() || !Loc.asLocation().isValid())
  1956. return nullptr;
  1957. return std::make_shared<PathDiagnosticEventPiece>(
  1958. Loc, TookTrue ? GenericTrueMessage : GenericFalseMessage);
  1959. }
  1960. bool ConditionBRVisitor::patternMatch(const Expr *Ex,
  1961. const Expr *ParentEx,
  1962. raw_ostream &Out,
  1963. BugReporterContext &BRC,
  1964. PathSensitiveBugReport &report,
  1965. const ExplodedNode *N,
  1966. Optional<bool> &prunable,
  1967. bool IsSameFieldName) {
  1968. const Expr *OriginalExpr = Ex;
  1969. Ex = Ex->IgnoreParenCasts();
  1970. if (isa<GNUNullExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) ||
  1971. isa<CXXBoolLiteralExpr>(Ex) || isa<IntegerLiteral>(Ex) ||
  1972. isa<FloatingLiteral>(Ex)) {
  1973. // Use heuristics to determine if the expression is a macro
  1974. // expanding to a literal and if so, use the macro's name.
  1975. SourceLocation BeginLoc = OriginalExpr->getBeginLoc();
  1976. SourceLocation EndLoc = OriginalExpr->getEndLoc();
  1977. if (BeginLoc.isMacroID() && EndLoc.isMacroID()) {
  1978. const SourceManager &SM = BRC.getSourceManager();
  1979. const LangOptions &LO = BRC.getASTContext().getLangOpts();
  1980. if (Lexer::isAtStartOfMacroExpansion(BeginLoc, SM, LO) &&
  1981. Lexer::isAtEndOfMacroExpansion(EndLoc, SM, LO)) {
  1982. CharSourceRange R = Lexer::getAsCharRange({BeginLoc, EndLoc}, SM, LO);
  1983. Out << Lexer::getSourceText(R, SM, LO);
  1984. return false;
  1985. }
  1986. }
  1987. }
  1988. if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
  1989. const bool quotes = isa<VarDecl>(DR->getDecl());
  1990. if (quotes) {
  1991. Out << '\'';
  1992. const LocationContext *LCtx = N->getLocationContext();
  1993. const ProgramState *state = N->getState().get();
  1994. if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
  1995. LCtx).getAsRegion()) {
  1996. if (report.isInteresting(R))
  1997. prunable = false;
  1998. else {
  1999. const ProgramState *state = N->getState().get();
  2000. SVal V = state->getSVal(R);
  2001. if (report.isInteresting(V))
  2002. prunable = false;
  2003. }
  2004. }
  2005. }
  2006. Out << DR->getDecl()->getDeclName().getAsString();
  2007. if (quotes)
  2008. Out << '\'';
  2009. return quotes;
  2010. }
  2011. if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
  2012. QualType OriginalTy = OriginalExpr->getType();
  2013. if (OriginalTy->isPointerType()) {
  2014. if (IL->getValue() == 0) {
  2015. Out << "null";
  2016. return false;
  2017. }
  2018. }
  2019. else if (OriginalTy->isObjCObjectPointerType()) {
  2020. if (IL->getValue() == 0) {
  2021. Out << "nil";
  2022. return false;
  2023. }
  2024. }
  2025. Out << IL->getValue();
  2026. return false;
  2027. }
  2028. if (const auto *ME = dyn_cast<MemberExpr>(Ex)) {
  2029. if (!IsSameFieldName)
  2030. Out << "field '" << ME->getMemberDecl()->getName() << '\'';
  2031. else
  2032. Out << '\''
  2033. << Lexer::getSourceText(
  2034. CharSourceRange::getTokenRange(Ex->getSourceRange()),
  2035. BRC.getSourceManager(), BRC.getASTContext().getLangOpts(), 0)
  2036. << '\'';
  2037. }
  2038. return false;
  2039. }
  2040. PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
  2041. const Expr *Cond, const BinaryOperator *BExpr, BugReporterContext &BRC,
  2042. PathSensitiveBugReport &R, const ExplodedNode *N, bool TookTrue,
  2043. bool IsAssuming) {
  2044. bool shouldInvert = false;
  2045. Optional<bool> shouldPrune;
  2046. // Check if the field name of the MemberExprs is ambiguous. Example:
  2047. // " 'a.d' is equal to 'h.d' " in 'test/Analysis/null-deref-path-notes.cpp'.
  2048. bool IsSameFieldName = false;
  2049. const auto *LhsME = dyn_cast<MemberExpr>(BExpr->getLHS()->IgnoreParenCasts());
  2050. const auto *RhsME = dyn_cast<MemberExpr>(BExpr->getRHS()->IgnoreParenCasts());
  2051. if (LhsME && RhsME)
  2052. IsSameFieldName =
  2053. LhsME->getMemberDecl()->getName() == RhsME->getMemberDecl()->getName();
  2054. SmallString<128> LhsString, RhsString;
  2055. {
  2056. llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
  2057. const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS, BRC, R,
  2058. N, shouldPrune, IsSameFieldName);
  2059. const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS, BRC, R,
  2060. N, shouldPrune, IsSameFieldName);
  2061. shouldInvert = !isVarLHS && isVarRHS;
  2062. }
  2063. BinaryOperator::Opcode Op = BExpr->getOpcode();
  2064. if (BinaryOperator::isAssignmentOp(Op)) {
  2065. // For assignment operators, all that we care about is that the LHS
  2066. // evaluates to "true" or "false".
  2067. return VisitConditionVariable(LhsString, BExpr->getLHS(), BRC, R, N,
  2068. TookTrue);
  2069. }
  2070. // For non-assignment operations, we require that we can understand
  2071. // both the LHS and RHS.
  2072. if (LhsString.empty() || RhsString.empty() ||
  2073. !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
  2074. return nullptr;
  2075. // Should we invert the strings if the LHS is not a variable name?
  2076. SmallString<256> buf;
  2077. llvm::raw_svector_ostream Out(buf);
  2078. Out << (IsAssuming ? "Assuming " : "")
  2079. << (shouldInvert ? RhsString : LhsString) << " is ";
  2080. // Do we need to invert the opcode?
  2081. if (shouldInvert)
  2082. switch (Op) {
  2083. default: break;
  2084. case BO_LT: Op = BO_GT; break;
  2085. case BO_GT: Op = BO_LT; break;
  2086. case BO_LE: Op = BO_GE; break;
  2087. case BO_GE: Op = BO_LE; break;
  2088. }
  2089. if (!TookTrue)
  2090. switch (Op) {
  2091. case BO_EQ: Op = BO_NE; break;
  2092. case BO_NE: Op = BO_EQ; break;
  2093. case BO_LT: Op = BO_GE; break;
  2094. case BO_GT: Op = BO_LE; break;
  2095. case BO_LE: Op = BO_GT; break;
  2096. case BO_GE: Op = BO_LT; break;
  2097. default:
  2098. return nullptr;
  2099. }
  2100. switch (Op) {
  2101. case BO_EQ:
  2102. Out << "equal to ";
  2103. break;
  2104. case BO_NE:
  2105. Out << "not equal to ";
  2106. break;
  2107. default:
  2108. Out << BinaryOperator::getOpcodeStr(Op) << ' ';
  2109. break;
  2110. }
  2111. Out << (shouldInvert ? LhsString : RhsString);
  2112. const LocationContext *LCtx = N->getLocationContext();
  2113. const SourceManager &SM = BRC.getSourceManager();
  2114. if (isVarAnInterestingCondition(BExpr->getLHS(), N, &R) ||
  2115. isVarAnInterestingCondition(BExpr->getRHS(), N, &R))
  2116. Out << WillBeUsedForACondition;
  2117. // Convert 'field ...' to 'Field ...' if it is a MemberExpr.
  2118. std::string Message = Out.str();
  2119. Message[0] = toupper(Message[0]);
  2120. // If we know the value create a pop-up note to the value part of 'BExpr'.
  2121. if (!IsAssuming) {
  2122. PathDiagnosticLocation Loc;
  2123. if (!shouldInvert) {
  2124. if (LhsME && LhsME->getMemberLoc().isValid())
  2125. Loc = PathDiagnosticLocation(LhsME->getMemberLoc(), SM);
  2126. else
  2127. Loc = PathDiagnosticLocation(BExpr->getLHS(), SM, LCtx);
  2128. } else {
  2129. if (RhsME && RhsME->getMemberLoc().isValid())
  2130. Loc = PathDiagnosticLocation(RhsME->getMemberLoc(), SM);
  2131. else
  2132. Loc = PathDiagnosticLocation(BExpr->getRHS(), SM, LCtx);
  2133. }
  2134. return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Message);
  2135. }
  2136. PathDiagnosticLocation Loc(Cond, SM, LCtx);
  2137. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Message);
  2138. if (shouldPrune.hasValue())
  2139. event->setPrunable(shouldPrune.getValue());
  2140. return event;
  2141. }
  2142. PathDiagnosticPieceRef ConditionBRVisitor::VisitConditionVariable(
  2143. StringRef LhsString, const Expr *CondVarExpr, BugReporterContext &BRC,
  2144. PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue) {
  2145. // FIXME: If there's already a constraint tracker for this variable,
  2146. // we shouldn't emit anything here (c.f. the double note in
  2147. // test/Analysis/inlining/path-notes.c)
  2148. SmallString<256> buf;
  2149. llvm::raw_svector_ostream Out(buf);
  2150. Out << "Assuming " << LhsString << " is ";
  2151. if (!printValue(CondVarExpr, Out, N, TookTrue, /*IsAssuming=*/true))
  2152. return nullptr;
  2153. const LocationContext *LCtx = N->getLocationContext();
  2154. PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
  2155. if (isVarAnInterestingCondition(CondVarExpr, N, &report))
  2156. Out << WillBeUsedForACondition;
  2157. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  2158. if (isInterestingExpr(CondVarExpr, N, &report))
  2159. event->setPrunable(false);
  2160. return event;
  2161. }
  2162. PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
  2163. const Expr *Cond, const DeclRefExpr *DRE, BugReporterContext &BRC,
  2164. PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
  2165. bool IsAssuming) {
  2166. const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
  2167. if (!VD)
  2168. return nullptr;
  2169. SmallString<256> Buf;
  2170. llvm::raw_svector_ostream Out(Buf);
  2171. Out << (IsAssuming ? "Assuming '" : "'") << VD->getDeclName() << "' is ";
  2172. if (!printValue(DRE, Out, N, TookTrue, IsAssuming))
  2173. return nullptr;
  2174. const LocationContext *LCtx = N->getLocationContext();
  2175. if (isVarAnInterestingCondition(DRE, N, &report))
  2176. Out << WillBeUsedForACondition;
  2177. // If we know the value create a pop-up note to the 'DRE'.
  2178. if (!IsAssuming) {
  2179. PathDiagnosticLocation Loc(DRE, BRC.getSourceManager(), LCtx);
  2180. return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
  2181. }
  2182. PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
  2183. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  2184. if (isInterestingExpr(DRE, N, &report))
  2185. event->setPrunable(false);
  2186. return std::move(event);
  2187. }
  2188. PathDiagnosticPieceRef ConditionBRVisitor::VisitTrueTest(
  2189. const Expr *Cond, const MemberExpr *ME, BugReporterContext &BRC,
  2190. PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
  2191. bool IsAssuming) {
  2192. SmallString<256> Buf;
  2193. llvm::raw_svector_ostream Out(Buf);
  2194. Out << (IsAssuming ? "Assuming field '" : "Field '")
  2195. << ME->getMemberDecl()->getName() << "' is ";
  2196. if (!printValue(ME, Out, N, TookTrue, IsAssuming))
  2197. return nullptr;
  2198. const LocationContext *LCtx = N->getLocationContext();
  2199. PathDiagnosticLocation Loc;
  2200. // If we know the value create a pop-up note to the member of the MemberExpr.
  2201. if (!IsAssuming && ME->getMemberLoc().isValid())
  2202. Loc = PathDiagnosticLocation(ME->getMemberLoc(), BRC.getSourceManager());
  2203. else
  2204. Loc = PathDiagnosticLocation(Cond, BRC.getSourceManager(), LCtx);
  2205. if (!Loc.isValid() || !Loc.asLocation().isValid())
  2206. return nullptr;
  2207. if (isVarAnInterestingCondition(ME, N, &report))
  2208. Out << WillBeUsedForACondition;
  2209. // If we know the value create a pop-up note.
  2210. if (!IsAssuming)
  2211. return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
  2212. auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
  2213. if (isInterestingExpr(ME, N, &report))
  2214. event->setPrunable(false);
  2215. return event;
  2216. }
  2217. bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out,
  2218. const ExplodedNode *N, bool TookTrue,
  2219. bool IsAssuming) {
  2220. QualType Ty = CondVarExpr->getType();
  2221. if (Ty->isPointerType()) {
  2222. Out << (TookTrue ? "non-null" : "null");
  2223. return true;
  2224. }
  2225. if (Ty->isObjCObjectPointerType()) {
  2226. Out << (TookTrue ? "non-nil" : "nil");
  2227. return true;
  2228. }
  2229. if (!Ty->isIntegralOrEnumerationType())
  2230. return false;
  2231. Optional<const llvm::APSInt *> IntValue;
  2232. if (!IsAssuming)
  2233. IntValue = getConcreteIntegerValue(CondVarExpr, N);
  2234. if (IsAssuming || !IntValue.hasValue()) {
  2235. if (Ty->isBooleanType())
  2236. Out << (TookTrue ? "true" : "false");
  2237. else
  2238. Out << (TookTrue ? "not equal to 0" : "0");
  2239. } else {
  2240. if (Ty->isBooleanType())
  2241. Out << (IntValue.getValue()->getBoolValue() ? "true" : "false");
  2242. else
  2243. Out << *IntValue.getValue();
  2244. }
  2245. return true;
  2246. }
  2247. constexpr llvm::StringLiteral ConditionBRVisitor::GenericTrueMessage;
  2248. constexpr llvm::StringLiteral ConditionBRVisitor::GenericFalseMessage;
  2249. bool ConditionBRVisitor::isPieceMessageGeneric(
  2250. const PathDiagnosticPiece *Piece) {
  2251. return Piece->getString() == GenericTrueMessage ||
  2252. Piece->getString() == GenericFalseMessage;
  2253. }
  2254. //===----------------------------------------------------------------------===//
  2255. // Implementation of LikelyFalsePositiveSuppressionBRVisitor.
  2256. //===----------------------------------------------------------------------===//
  2257. void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
  2258. BugReporterContext &BRC, const ExplodedNode *N,
  2259. PathSensitiveBugReport &BR) {
  2260. // Here we suppress false positives coming from system headers. This list is
  2261. // based on known issues.
  2262. const AnalyzerOptions &Options = BRC.getAnalyzerOptions();
  2263. const Decl *D = N->getLocationContext()->getDecl();
  2264. if (AnalysisDeclContext::isInStdNamespace(D)) {
  2265. // Skip reports within the 'std' namespace. Although these can sometimes be
  2266. // the user's fault, we currently don't report them very well, and
  2267. // Note that this will not help for any other data structure libraries, like
  2268. // TR1, Boost, or llvm/ADT.
  2269. if (Options.ShouldSuppressFromCXXStandardLibrary) {
  2270. BR.markInvalid(getTag(), nullptr);
  2271. return;
  2272. } else {
  2273. // If the complete 'std' suppression is not enabled, suppress reports
  2274. // from the 'std' namespace that are known to produce false positives.
  2275. // The analyzer issues a false use-after-free when std::list::pop_front
  2276. // or std::list::pop_back are called multiple times because we cannot
  2277. // reason about the internal invariants of the data structure.
  2278. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  2279. const CXXRecordDecl *CD = MD->getParent();
  2280. if (CD->getName() == "list") {
  2281. BR.markInvalid(getTag(), nullptr);
  2282. return;
  2283. }
  2284. }
  2285. // The analyzer issues a false positive when the constructor of
  2286. // std::__independent_bits_engine from algorithms is used.
  2287. if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
  2288. const CXXRecordDecl *CD = MD->getParent();
  2289. if (CD->getName() == "__independent_bits_engine") {
  2290. BR.markInvalid(getTag(), nullptr);
  2291. return;
  2292. }
  2293. }
  2294. for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
  2295. LCtx = LCtx->getParent()) {
  2296. const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
  2297. if (!MD)
  2298. continue;
  2299. const CXXRecordDecl *CD = MD->getParent();
  2300. // The analyzer issues a false positive on
  2301. // std::basic_string<uint8_t> v; v.push_back(1);
  2302. // and
  2303. // std::u16string s; s += u'a';
  2304. // because we cannot reason about the internal invariants of the
  2305. // data structure.
  2306. if (CD->getName() == "basic_string") {
  2307. BR.markInvalid(getTag(), nullptr);
  2308. return;
  2309. }
  2310. // The analyzer issues a false positive on
  2311. // std::shared_ptr<int> p(new int(1)); p = nullptr;
  2312. // because it does not reason properly about temporary destructors.
  2313. if (CD->getName() == "shared_ptr") {
  2314. BR.markInvalid(getTag(), nullptr);
  2315. return;
  2316. }
  2317. }
  2318. }
  2319. }
  2320. // Skip reports within the sys/queue.h macros as we do not have the ability to
  2321. // reason about data structure shapes.
  2322. const SourceManager &SM = BRC.getSourceManager();
  2323. FullSourceLoc Loc = BR.getLocation().asLocation();
  2324. while (Loc.isMacroID()) {
  2325. Loc = Loc.getSpellingLoc();
  2326. if (SM.getFilename(Loc).endswith("sys/queue.h")) {
  2327. BR.markInvalid(getTag(), nullptr);
  2328. return;
  2329. }
  2330. }
  2331. }
  2332. //===----------------------------------------------------------------------===//
  2333. // Implementation of UndefOrNullArgVisitor.
  2334. //===----------------------------------------------------------------------===//
  2335. PathDiagnosticPieceRef
  2336. UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
  2337. PathSensitiveBugReport &BR) {
  2338. ProgramStateRef State = N->getState();
  2339. ProgramPoint ProgLoc = N->getLocation();
  2340. // We are only interested in visiting CallEnter nodes.
  2341. Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
  2342. if (!CEnter)
  2343. return nullptr;
  2344. // Check if one of the arguments is the region the visitor is tracking.
  2345. CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
  2346. CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
  2347. unsigned Idx = 0;
  2348. ArrayRef<ParmVarDecl *> parms = Call->parameters();
  2349. for (const auto ParamDecl : parms) {
  2350. const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
  2351. ++Idx;
  2352. // Are we tracking the argument or its subregion?
  2353. if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
  2354. continue;
  2355. // Check the function parameter type.
  2356. assert(ParamDecl && "Formal parameter has no decl?");
  2357. QualType T = ParamDecl->getType();
  2358. if (!(T->isAnyPointerType() || T->isReferenceType())) {
  2359. // Function can only change the value passed in by address.
  2360. continue;
  2361. }
  2362. // If it is a const pointer value, the function does not intend to
  2363. // change the value.
  2364. if (T->getPointeeType().isConstQualified())
  2365. continue;
  2366. // Mark the call site (LocationContext) as interesting if the value of the
  2367. // argument is undefined or '0'/'NULL'.
  2368. SVal BoundVal = State->getSVal(R);
  2369. if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
  2370. BR.markInteresting(CEnter->getCalleeContext());
  2371. return nullptr;
  2372. }
  2373. }
  2374. return nullptr;
  2375. }
  2376. //===----------------------------------------------------------------------===//
  2377. // Implementation of FalsePositiveRefutationBRVisitor.
  2378. //===----------------------------------------------------------------------===//
  2379. FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor()
  2380. : Constraints(ConstraintRangeTy::Factory().getEmptyMap()) {}
  2381. void FalsePositiveRefutationBRVisitor::finalizeVisitor(
  2382. BugReporterContext &BRC, const ExplodedNode *EndPathNode,
  2383. PathSensitiveBugReport &BR) {
  2384. // Collect new constraints
  2385. VisitNode(EndPathNode, BRC, BR);
  2386. // Create a refutation manager
  2387. llvm::SMTSolverRef RefutationSolver = llvm::CreateZ3Solver();
  2388. ASTContext &Ctx = BRC.getASTContext();
  2389. // Add constraints to the solver
  2390. for (const auto &I : Constraints) {
  2391. const SymbolRef Sym = I.first;
  2392. auto RangeIt = I.second.begin();
  2393. llvm::SMTExprRef Constraints = SMTConv::getRangeExpr(
  2394. RefutationSolver, Ctx, Sym, RangeIt->From(), RangeIt->To(),
  2395. /*InRange=*/true);
  2396. while ((++RangeIt) != I.second.end()) {
  2397. Constraints = RefutationSolver->mkOr(
  2398. Constraints, SMTConv::getRangeExpr(RefutationSolver, Ctx, Sym,
  2399. RangeIt->From(), RangeIt->To(),
  2400. /*InRange=*/true));
  2401. }
  2402. RefutationSolver->addConstraint(Constraints);
  2403. }
  2404. // And check for satisfiability
  2405. Optional<bool> isSat = RefutationSolver->check();
  2406. if (!isSat.hasValue())
  2407. return;
  2408. if (!isSat.getValue())
  2409. BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext());
  2410. }
  2411. PathDiagnosticPieceRef FalsePositiveRefutationBRVisitor::VisitNode(
  2412. const ExplodedNode *N, BugReporterContext &, PathSensitiveBugReport &) {
  2413. // Collect new constraints
  2414. const ConstraintRangeTy &NewCs = N->getState()->get<ConstraintRange>();
  2415. ConstraintRangeTy::Factory &CF =
  2416. N->getState()->get_context<ConstraintRange>();
  2417. // Add constraints if we don't have them yet
  2418. for (auto const &C : NewCs) {
  2419. const SymbolRef &Sym = C.first;
  2420. if (!Constraints.contains(Sym)) {
  2421. Constraints = CF.add(Constraints, Sym, C.second);
  2422. }
  2423. }
  2424. return nullptr;
  2425. }
  2426. void FalsePositiveRefutationBRVisitor::Profile(
  2427. llvm::FoldingSetNodeID &ID) const {
  2428. static int Tag = 0;
  2429. ID.AddPointer(&Tag);
  2430. }
  2431. //===----------------------------------------------------------------------===//
  2432. // Implementation of TagVisitor.
  2433. //===----------------------------------------------------------------------===//
  2434. int NoteTag::Kind = 0;
  2435. void TagVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
  2436. static int Tag = 0;
  2437. ID.AddPointer(&Tag);
  2438. }
  2439. PathDiagnosticPieceRef TagVisitor::VisitNode(const ExplodedNode *N,
  2440. BugReporterContext &BRC,
  2441. PathSensitiveBugReport &R) {
  2442. ProgramPoint PP = N->getLocation();
  2443. const NoteTag *T = dyn_cast_or_null<NoteTag>(PP.getTag());
  2444. if (!T)
  2445. return nullptr;
  2446. if (Optional<std::string> Msg = T->generateMessage(BRC, R)) {
  2447. PathDiagnosticLocation Loc =
  2448. PathDiagnosticLocation::create(PP, BRC.getSourceManager());
  2449. auto Piece = std::make_shared<PathDiagnosticEventPiece>(Loc, *Msg);
  2450. Piece->setPrunable(T->isPrunable());
  2451. return Piece;
  2452. }
  2453. return nullptr;
  2454. }