BugReporterVisitors.cpp 103 KB

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