ExprEngine.cpp 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536
  1. //=-- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ---*- C++ -*-=
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines a meta-engine for path-sensitive dataflow analysis that
  11. // is built on GREngine, but provides the boilerplate to execute transfer
  12. // functions and build the ExplodedGraph at the expression level.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #define DEBUG_TYPE "ExprEngine"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  17. #include "PrettyStackTraceLocationContext.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/ParentMap.h"
  20. #include "clang/AST/StmtCXX.h"
  21. #include "clang/AST/StmtObjC.h"
  22. #include "clang/Basic/Builtins.h"
  23. #include "clang/Basic/PrettyStackTrace.h"
  24. #include "clang/Basic/SourceManager.h"
  25. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  26. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  27. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  28. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  29. #include "llvm/ADT/ImmutableList.h"
  30. #include "llvm/ADT/Statistic.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #ifndef NDEBUG
  33. #include "llvm/Support/GraphWriter.h"
  34. #endif
  35. using namespace clang;
  36. using namespace ento;
  37. using llvm::APSInt;
  38. STATISTIC(NumRemoveDeadBindings,
  39. "The # of times RemoveDeadBindings is called");
  40. STATISTIC(NumMaxBlockCountReached,
  41. "The # of aborted paths due to reaching the maximum block count in "
  42. "a top level function");
  43. STATISTIC(NumMaxBlockCountReachedInInlined,
  44. "The # of aborted paths due to reaching the maximum block count in "
  45. "an inlined function");
  46. STATISTIC(NumTimesRetriedWithoutInlining,
  47. "The # of times we re-evaluated a call without inlining");
  48. //===----------------------------------------------------------------------===//
  49. // Engine construction and deletion.
  50. //===----------------------------------------------------------------------===//
  51. ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
  52. SetOfConstDecls *VisitedCalleesIn,
  53. FunctionSummariesTy *FS,
  54. InliningModes HowToInlineIn)
  55. : AMgr(mgr),
  56. AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
  57. Engine(*this, FS),
  58. G(Engine.getGraph()),
  59. StateMgr(getContext(), mgr.getStoreManagerCreator(),
  60. mgr.getConstraintManagerCreator(), G.getAllocator(),
  61. this),
  62. SymMgr(StateMgr.getSymbolManager()),
  63. svalBuilder(StateMgr.getSValBuilder()),
  64. currStmtIdx(0), currBldrCtx(0),
  65. ObjCNoRet(mgr.getASTContext()),
  66. ObjCGCEnabled(gcEnabled), BR(mgr, *this),
  67. VisitedCallees(VisitedCalleesIn),
  68. HowToInline(HowToInlineIn)
  69. {
  70. unsigned TrimInterval = mgr.options.getGraphTrimInterval();
  71. if (TrimInterval != 0) {
  72. // Enable eager node reclaimation when constructing the ExplodedGraph.
  73. G.enableNodeReclamation(TrimInterval);
  74. }
  75. }
  76. ExprEngine::~ExprEngine() {
  77. BR.FlushReports();
  78. }
  79. //===----------------------------------------------------------------------===//
  80. // Utility methods.
  81. //===----------------------------------------------------------------------===//
  82. ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
  83. ProgramStateRef state = StateMgr.getInitialState(InitLoc);
  84. const Decl *D = InitLoc->getDecl();
  85. // Preconditions.
  86. // FIXME: It would be nice if we had a more general mechanism to add
  87. // such preconditions. Some day.
  88. do {
  89. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  90. // Precondition: the first argument of 'main' is an integer guaranteed
  91. // to be > 0.
  92. const IdentifierInfo *II = FD->getIdentifier();
  93. if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
  94. break;
  95. const ParmVarDecl *PD = FD->getParamDecl(0);
  96. QualType T = PD->getType();
  97. const BuiltinType *BT = dyn_cast<BuiltinType>(T);
  98. if (!BT || !BT->isInteger())
  99. break;
  100. const MemRegion *R = state->getRegion(PD, InitLoc);
  101. if (!R)
  102. break;
  103. SVal V = state->getSVal(loc::MemRegionVal(R));
  104. SVal Constraint_untested = evalBinOp(state, BO_GT, V,
  105. svalBuilder.makeZeroVal(T),
  106. getContext().IntTy);
  107. Optional<DefinedOrUnknownSVal> Constraint =
  108. Constraint_untested.getAs<DefinedOrUnknownSVal>();
  109. if (!Constraint)
  110. break;
  111. if (ProgramStateRef newState = state->assume(*Constraint, true))
  112. state = newState;
  113. }
  114. break;
  115. }
  116. while (0);
  117. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  118. // Precondition: 'self' is always non-null upon entry to an Objective-C
  119. // method.
  120. const ImplicitParamDecl *SelfD = MD->getSelfDecl();
  121. const MemRegion *R = state->getRegion(SelfD, InitLoc);
  122. SVal V = state->getSVal(loc::MemRegionVal(R));
  123. if (Optional<Loc> LV = V.getAs<Loc>()) {
  124. // Assume that the pointer value in 'self' is non-null.
  125. state = state->assume(*LV, true);
  126. assert(state && "'self' cannot be null");
  127. }
  128. }
  129. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  130. if (!MD->isStatic()) {
  131. // Precondition: 'this' is always non-null upon entry to the
  132. // top-level function. This is our starting assumption for
  133. // analyzing an "open" program.
  134. const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
  135. if (SFC->getParent() == 0) {
  136. loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
  137. SVal V = state->getSVal(L);
  138. if (Optional<Loc> LV = V.getAs<Loc>()) {
  139. state = state->assume(*LV, true);
  140. assert(state && "'this' cannot be null");
  141. }
  142. }
  143. }
  144. }
  145. return state;
  146. }
  147. ProgramStateRef
  148. ExprEngine::createTemporaryRegionIfNeeded(ProgramStateRef State,
  149. const LocationContext *LC,
  150. const Expr *Ex,
  151. const Expr *Result) {
  152. SVal V = State->getSVal(Ex, LC);
  153. if (!Result) {
  154. // If we don't have an explicit result expression, we're in "if needed"
  155. // mode. Only create a region if the current value is a NonLoc.
  156. if (!V.getAs<NonLoc>())
  157. return State;
  158. Result = Ex;
  159. } else {
  160. // We need to create a region no matter what. For sanity, make sure we don't
  161. // try to stuff a Loc into a non-pointer temporary region.
  162. assert(!V.getAs<Loc>() || Loc::isLocType(Result->getType()) ||
  163. Result->getType()->isMemberPointerType());
  164. }
  165. ProgramStateManager &StateMgr = State->getStateManager();
  166. MemRegionManager &MRMgr = StateMgr.getRegionManager();
  167. StoreManager &StoreMgr = StateMgr.getStoreManager();
  168. // We need to be careful about treating a derived type's value as
  169. // bindings for a base type. Unless we're creating a temporary pointer region,
  170. // start by stripping and recording base casts.
  171. SmallVector<const CastExpr *, 4> Casts;
  172. const Expr *Inner = Ex->IgnoreParens();
  173. if (!Loc::isLocType(Result->getType())) {
  174. while (const CastExpr *CE = dyn_cast<CastExpr>(Inner)) {
  175. if (CE->getCastKind() == CK_DerivedToBase ||
  176. CE->getCastKind() == CK_UncheckedDerivedToBase)
  177. Casts.push_back(CE);
  178. else if (CE->getCastKind() != CK_NoOp)
  179. break;
  180. Inner = CE->getSubExpr()->IgnoreParens();
  181. }
  182. }
  183. // Create a temporary object region for the inner expression (which may have
  184. // a more derived type) and bind the value into it.
  185. const TypedValueRegion *TR = NULL;
  186. if (const MaterializeTemporaryExpr *MT =
  187. dyn_cast<MaterializeTemporaryExpr>(Result)) {
  188. StorageDuration SD = MT->getStorageDuration();
  189. // If this object is bound to a reference with static storage duration, we
  190. // put it in a different region to prevent "address leakage" warnings.
  191. if (SD == SD_Static || SD == SD_Thread)
  192. TR = MRMgr.getCXXStaticTempObjectRegion(Inner);
  193. }
  194. if (!TR)
  195. TR = MRMgr.getCXXTempObjectRegion(Inner, LC);
  196. SVal Reg = loc::MemRegionVal(TR);
  197. if (V.isUnknown())
  198. V = getSValBuilder().conjureSymbolVal(Result, LC, TR->getValueType(),
  199. currBldrCtx->blockCount());
  200. State = State->bindLoc(Reg, V);
  201. // Re-apply the casts (from innermost to outermost) for type sanity.
  202. for (SmallVectorImpl<const CastExpr *>::reverse_iterator I = Casts.rbegin(),
  203. E = Casts.rend();
  204. I != E; ++I) {
  205. Reg = StoreMgr.evalDerivedToBase(Reg, *I);
  206. }
  207. State = State->BindExpr(Result, LC, Reg);
  208. return State;
  209. }
  210. //===----------------------------------------------------------------------===//
  211. // Top-level transfer function logic (Dispatcher).
  212. //===----------------------------------------------------------------------===//
  213. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  214. /// logic for handling assumptions on symbolic values.
  215. ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
  216. SVal cond, bool assumption) {
  217. return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
  218. }
  219. bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
  220. return getCheckerManager().wantsRegionChangeUpdate(state);
  221. }
  222. ProgramStateRef
  223. ExprEngine::processRegionChanges(ProgramStateRef state,
  224. const InvalidatedSymbols *invalidated,
  225. ArrayRef<const MemRegion *> Explicits,
  226. ArrayRef<const MemRegion *> Regions,
  227. const CallEvent *Call) {
  228. return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
  229. Explicits, Regions, Call);
  230. }
  231. void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
  232. const char *NL, const char *Sep) {
  233. getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
  234. }
  235. void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
  236. getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
  237. }
  238. void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
  239. unsigned StmtIdx, NodeBuilderContext *Ctx) {
  240. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  241. currStmtIdx = StmtIdx;
  242. currBldrCtx = Ctx;
  243. switch (E.getKind()) {
  244. case CFGElement::Statement:
  245. ProcessStmt(const_cast<Stmt*>(E.castAs<CFGStmt>().getStmt()), Pred);
  246. return;
  247. case CFGElement::Initializer:
  248. ProcessInitializer(E.castAs<CFGInitializer>().getInitializer(), Pred);
  249. return;
  250. case CFGElement::AutomaticObjectDtor:
  251. case CFGElement::DeleteDtor:
  252. case CFGElement::BaseDtor:
  253. case CFGElement::MemberDtor:
  254. case CFGElement::TemporaryDtor:
  255. ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
  256. return;
  257. }
  258. }
  259. static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
  260. const CFGStmt S,
  261. const ExplodedNode *Pred,
  262. const LocationContext *LC) {
  263. // Are we never purging state values?
  264. if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
  265. return false;
  266. // Is this the beginning of a basic block?
  267. if (Pred->getLocation().getAs<BlockEntrance>())
  268. return true;
  269. // Is this on a non-expression?
  270. if (!isa<Expr>(S.getStmt()))
  271. return true;
  272. // Run before processing a call.
  273. if (CallEvent::isCallStmt(S.getStmt()))
  274. return true;
  275. // Is this an expression that is consumed by another expression? If so,
  276. // postpone cleaning out the state.
  277. ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
  278. return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
  279. }
  280. void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
  281. const Stmt *ReferenceStmt,
  282. const LocationContext *LC,
  283. const Stmt *DiagnosticStmt,
  284. ProgramPoint::Kind K) {
  285. assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
  286. ReferenceStmt == 0 || isa<ReturnStmt>(ReferenceStmt))
  287. && "PostStmt is not generally supported by the SymbolReaper yet");
  288. assert(LC && "Must pass the current (or expiring) LocationContext");
  289. if (!DiagnosticStmt) {
  290. DiagnosticStmt = ReferenceStmt;
  291. assert(DiagnosticStmt && "Required for clearing a LocationContext");
  292. }
  293. NumRemoveDeadBindings++;
  294. ProgramStateRef CleanedState = Pred->getState();
  295. // LC is the location context being destroyed, but SymbolReaper wants a
  296. // location context that is still live. (If this is the top-level stack
  297. // frame, this will be null.)
  298. if (!ReferenceStmt) {
  299. assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
  300. "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
  301. LC = LC->getParent();
  302. }
  303. const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : 0;
  304. SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
  305. getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
  306. // Create a state in which dead bindings are removed from the environment
  307. // and the store. TODO: The function should just return new env and store,
  308. // not a new state.
  309. CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
  310. // Process any special transfer function for dead symbols.
  311. // A tag to track convenience transitions, which can be removed at cleanup.
  312. static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node");
  313. if (!SymReaper.hasDeadSymbols()) {
  314. // Generate a CleanedNode that has the environment and store cleaned
  315. // up. Since no symbols are dead, we can optimize and not clean out
  316. // the constraint manager.
  317. StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
  318. Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
  319. } else {
  320. // Call checkers with the non-cleaned state so that they could query the
  321. // values of the soon to be dead symbols.
  322. ExplodedNodeSet CheckedSet;
  323. getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
  324. DiagnosticStmt, *this, K);
  325. // For each node in CheckedSet, generate CleanedNodes that have the
  326. // environment, the store, and the constraints cleaned up but have the
  327. // user-supplied states as the predecessors.
  328. StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
  329. for (ExplodedNodeSet::const_iterator
  330. I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
  331. ProgramStateRef CheckerState = (*I)->getState();
  332. // The constraint manager has not been cleaned up yet, so clean up now.
  333. CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
  334. SymReaper);
  335. assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
  336. "Checkers are not allowed to modify the Environment as a part of "
  337. "checkDeadSymbols processing.");
  338. assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
  339. "Checkers are not allowed to modify the Store as a part of "
  340. "checkDeadSymbols processing.");
  341. // Create a state based on CleanedState with CheckerState GDM and
  342. // generate a transition to that state.
  343. ProgramStateRef CleanedCheckerSt =
  344. StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
  345. Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K);
  346. }
  347. }
  348. }
  349. void ExprEngine::ProcessStmt(const CFGStmt S,
  350. ExplodedNode *Pred) {
  351. // Reclaim any unnecessary nodes in the ExplodedGraph.
  352. G.reclaimRecentlyAllocatedNodes();
  353. const Stmt *currStmt = S.getStmt();
  354. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  355. currStmt->getLocStart(),
  356. "Error evaluating statement");
  357. // Remove dead bindings and symbols.
  358. ExplodedNodeSet CleanedStates;
  359. if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
  360. removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
  361. } else
  362. CleanedStates.Add(Pred);
  363. // Visit the statement.
  364. ExplodedNodeSet Dst;
  365. for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
  366. E = CleanedStates.end(); I != E; ++I) {
  367. ExplodedNodeSet DstI;
  368. // Visit the statement.
  369. Visit(currStmt, *I, DstI);
  370. Dst.insert(DstI);
  371. }
  372. // Enqueue the new nodes onto the work list.
  373. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  374. }
  375. void ExprEngine::ProcessInitializer(const CFGInitializer Init,
  376. ExplodedNode *Pred) {
  377. const CXXCtorInitializer *BMI = Init.getInitializer();
  378. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  379. BMI->getSourceLocation(),
  380. "Error evaluating initializer");
  381. // We don't clean up dead bindings here.
  382. const StackFrameContext *stackFrame =
  383. cast<StackFrameContext>(Pred->getLocationContext());
  384. const CXXConstructorDecl *decl =
  385. cast<CXXConstructorDecl>(stackFrame->getDecl());
  386. ProgramStateRef State = Pred->getState();
  387. SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
  388. ExplodedNodeSet Tmp(Pred);
  389. SVal FieldLoc;
  390. // Evaluate the initializer, if necessary
  391. if (BMI->isAnyMemberInitializer()) {
  392. // Constructors build the object directly in the field,
  393. // but non-objects must be copied in from the initializer.
  394. const Expr *Init = BMI->getInit()->IgnoreImplicit();
  395. if (!isa<CXXConstructExpr>(Init)) {
  396. const ValueDecl *Field;
  397. if (BMI->isIndirectMemberInitializer()) {
  398. Field = BMI->getIndirectMember();
  399. FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
  400. } else {
  401. Field = BMI->getMember();
  402. FieldLoc = State->getLValue(BMI->getMember(), thisVal);
  403. }
  404. SVal InitVal;
  405. if (BMI->getNumArrayIndices() > 0) {
  406. // Handle arrays of trivial type. We can represent this with a
  407. // primitive load/copy from the base array region.
  408. const ArraySubscriptExpr *ASE;
  409. while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
  410. Init = ASE->getBase()->IgnoreImplicit();
  411. SVal LValue = State->getSVal(Init, stackFrame);
  412. if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
  413. InitVal = State->getSVal(*LValueLoc);
  414. // If we fail to get the value for some reason, use a symbolic value.
  415. if (InitVal.isUnknownOrUndef()) {
  416. SValBuilder &SVB = getSValBuilder();
  417. InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
  418. Field->getType(),
  419. currBldrCtx->blockCount());
  420. }
  421. } else {
  422. InitVal = State->getSVal(BMI->getInit(), stackFrame);
  423. }
  424. assert(Tmp.size() == 1 && "have not generated any new nodes yet");
  425. assert(*Tmp.begin() == Pred && "have not generated any new nodes yet");
  426. Tmp.clear();
  427. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  428. evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
  429. }
  430. } else {
  431. assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
  432. // We already did all the work when visiting the CXXConstructExpr.
  433. }
  434. // Construct PostInitializer nodes whether the state changed or not,
  435. // so that the diagnostics don't get confused.
  436. PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
  437. ExplodedNodeSet Dst;
  438. NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  439. for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) {
  440. ExplodedNode *N = *I;
  441. Bldr.generateNode(PP, N->getState(), N);
  442. }
  443. // Enqueue the new nodes onto the work list.
  444. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  445. }
  446. void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
  447. ExplodedNode *Pred) {
  448. ExplodedNodeSet Dst;
  449. switch (D.getKind()) {
  450. case CFGElement::AutomaticObjectDtor:
  451. ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
  452. break;
  453. case CFGElement::BaseDtor:
  454. ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
  455. break;
  456. case CFGElement::MemberDtor:
  457. ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
  458. break;
  459. case CFGElement::TemporaryDtor:
  460. ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
  461. break;
  462. case CFGElement::DeleteDtor:
  463. ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
  464. break;
  465. default:
  466. llvm_unreachable("Unexpected dtor kind.");
  467. }
  468. // Enqueue the new nodes onto the work list.
  469. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  470. }
  471. void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
  472. ExplodedNode *Pred,
  473. ExplodedNodeSet &Dst) {
  474. const VarDecl *varDecl = Dtor.getVarDecl();
  475. QualType varType = varDecl->getType();
  476. ProgramStateRef state = Pred->getState();
  477. SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
  478. const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
  479. if (const ReferenceType *refType = varType->getAs<ReferenceType>()) {
  480. varType = refType->getPointeeType();
  481. Region = state->getSVal(Region).getAsRegion();
  482. }
  483. VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
  484. Pred, Dst);
  485. }
  486. void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
  487. ExplodedNode *Pred,
  488. ExplodedNodeSet &Dst) {
  489. ProgramStateRef State = Pred->getState();
  490. const LocationContext *LCtx = Pred->getLocationContext();
  491. const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
  492. const Stmt *Arg = DE->getArgument();
  493. SVal ArgVal = State->getSVal(Arg, LCtx);
  494. // If the argument to delete is known to be a null value,
  495. // don't run destructor.
  496. if (State->isNull(ArgVal).isConstrainedTrue()) {
  497. QualType DTy = DE->getDestroyedType();
  498. QualType BTy = getContext().getBaseElementType(DTy);
  499. const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
  500. const CXXDestructorDecl *Dtor = RD->getDestructor();
  501. PostImplicitCall PP(Dtor, DE->getLocStart(), LCtx);
  502. NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  503. Bldr.generateNode(PP, Pred->getState(), Pred);
  504. return;
  505. }
  506. VisitCXXDestructor(DE->getDestroyedType(),
  507. ArgVal.getAsRegion(),
  508. DE, /*IsBase=*/ false,
  509. Pred, Dst);
  510. }
  511. void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
  512. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  513. const LocationContext *LCtx = Pred->getLocationContext();
  514. const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  515. Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
  516. LCtx->getCurrentStackFrame());
  517. SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
  518. // Create the base object region.
  519. const CXXBaseSpecifier *Base = D.getBaseSpecifier();
  520. QualType BaseTy = Base->getType();
  521. SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
  522. Base->isVirtual());
  523. VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
  524. CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst);
  525. }
  526. void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
  527. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  528. const FieldDecl *Member = D.getFieldDecl();
  529. ProgramStateRef State = Pred->getState();
  530. const LocationContext *LCtx = Pred->getLocationContext();
  531. const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  532. Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
  533. LCtx->getCurrentStackFrame());
  534. SVal FieldVal =
  535. State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
  536. VisitCXXDestructor(Member->getType(),
  537. FieldVal.castAs<loc::MemRegionVal>().getRegion(),
  538. CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
  539. }
  540. void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
  541. ExplodedNode *Pred,
  542. ExplodedNodeSet &Dst) {
  543. QualType varType = D.getBindTemporaryExpr()->getSubExpr()->getType();
  544. // FIXME: Inlining of temporary destructors is not supported yet anyway, so we
  545. // just put a NULL region for now. This will need to be changed later.
  546. VisitCXXDestructor(varType, NULL, D.getBindTemporaryExpr(),
  547. /*IsBase=*/ false, Pred, Dst);
  548. }
  549. void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
  550. ExplodedNodeSet &DstTop) {
  551. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  552. S->getLocStart(),
  553. "Error evaluating statement");
  554. ExplodedNodeSet Dst;
  555. StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
  556. assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
  557. switch (S->getStmtClass()) {
  558. // C++ and ARC stuff we don't support yet.
  559. case Expr::ObjCIndirectCopyRestoreExprClass:
  560. case Stmt::CXXDependentScopeMemberExprClass:
  561. case Stmt::CXXTryStmtClass:
  562. case Stmt::CXXTypeidExprClass:
  563. case Stmt::CXXUuidofExprClass:
  564. case Stmt::MSPropertyRefExprClass:
  565. case Stmt::CXXUnresolvedConstructExprClass:
  566. case Stmt::DependentScopeDeclRefExprClass:
  567. case Stmt::UnaryTypeTraitExprClass:
  568. case Stmt::TypeTraitExprClass:
  569. case Stmt::ArrayTypeTraitExprClass:
  570. case Stmt::ExpressionTraitExprClass:
  571. case Stmt::UnresolvedLookupExprClass:
  572. case Stmt::UnresolvedMemberExprClass:
  573. case Stmt::CXXNoexceptExprClass:
  574. case Stmt::PackExpansionExprClass:
  575. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  576. case Stmt::FunctionParmPackExprClass:
  577. case Stmt::SEHTryStmtClass:
  578. case Stmt::SEHExceptStmtClass:
  579. case Stmt::LambdaExprClass:
  580. case Stmt::SEHFinallyStmtClass: {
  581. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  582. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  583. break;
  584. }
  585. case Stmt::ParenExprClass:
  586. llvm_unreachable("ParenExprs already handled.");
  587. case Stmt::GenericSelectionExprClass:
  588. llvm_unreachable("GenericSelectionExprs already handled.");
  589. // Cases that should never be evaluated simply because they shouldn't
  590. // appear in the CFG.
  591. case Stmt::BreakStmtClass:
  592. case Stmt::CaseStmtClass:
  593. case Stmt::CompoundStmtClass:
  594. case Stmt::ContinueStmtClass:
  595. case Stmt::CXXForRangeStmtClass:
  596. case Stmt::DefaultStmtClass:
  597. case Stmt::DoStmtClass:
  598. case Stmt::ForStmtClass:
  599. case Stmt::GotoStmtClass:
  600. case Stmt::IfStmtClass:
  601. case Stmt::IndirectGotoStmtClass:
  602. case Stmt::LabelStmtClass:
  603. case Stmt::NoStmtClass:
  604. case Stmt::NullStmtClass:
  605. case Stmt::SwitchStmtClass:
  606. case Stmt::WhileStmtClass:
  607. case Expr::MSDependentExistsStmtClass:
  608. case Stmt::CapturedStmtClass:
  609. case Stmt::OMPParallelDirectiveClass:
  610. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  611. case Stmt::ObjCSubscriptRefExprClass:
  612. case Stmt::ObjCPropertyRefExprClass:
  613. llvm_unreachable("These are handled by PseudoObjectExpr");
  614. case Stmt::GNUNullExprClass: {
  615. // GNU __null is a pointer-width integer, not an actual pointer.
  616. ProgramStateRef state = Pred->getState();
  617. state = state->BindExpr(S, Pred->getLocationContext(),
  618. svalBuilder.makeIntValWithPtrWidth(0, false));
  619. Bldr.generateNode(S, Pred, state);
  620. break;
  621. }
  622. case Stmt::ObjCAtSynchronizedStmtClass:
  623. Bldr.takeNodes(Pred);
  624. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  625. Bldr.addNodes(Dst);
  626. break;
  627. case Stmt::ExprWithCleanupsClass:
  628. // Handled due to fully linearised CFG.
  629. break;
  630. // Cases not handled yet; but will handle some day.
  631. case Stmt::DesignatedInitExprClass:
  632. case Stmt::ExtVectorElementExprClass:
  633. case Stmt::ImaginaryLiteralClass:
  634. case Stmt::ObjCAtCatchStmtClass:
  635. case Stmt::ObjCAtFinallyStmtClass:
  636. case Stmt::ObjCAtTryStmtClass:
  637. case Stmt::ObjCAutoreleasePoolStmtClass:
  638. case Stmt::ObjCEncodeExprClass:
  639. case Stmt::ObjCIsaExprClass:
  640. case Stmt::ObjCProtocolExprClass:
  641. case Stmt::ObjCSelectorExprClass:
  642. case Stmt::ParenListExprClass:
  643. case Stmt::PredefinedExprClass:
  644. case Stmt::ShuffleVectorExprClass:
  645. case Stmt::ConvertVectorExprClass:
  646. case Stmt::VAArgExprClass:
  647. case Stmt::CUDAKernelCallExprClass:
  648. case Stmt::OpaqueValueExprClass:
  649. case Stmt::AsTypeExprClass:
  650. case Stmt::AtomicExprClass:
  651. // Fall through.
  652. // Cases we intentionally don't evaluate, since they don't need
  653. // to be explicitly evaluated.
  654. case Stmt::AddrLabelExprClass:
  655. case Stmt::AttributedStmtClass:
  656. case Stmt::IntegerLiteralClass:
  657. case Stmt::CharacterLiteralClass:
  658. case Stmt::ImplicitValueInitExprClass:
  659. case Stmt::CXXScalarValueInitExprClass:
  660. case Stmt::CXXBoolLiteralExprClass:
  661. case Stmt::ObjCBoolLiteralExprClass:
  662. case Stmt::FloatingLiteralClass:
  663. case Stmt::SizeOfPackExprClass:
  664. case Stmt::StringLiteralClass:
  665. case Stmt::ObjCStringLiteralClass:
  666. case Stmt::CXXBindTemporaryExprClass:
  667. case Stmt::CXXPseudoDestructorExprClass:
  668. case Stmt::SubstNonTypeTemplateParmExprClass:
  669. case Stmt::CXXNullPtrLiteralExprClass: {
  670. Bldr.takeNodes(Pred);
  671. ExplodedNodeSet preVisit;
  672. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  673. getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
  674. Bldr.addNodes(Dst);
  675. break;
  676. }
  677. case Stmt::CXXDefaultArgExprClass:
  678. case Stmt::CXXDefaultInitExprClass: {
  679. Bldr.takeNodes(Pred);
  680. ExplodedNodeSet PreVisit;
  681. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  682. ExplodedNodeSet Tmp;
  683. StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
  684. const Expr *ArgE;
  685. if (const CXXDefaultArgExpr *DefE = dyn_cast<CXXDefaultArgExpr>(S))
  686. ArgE = DefE->getExpr();
  687. else if (const CXXDefaultInitExpr *DefE = dyn_cast<CXXDefaultInitExpr>(S))
  688. ArgE = DefE->getExpr();
  689. else
  690. llvm_unreachable("unknown constant wrapper kind");
  691. bool IsTemporary = false;
  692. if (const MaterializeTemporaryExpr *MTE =
  693. dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
  694. ArgE = MTE->GetTemporaryExpr();
  695. IsTemporary = true;
  696. }
  697. Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
  698. if (!ConstantVal)
  699. ConstantVal = UnknownVal();
  700. const LocationContext *LCtx = Pred->getLocationContext();
  701. for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
  702. I != E; ++I) {
  703. ProgramStateRef State = (*I)->getState();
  704. State = State->BindExpr(S, LCtx, *ConstantVal);
  705. if (IsTemporary)
  706. State = createTemporaryRegionIfNeeded(State, LCtx,
  707. cast<Expr>(S),
  708. cast<Expr>(S));
  709. Bldr2.generateNode(S, *I, State);
  710. }
  711. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  712. Bldr.addNodes(Dst);
  713. break;
  714. }
  715. // Cases we evaluate as opaque expressions, conjuring a symbol.
  716. case Stmt::CXXStdInitializerListExprClass:
  717. case Expr::ObjCArrayLiteralClass:
  718. case Expr::ObjCDictionaryLiteralClass:
  719. case Expr::ObjCBoxedExprClass: {
  720. Bldr.takeNodes(Pred);
  721. ExplodedNodeSet preVisit;
  722. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  723. ExplodedNodeSet Tmp;
  724. StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
  725. const Expr *Ex = cast<Expr>(S);
  726. QualType resultType = Ex->getType();
  727. for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
  728. it != et; ++it) {
  729. ExplodedNode *N = *it;
  730. const LocationContext *LCtx = N->getLocationContext();
  731. SVal result = svalBuilder.conjureSymbolVal(0, Ex, LCtx, resultType,
  732. currBldrCtx->blockCount());
  733. ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
  734. Bldr2.generateNode(S, N, state);
  735. }
  736. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  737. Bldr.addNodes(Dst);
  738. break;
  739. }
  740. case Stmt::ArraySubscriptExprClass:
  741. Bldr.takeNodes(Pred);
  742. VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  743. Bldr.addNodes(Dst);
  744. break;
  745. case Stmt::GCCAsmStmtClass:
  746. Bldr.takeNodes(Pred);
  747. VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
  748. Bldr.addNodes(Dst);
  749. break;
  750. case Stmt::MSAsmStmtClass:
  751. Bldr.takeNodes(Pred);
  752. VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
  753. Bldr.addNodes(Dst);
  754. break;
  755. case Stmt::BlockExprClass:
  756. Bldr.takeNodes(Pred);
  757. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  758. Bldr.addNodes(Dst);
  759. break;
  760. case Stmt::BinaryOperatorClass: {
  761. const BinaryOperator* B = cast<BinaryOperator>(S);
  762. if (B->isLogicalOp()) {
  763. Bldr.takeNodes(Pred);
  764. VisitLogicalExpr(B, Pred, Dst);
  765. Bldr.addNodes(Dst);
  766. break;
  767. }
  768. else if (B->getOpcode() == BO_Comma) {
  769. ProgramStateRef state = Pred->getState();
  770. Bldr.generateNode(B, Pred,
  771. state->BindExpr(B, Pred->getLocationContext(),
  772. state->getSVal(B->getRHS(),
  773. Pred->getLocationContext())));
  774. break;
  775. }
  776. Bldr.takeNodes(Pred);
  777. if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
  778. (B->isRelationalOp() || B->isEqualityOp())) {
  779. ExplodedNodeSet Tmp;
  780. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  781. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
  782. }
  783. else
  784. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  785. Bldr.addNodes(Dst);
  786. break;
  787. }
  788. case Stmt::CXXOperatorCallExprClass: {
  789. const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
  790. // For instance method operators, make sure the 'this' argument has a
  791. // valid region.
  792. const Decl *Callee = OCE->getCalleeDecl();
  793. if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
  794. if (MD->isInstance()) {
  795. ProgramStateRef State = Pred->getState();
  796. const LocationContext *LCtx = Pred->getLocationContext();
  797. ProgramStateRef NewState =
  798. createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
  799. if (NewState != State) {
  800. Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/0,
  801. ProgramPoint::PreStmtKind);
  802. // Did we cache out?
  803. if (!Pred)
  804. break;
  805. }
  806. }
  807. }
  808. // FALLTHROUGH
  809. }
  810. case Stmt::CallExprClass:
  811. case Stmt::CXXMemberCallExprClass:
  812. case Stmt::UserDefinedLiteralClass: {
  813. Bldr.takeNodes(Pred);
  814. VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
  815. Bldr.addNodes(Dst);
  816. break;
  817. }
  818. case Stmt::CXXCatchStmtClass: {
  819. Bldr.takeNodes(Pred);
  820. VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
  821. Bldr.addNodes(Dst);
  822. break;
  823. }
  824. case Stmt::CXXTemporaryObjectExprClass:
  825. case Stmt::CXXConstructExprClass: {
  826. Bldr.takeNodes(Pred);
  827. VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
  828. Bldr.addNodes(Dst);
  829. break;
  830. }
  831. case Stmt::CXXNewExprClass: {
  832. Bldr.takeNodes(Pred);
  833. ExplodedNodeSet PostVisit;
  834. VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
  835. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  836. Bldr.addNodes(Dst);
  837. break;
  838. }
  839. case Stmt::CXXDeleteExprClass: {
  840. Bldr.takeNodes(Pred);
  841. ExplodedNodeSet PreVisit;
  842. const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
  843. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  844. for (ExplodedNodeSet::iterator i = PreVisit.begin(),
  845. e = PreVisit.end(); i != e ; ++i)
  846. VisitCXXDeleteExpr(CDE, *i, Dst);
  847. Bldr.addNodes(Dst);
  848. break;
  849. }
  850. // FIXME: ChooseExpr is really a constant. We need to fix
  851. // the CFG do not model them as explicit control-flow.
  852. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  853. Bldr.takeNodes(Pred);
  854. const ChooseExpr *C = cast<ChooseExpr>(S);
  855. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  856. Bldr.addNodes(Dst);
  857. break;
  858. }
  859. case Stmt::CompoundAssignOperatorClass:
  860. Bldr.takeNodes(Pred);
  861. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  862. Bldr.addNodes(Dst);
  863. break;
  864. case Stmt::CompoundLiteralExprClass:
  865. Bldr.takeNodes(Pred);
  866. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  867. Bldr.addNodes(Dst);
  868. break;
  869. case Stmt::BinaryConditionalOperatorClass:
  870. case Stmt::ConditionalOperatorClass: { // '?' operator
  871. Bldr.takeNodes(Pred);
  872. const AbstractConditionalOperator *C
  873. = cast<AbstractConditionalOperator>(S);
  874. VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
  875. Bldr.addNodes(Dst);
  876. break;
  877. }
  878. case Stmt::CXXThisExprClass:
  879. Bldr.takeNodes(Pred);
  880. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  881. Bldr.addNodes(Dst);
  882. break;
  883. case Stmt::DeclRefExprClass: {
  884. Bldr.takeNodes(Pred);
  885. const DeclRefExpr *DE = cast<DeclRefExpr>(S);
  886. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  887. Bldr.addNodes(Dst);
  888. break;
  889. }
  890. case Stmt::DeclStmtClass:
  891. Bldr.takeNodes(Pred);
  892. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  893. Bldr.addNodes(Dst);
  894. break;
  895. case Stmt::ImplicitCastExprClass:
  896. case Stmt::CStyleCastExprClass:
  897. case Stmt::CXXStaticCastExprClass:
  898. case Stmt::CXXDynamicCastExprClass:
  899. case Stmt::CXXReinterpretCastExprClass:
  900. case Stmt::CXXConstCastExprClass:
  901. case Stmt::CXXFunctionalCastExprClass:
  902. case Stmt::ObjCBridgedCastExprClass: {
  903. Bldr.takeNodes(Pred);
  904. const CastExpr *C = cast<CastExpr>(S);
  905. // Handle the previsit checks.
  906. ExplodedNodeSet dstPrevisit;
  907. getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
  908. // Handle the expression itself.
  909. ExplodedNodeSet dstExpr;
  910. for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
  911. e = dstPrevisit.end(); i != e ; ++i) {
  912. VisitCast(C, C->getSubExpr(), *i, dstExpr);
  913. }
  914. // Handle the postvisit checks.
  915. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
  916. Bldr.addNodes(Dst);
  917. break;
  918. }
  919. case Expr::MaterializeTemporaryExprClass: {
  920. Bldr.takeNodes(Pred);
  921. const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
  922. CreateCXXTemporaryObject(MTE, Pred, Dst);
  923. Bldr.addNodes(Dst);
  924. break;
  925. }
  926. case Stmt::InitListExprClass:
  927. Bldr.takeNodes(Pred);
  928. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  929. Bldr.addNodes(Dst);
  930. break;
  931. case Stmt::MemberExprClass:
  932. Bldr.takeNodes(Pred);
  933. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  934. Bldr.addNodes(Dst);
  935. break;
  936. case Stmt::ObjCIvarRefExprClass:
  937. Bldr.takeNodes(Pred);
  938. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  939. Bldr.addNodes(Dst);
  940. break;
  941. case Stmt::ObjCForCollectionStmtClass:
  942. Bldr.takeNodes(Pred);
  943. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  944. Bldr.addNodes(Dst);
  945. break;
  946. case Stmt::ObjCMessageExprClass:
  947. Bldr.takeNodes(Pred);
  948. VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
  949. Bldr.addNodes(Dst);
  950. break;
  951. case Stmt::ObjCAtThrowStmtClass:
  952. case Stmt::CXXThrowExprClass:
  953. // FIXME: This is not complete. We basically treat @throw as
  954. // an abort.
  955. Bldr.generateSink(S, Pred, Pred->getState());
  956. break;
  957. case Stmt::ReturnStmtClass:
  958. Bldr.takeNodes(Pred);
  959. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  960. Bldr.addNodes(Dst);
  961. break;
  962. case Stmt::OffsetOfExprClass:
  963. Bldr.takeNodes(Pred);
  964. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
  965. Bldr.addNodes(Dst);
  966. break;
  967. case Stmt::UnaryExprOrTypeTraitExprClass:
  968. Bldr.takeNodes(Pred);
  969. VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  970. Pred, Dst);
  971. Bldr.addNodes(Dst);
  972. break;
  973. case Stmt::StmtExprClass: {
  974. const StmtExpr *SE = cast<StmtExpr>(S);
  975. if (SE->getSubStmt()->body_empty()) {
  976. // Empty statement expression.
  977. assert(SE->getType() == getContext().VoidTy
  978. && "Empty statement expression must have void type.");
  979. break;
  980. }
  981. if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  982. ProgramStateRef state = Pred->getState();
  983. Bldr.generateNode(SE, Pred,
  984. state->BindExpr(SE, Pred->getLocationContext(),
  985. state->getSVal(LastExpr,
  986. Pred->getLocationContext())));
  987. }
  988. break;
  989. }
  990. case Stmt::UnaryOperatorClass: {
  991. Bldr.takeNodes(Pred);
  992. const UnaryOperator *U = cast<UnaryOperator>(S);
  993. if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
  994. ExplodedNodeSet Tmp;
  995. VisitUnaryOperator(U, Pred, Tmp);
  996. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
  997. }
  998. else
  999. VisitUnaryOperator(U, Pred, Dst);
  1000. Bldr.addNodes(Dst);
  1001. break;
  1002. }
  1003. case Stmt::PseudoObjectExprClass: {
  1004. Bldr.takeNodes(Pred);
  1005. ProgramStateRef state = Pred->getState();
  1006. const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
  1007. if (const Expr *Result = PE->getResultExpr()) {
  1008. SVal V = state->getSVal(Result, Pred->getLocationContext());
  1009. Bldr.generateNode(S, Pred,
  1010. state->BindExpr(S, Pred->getLocationContext(), V));
  1011. }
  1012. else
  1013. Bldr.generateNode(S, Pred,
  1014. state->BindExpr(S, Pred->getLocationContext(),
  1015. UnknownVal()));
  1016. Bldr.addNodes(Dst);
  1017. break;
  1018. }
  1019. }
  1020. }
  1021. bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
  1022. const LocationContext *CalleeLC) {
  1023. const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
  1024. const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
  1025. assert(CalleeSF && CallerSF);
  1026. ExplodedNode *BeforeProcessingCall = 0;
  1027. const Stmt *CE = CalleeSF->getCallSite();
  1028. // Find the first node before we started processing the call expression.
  1029. while (N) {
  1030. ProgramPoint L = N->getLocation();
  1031. BeforeProcessingCall = N;
  1032. N = N->pred_empty() ? NULL : *(N->pred_begin());
  1033. // Skip the nodes corresponding to the inlined code.
  1034. if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
  1035. continue;
  1036. // We reached the caller. Find the node right before we started
  1037. // processing the call.
  1038. if (L.isPurgeKind())
  1039. continue;
  1040. if (L.getAs<PreImplicitCall>())
  1041. continue;
  1042. if (L.getAs<CallEnter>())
  1043. continue;
  1044. if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
  1045. if (SP->getStmt() == CE)
  1046. continue;
  1047. break;
  1048. }
  1049. if (!BeforeProcessingCall)
  1050. return false;
  1051. // TODO: Clean up the unneeded nodes.
  1052. // Build an Epsilon node from which we will restart the analyzes.
  1053. // Note that CE is permitted to be NULL!
  1054. ProgramPoint NewNodeLoc =
  1055. EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
  1056. // Add the special flag to GDM to signal retrying with no inlining.
  1057. // Note, changing the state ensures that we are not going to cache out.
  1058. ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
  1059. NewNodeState =
  1060. NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
  1061. // Make the new node a successor of BeforeProcessingCall.
  1062. bool IsNew = false;
  1063. ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
  1064. // We cached out at this point. Caching out is common due to us backtracking
  1065. // from the inlined function, which might spawn several paths.
  1066. if (!IsNew)
  1067. return true;
  1068. NewNode->addPredecessor(BeforeProcessingCall, G);
  1069. // Add the new node to the work list.
  1070. Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
  1071. CalleeSF->getIndex());
  1072. NumTimesRetriedWithoutInlining++;
  1073. return true;
  1074. }
  1075. /// Block entrance. (Update counters).
  1076. void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
  1077. NodeBuilderWithSinks &nodeBuilder,
  1078. ExplodedNode *Pred) {
  1079. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1080. // FIXME: Refactor this into a checker.
  1081. if (nodeBuilder.getContext().blockCount() >= AMgr.options.maxBlockVisitOnPath) {
  1082. static SimpleProgramPointTag tag("ExprEngine : Block count exceeded");
  1083. const ExplodedNode *Sink =
  1084. nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
  1085. // Check if we stopped at the top level function or not.
  1086. // Root node should have the location context of the top most function.
  1087. const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
  1088. const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
  1089. const LocationContext *RootLC =
  1090. (*G.roots_begin())->getLocation().getLocationContext();
  1091. if (RootLC->getCurrentStackFrame() != CalleeSF) {
  1092. Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
  1093. // Re-run the call evaluation without inlining it, by storing the
  1094. // no-inlining policy in the state and enqueuing the new work item on
  1095. // the list. Replay should almost never fail. Use the stats to catch it
  1096. // if it does.
  1097. if ((!AMgr.options.NoRetryExhausted &&
  1098. replayWithoutInlining(Pred, CalleeLC)))
  1099. return;
  1100. NumMaxBlockCountReachedInInlined++;
  1101. } else
  1102. NumMaxBlockCountReached++;
  1103. // Make sink nodes as exhausted(for stats) only if retry failed.
  1104. Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
  1105. }
  1106. }
  1107. //===----------------------------------------------------------------------===//
  1108. // Branch processing.
  1109. //===----------------------------------------------------------------------===//
  1110. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  1111. /// to try to recover some path-sensitivity for casts of symbolic
  1112. /// integers that promote their values (which are currently not tracked well).
  1113. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  1114. // cast(s) did was sign-extend the original value.
  1115. static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
  1116. ProgramStateRef state,
  1117. const Stmt *Condition,
  1118. const LocationContext *LCtx,
  1119. ASTContext &Ctx) {
  1120. const Expr *Ex = dyn_cast<Expr>(Condition);
  1121. if (!Ex)
  1122. return UnknownVal();
  1123. uint64_t bits = 0;
  1124. bool bitsInit = false;
  1125. while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
  1126. QualType T = CE->getType();
  1127. if (!T->isIntegralOrEnumerationType())
  1128. return UnknownVal();
  1129. uint64_t newBits = Ctx.getTypeSize(T);
  1130. if (!bitsInit || newBits < bits) {
  1131. bitsInit = true;
  1132. bits = newBits;
  1133. }
  1134. Ex = CE->getSubExpr();
  1135. }
  1136. // We reached a non-cast. Is it a symbolic value?
  1137. QualType T = Ex->getType();
  1138. if (!bitsInit || !T->isIntegralOrEnumerationType() ||
  1139. Ctx.getTypeSize(T) > bits)
  1140. return UnknownVal();
  1141. return state->getSVal(Ex, LCtx);
  1142. }
  1143. static const Stmt *ResolveCondition(const Stmt *Condition,
  1144. const CFGBlock *B) {
  1145. if (const Expr *Ex = dyn_cast<Expr>(Condition))
  1146. Condition = Ex->IgnoreParens();
  1147. const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
  1148. if (!BO || !BO->isLogicalOp())
  1149. return Condition;
  1150. // For logical operations, we still have the case where some branches
  1151. // use the traditional "merge" approach and others sink the branch
  1152. // directly into the basic blocks representing the logical operation.
  1153. // We need to distinguish between those two cases here.
  1154. // The invariants are still shifting, but it is possible that the
  1155. // last element in a CFGBlock is not a CFGStmt. Look for the last
  1156. // CFGStmt as the value of the condition.
  1157. CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
  1158. for (; I != E; ++I) {
  1159. CFGElement Elem = *I;
  1160. Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
  1161. if (!CS)
  1162. continue;
  1163. if (CS->getStmt() != Condition)
  1164. break;
  1165. return Condition;
  1166. }
  1167. assert(I != E);
  1168. while (Condition) {
  1169. BO = dyn_cast<BinaryOperator>(Condition);
  1170. if (!BO || !BO->isLogicalOp())
  1171. return Condition;
  1172. Condition = BO->getRHS()->IgnoreParens();
  1173. }
  1174. llvm_unreachable("could not resolve condition");
  1175. }
  1176. void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
  1177. NodeBuilderContext& BldCtx,
  1178. ExplodedNode *Pred,
  1179. ExplodedNodeSet &Dst,
  1180. const CFGBlock *DstT,
  1181. const CFGBlock *DstF) {
  1182. const LocationContext *LCtx = Pred->getLocationContext();
  1183. PrettyStackTraceLocationContext StackCrashInfo(LCtx);
  1184. currBldrCtx = &BldCtx;
  1185. // Check for NULL conditions; e.g. "for(;;)"
  1186. if (!Condition) {
  1187. BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
  1188. NullCondBldr.markInfeasible(false);
  1189. NullCondBldr.generateNode(Pred->getState(), true, Pred);
  1190. return;
  1191. }
  1192. if (const Expr *Ex = dyn_cast<Expr>(Condition))
  1193. Condition = Ex->IgnoreParens();
  1194. Condition = ResolveCondition(Condition, BldCtx.getBlock());
  1195. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1196. Condition->getLocStart(),
  1197. "Error evaluating branch");
  1198. ExplodedNodeSet CheckersOutSet;
  1199. getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
  1200. Pred, *this);
  1201. // We generated only sinks.
  1202. if (CheckersOutSet.empty())
  1203. return;
  1204. BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
  1205. for (NodeBuilder::iterator I = CheckersOutSet.begin(),
  1206. E = CheckersOutSet.end(); E != I; ++I) {
  1207. ExplodedNode *PredI = *I;
  1208. if (PredI->isSink())
  1209. continue;
  1210. ProgramStateRef PrevState = PredI->getState();
  1211. SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
  1212. if (X.isUnknownOrUndef()) {
  1213. // Give it a chance to recover from unknown.
  1214. if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
  1215. if (Ex->getType()->isIntegralOrEnumerationType()) {
  1216. // Try to recover some path-sensitivity. Right now casts of symbolic
  1217. // integers that promote their values are currently not tracked well.
  1218. // If 'Condition' is such an expression, try and recover the
  1219. // underlying value and use that instead.
  1220. SVal recovered = RecoverCastedSymbol(getStateManager(),
  1221. PrevState, Condition,
  1222. PredI->getLocationContext(),
  1223. getContext());
  1224. if (!recovered.isUnknown()) {
  1225. X = recovered;
  1226. }
  1227. }
  1228. }
  1229. }
  1230. // If the condition is still unknown, give up.
  1231. if (X.isUnknownOrUndef()) {
  1232. builder.generateNode(PrevState, true, PredI);
  1233. builder.generateNode(PrevState, false, PredI);
  1234. continue;
  1235. }
  1236. DefinedSVal V = X.castAs<DefinedSVal>();
  1237. ProgramStateRef StTrue, StFalse;
  1238. tie(StTrue, StFalse) = PrevState->assume(V);
  1239. // Process the true branch.
  1240. if (builder.isFeasible(true)) {
  1241. if (StTrue)
  1242. builder.generateNode(StTrue, true, PredI);
  1243. else
  1244. builder.markInfeasible(true);
  1245. }
  1246. // Process the false branch.
  1247. if (builder.isFeasible(false)) {
  1248. if (StFalse)
  1249. builder.generateNode(StFalse, false, PredI);
  1250. else
  1251. builder.markInfeasible(false);
  1252. }
  1253. }
  1254. currBldrCtx = 0;
  1255. }
  1256. /// The GDM component containing the set of global variables which have been
  1257. /// previously initialized with explicit initializers.
  1258. REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
  1259. llvm::ImmutableSet<const VarDecl *>)
  1260. void ExprEngine::processStaticInitializer(const DeclStmt *DS,
  1261. NodeBuilderContext &BuilderCtx,
  1262. ExplodedNode *Pred,
  1263. clang::ento::ExplodedNodeSet &Dst,
  1264. const CFGBlock *DstT,
  1265. const CFGBlock *DstF) {
  1266. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1267. currBldrCtx = &BuilderCtx;
  1268. const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
  1269. ProgramStateRef state = Pred->getState();
  1270. bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
  1271. BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
  1272. if (!initHasRun) {
  1273. state = state->add<InitializedGlobalsSet>(VD);
  1274. }
  1275. builder.generateNode(state, initHasRun, Pred);
  1276. builder.markInfeasible(!initHasRun);
  1277. currBldrCtx = 0;
  1278. }
  1279. /// processIndirectGoto - Called by CoreEngine. Used to generate successor
  1280. /// nodes by processing the 'effects' of a computed goto jump.
  1281. void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
  1282. ProgramStateRef state = builder.getState();
  1283. SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
  1284. // Three possibilities:
  1285. //
  1286. // (1) We know the computed label.
  1287. // (2) The label is NULL (or some other constant), or Undefined.
  1288. // (3) We have no clue about the label. Dispatch to all targets.
  1289. //
  1290. typedef IndirectGotoNodeBuilder::iterator iterator;
  1291. if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
  1292. const LabelDecl *L = LV->getLabel();
  1293. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
  1294. if (I.getLabel() == L) {
  1295. builder.generateNode(I, state);
  1296. return;
  1297. }
  1298. }
  1299. llvm_unreachable("No block with label.");
  1300. }
  1301. if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
  1302. // Dispatch to the first target and mark it as a sink.
  1303. //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
  1304. // FIXME: add checker visit.
  1305. // UndefBranches.insert(N);
  1306. return;
  1307. }
  1308. // This is really a catch-all. We don't support symbolics yet.
  1309. // FIXME: Implement dispatch for symbolic pointers.
  1310. for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
  1311. builder.generateNode(I, state);
  1312. }
  1313. /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
  1314. /// nodes when the control reaches the end of a function.
  1315. void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
  1316. ExplodedNode *Pred) {
  1317. PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
  1318. StateMgr.EndPath(Pred->getState());
  1319. ExplodedNodeSet Dst;
  1320. if (Pred->getLocationContext()->inTopFrame()) {
  1321. // Remove dead symbols.
  1322. ExplodedNodeSet AfterRemovedDead;
  1323. removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
  1324. // Notify checkers.
  1325. for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
  1326. E = AfterRemovedDead.end(); I != E; ++I) {
  1327. getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
  1328. }
  1329. } else {
  1330. getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
  1331. }
  1332. Engine.enqueueEndOfFunction(Dst);
  1333. }
  1334. /// ProcessSwitch - Called by CoreEngine. Used to generate successor
  1335. /// nodes by processing the 'effects' of a switch statement.
  1336. void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
  1337. typedef SwitchNodeBuilder::iterator iterator;
  1338. ProgramStateRef state = builder.getState();
  1339. const Expr *CondE = builder.getCondition();
  1340. SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
  1341. if (CondV_untested.isUndef()) {
  1342. //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
  1343. // FIXME: add checker
  1344. //UndefBranches.insert(N);
  1345. return;
  1346. }
  1347. DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
  1348. ProgramStateRef DefaultSt = state;
  1349. iterator I = builder.begin(), EI = builder.end();
  1350. bool defaultIsFeasible = I == EI;
  1351. for ( ; I != EI; ++I) {
  1352. // Successor may be pruned out during CFG construction.
  1353. if (!I.getBlock())
  1354. continue;
  1355. const CaseStmt *Case = I.getCase();
  1356. // Evaluate the LHS of the case value.
  1357. llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
  1358. assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
  1359. // Get the RHS of the case, if it exists.
  1360. llvm::APSInt V2;
  1361. if (const Expr *E = Case->getRHS())
  1362. V2 = E->EvaluateKnownConstInt(getContext());
  1363. else
  1364. V2 = V1;
  1365. // FIXME: Eventually we should replace the logic below with a range
  1366. // comparison, rather than concretize the values within the range.
  1367. // This should be easy once we have "ranges" for NonLVals.
  1368. do {
  1369. nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1));
  1370. DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
  1371. CondV, CaseVal);
  1372. // Now "assume" that the case matches.
  1373. if (ProgramStateRef stateNew = state->assume(Res, true)) {
  1374. builder.generateCaseStmtNode(I, stateNew);
  1375. // If CondV evaluates to a constant, then we know that this
  1376. // is the *only* case that we can take, so stop evaluating the
  1377. // others.
  1378. if (CondV.getAs<nonloc::ConcreteInt>())
  1379. return;
  1380. }
  1381. // Now "assume" that the case doesn't match. Add this state
  1382. // to the default state (if it is feasible).
  1383. if (DefaultSt) {
  1384. if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) {
  1385. defaultIsFeasible = true;
  1386. DefaultSt = stateNew;
  1387. }
  1388. else {
  1389. defaultIsFeasible = false;
  1390. DefaultSt = NULL;
  1391. }
  1392. }
  1393. // Concretize the next value in the range.
  1394. if (V1 == V2)
  1395. break;
  1396. ++V1;
  1397. assert (V1 <= V2);
  1398. } while (true);
  1399. }
  1400. if (!defaultIsFeasible)
  1401. return;
  1402. // If we have switch(enum value), the default branch is not
  1403. // feasible if all of the enum constants not covered by 'case:' statements
  1404. // are not feasible values for the switch condition.
  1405. //
  1406. // Note that this isn't as accurate as it could be. Even if there isn't
  1407. // a case for a particular enum value as long as that enum value isn't
  1408. // feasible then it shouldn't be considered for making 'default:' reachable.
  1409. const SwitchStmt *SS = builder.getSwitch();
  1410. const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
  1411. if (CondExpr->getType()->getAs<EnumType>()) {
  1412. if (SS->isAllEnumCasesCovered())
  1413. return;
  1414. }
  1415. builder.generateDefaultCaseNode(DefaultSt);
  1416. }
  1417. //===----------------------------------------------------------------------===//
  1418. // Transfer functions: Loads and stores.
  1419. //===----------------------------------------------------------------------===//
  1420. void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
  1421. ExplodedNode *Pred,
  1422. ExplodedNodeSet &Dst) {
  1423. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  1424. ProgramStateRef state = Pred->getState();
  1425. const LocationContext *LCtx = Pred->getLocationContext();
  1426. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1427. // C permits "extern void v", and if you cast the address to a valid type,
  1428. // you can even do things with it. We simply pretend
  1429. assert(Ex->isGLValue() || VD->getType()->isVoidType());
  1430. SVal V = state->getLValue(VD, Pred->getLocationContext());
  1431. // For references, the 'lvalue' is the pointer address stored in the
  1432. // reference region.
  1433. if (VD->getType()->isReferenceType()) {
  1434. if (const MemRegion *R = V.getAsRegion())
  1435. V = state->getSVal(R);
  1436. else
  1437. V = UnknownVal();
  1438. }
  1439. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
  1440. ProgramPoint::PostLValueKind);
  1441. return;
  1442. }
  1443. if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
  1444. assert(!Ex->isGLValue());
  1445. SVal V = svalBuilder.makeIntVal(ED->getInitVal());
  1446. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
  1447. return;
  1448. }
  1449. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1450. SVal V = svalBuilder.getFunctionPointer(FD);
  1451. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
  1452. ProgramPoint::PostLValueKind);
  1453. return;
  1454. }
  1455. if (isa<FieldDecl>(D)) {
  1456. // FIXME: Compute lvalue of field pointers-to-member.
  1457. // Right now we just use a non-null void pointer, so that it gives proper
  1458. // results in boolean contexts.
  1459. SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
  1460. currBldrCtx->blockCount());
  1461. state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
  1462. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
  1463. ProgramPoint::PostLValueKind);
  1464. return;
  1465. }
  1466. llvm_unreachable("Support for this Decl not implemented.");
  1467. }
  1468. /// VisitArraySubscriptExpr - Transfer function for array accesses
  1469. void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
  1470. ExplodedNode *Pred,
  1471. ExplodedNodeSet &Dst){
  1472. const Expr *Base = A->getBase()->IgnoreParens();
  1473. const Expr *Idx = A->getIdx()->IgnoreParens();
  1474. ExplodedNodeSet checkerPreStmt;
  1475. getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
  1476. StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
  1477. for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
  1478. ei = checkerPreStmt.end(); it != ei; ++it) {
  1479. const LocationContext *LCtx = (*it)->getLocationContext();
  1480. ProgramStateRef state = (*it)->getState();
  1481. SVal V = state->getLValue(A->getType(),
  1482. state->getSVal(Idx, LCtx),
  1483. state->getSVal(Base, LCtx));
  1484. assert(A->isGLValue());
  1485. Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), 0,
  1486. ProgramPoint::PostLValueKind);
  1487. }
  1488. }
  1489. /// VisitMemberExpr - Transfer function for member expressions.
  1490. void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
  1491. ExplodedNodeSet &Dst) {
  1492. // FIXME: Prechecks eventually go in ::Visit().
  1493. ExplodedNodeSet CheckedSet;
  1494. getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
  1495. ExplodedNodeSet EvalSet;
  1496. ValueDecl *Member = M->getMemberDecl();
  1497. // Handle static member variables and enum constants accessed via
  1498. // member syntax.
  1499. if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
  1500. ExplodedNodeSet Dst;
  1501. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  1502. I != E; ++I) {
  1503. VisitCommonDeclRefExpr(M, Member, Pred, EvalSet);
  1504. }
  1505. } else {
  1506. StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
  1507. ExplodedNodeSet Tmp;
  1508. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  1509. I != E; ++I) {
  1510. ProgramStateRef state = (*I)->getState();
  1511. const LocationContext *LCtx = (*I)->getLocationContext();
  1512. Expr *BaseExpr = M->getBase();
  1513. // Handle C++ method calls.
  1514. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
  1515. if (MD->isInstance())
  1516. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  1517. SVal MDVal = svalBuilder.getFunctionPointer(MD);
  1518. state = state->BindExpr(M, LCtx, MDVal);
  1519. Bldr.generateNode(M, *I, state);
  1520. continue;
  1521. }
  1522. // Handle regular struct fields / member variables.
  1523. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  1524. SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
  1525. FieldDecl *field = cast<FieldDecl>(Member);
  1526. SVal L = state->getLValue(field, baseExprVal);
  1527. if (M->isGLValue() || M->getType()->isArrayType()) {
  1528. // We special-case rvalues of array type because the analyzer cannot
  1529. // reason about them, since we expect all regions to be wrapped in Locs.
  1530. // We instead treat these as lvalues and assume that they will decay to
  1531. // pointers as soon as they are used.
  1532. if (!M->isGLValue()) {
  1533. assert(M->getType()->isArrayType());
  1534. const ImplicitCastExpr *PE =
  1535. dyn_cast<ImplicitCastExpr>((*I)->getParentMap().getParent(M));
  1536. if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
  1537. llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
  1538. L = UnknownVal();
  1539. }
  1540. }
  1541. if (field->getType()->isReferenceType()) {
  1542. if (const MemRegion *R = L.getAsRegion())
  1543. L = state->getSVal(R);
  1544. else
  1545. L = UnknownVal();
  1546. }
  1547. Bldr.generateNode(M, *I, state->BindExpr(M, LCtx, L), 0,
  1548. ProgramPoint::PostLValueKind);
  1549. } else {
  1550. Bldr.takeNodes(*I);
  1551. evalLoad(Tmp, M, M, *I, state, L);
  1552. Bldr.addNodes(Tmp);
  1553. }
  1554. }
  1555. }
  1556. getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
  1557. }
  1558. namespace {
  1559. class CollectReachableSymbolsCallback : public SymbolVisitor {
  1560. InvalidatedSymbols Symbols;
  1561. public:
  1562. CollectReachableSymbolsCallback(ProgramStateRef State) {}
  1563. const InvalidatedSymbols &getSymbols() const { return Symbols; }
  1564. bool VisitSymbol(SymbolRef Sym) {
  1565. Symbols.insert(Sym);
  1566. return true;
  1567. }
  1568. };
  1569. } // end anonymous namespace
  1570. // A value escapes in three possible cases:
  1571. // (1) We are binding to something that is not a memory region.
  1572. // (2) We are binding to a MemrRegion that does not have stack storage.
  1573. // (3) We are binding to a MemRegion with stack storage that the store
  1574. // does not understand.
  1575. ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
  1576. SVal Loc, SVal Val) {
  1577. // Are we storing to something that causes the value to "escape"?
  1578. bool escapes = true;
  1579. // TODO: Move to StoreManager.
  1580. if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
  1581. escapes = !regionLoc->getRegion()->hasStackStorage();
  1582. if (!escapes) {
  1583. // To test (3), generate a new state with the binding added. If it is
  1584. // the same state, then it escapes (since the store cannot represent
  1585. // the binding).
  1586. // Do this only if we know that the store is not supposed to generate the
  1587. // same state.
  1588. SVal StoredVal = State->getSVal(regionLoc->getRegion());
  1589. if (StoredVal != Val)
  1590. escapes = (State == (State->bindLoc(*regionLoc, Val)));
  1591. }
  1592. }
  1593. // If our store can represent the binding and we aren't storing to something
  1594. // that doesn't have local storage then just return and have the simulation
  1595. // state continue as is.
  1596. if (!escapes)
  1597. return State;
  1598. // Otherwise, find all symbols referenced by 'val' that we are tracking
  1599. // and stop tracking them.
  1600. CollectReachableSymbolsCallback Scanner =
  1601. State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
  1602. const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
  1603. State = getCheckerManager().runCheckersForPointerEscape(State,
  1604. EscapedSymbols,
  1605. /*CallEvent*/ 0,
  1606. PSK_EscapeOnBind,
  1607. 0);
  1608. return State;
  1609. }
  1610. ProgramStateRef
  1611. ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
  1612. const InvalidatedSymbols *Invalidated,
  1613. ArrayRef<const MemRegion *> ExplicitRegions,
  1614. ArrayRef<const MemRegion *> Regions,
  1615. const CallEvent *Call,
  1616. RegionAndSymbolInvalidationTraits &ITraits) {
  1617. if (!Invalidated || Invalidated->empty())
  1618. return State;
  1619. if (!Call)
  1620. return getCheckerManager().runCheckersForPointerEscape(State,
  1621. *Invalidated,
  1622. 0,
  1623. PSK_EscapeOther,
  1624. &ITraits);
  1625. // If the symbols were invalidated by a call, we want to find out which ones
  1626. // were invalidated directly due to being arguments to the call.
  1627. InvalidatedSymbols SymbolsDirectlyInvalidated;
  1628. for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
  1629. E = ExplicitRegions.end(); I != E; ++I) {
  1630. if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
  1631. SymbolsDirectlyInvalidated.insert(R->getSymbol());
  1632. }
  1633. InvalidatedSymbols SymbolsIndirectlyInvalidated;
  1634. for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
  1635. E = Invalidated->end(); I!=E; ++I) {
  1636. SymbolRef sym = *I;
  1637. if (SymbolsDirectlyInvalidated.count(sym))
  1638. continue;
  1639. SymbolsIndirectlyInvalidated.insert(sym);
  1640. }
  1641. if (!SymbolsDirectlyInvalidated.empty())
  1642. State = getCheckerManager().runCheckersForPointerEscape(State,
  1643. SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
  1644. // Notify about the symbols that get indirectly invalidated by the call.
  1645. if (!SymbolsIndirectlyInvalidated.empty())
  1646. State = getCheckerManager().runCheckersForPointerEscape(State,
  1647. SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
  1648. return State;
  1649. }
  1650. /// evalBind - Handle the semantics of binding a value to a specific location.
  1651. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  1652. void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
  1653. ExplodedNode *Pred,
  1654. SVal location, SVal Val,
  1655. bool atDeclInit, const ProgramPoint *PP) {
  1656. const LocationContext *LC = Pred->getLocationContext();
  1657. PostStmt PS(StoreE, LC);
  1658. if (!PP)
  1659. PP = &PS;
  1660. // Do a previsit of the bind.
  1661. ExplodedNodeSet CheckedSet;
  1662. getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
  1663. StoreE, *this, *PP);
  1664. StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
  1665. // If the location is not a 'Loc', it will already be handled by
  1666. // the checkers. There is nothing left to do.
  1667. if (!location.getAs<Loc>()) {
  1668. const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/0, /*tag*/0);
  1669. ProgramStateRef state = Pred->getState();
  1670. state = processPointerEscapedOnBind(state, location, Val);
  1671. Bldr.generateNode(L, state, Pred);
  1672. return;
  1673. }
  1674. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  1675. I!=E; ++I) {
  1676. ExplodedNode *PredI = *I;
  1677. ProgramStateRef state = PredI->getState();
  1678. state = processPointerEscapedOnBind(state, location, Val);
  1679. // When binding the value, pass on the hint that this is a initialization.
  1680. // For initializations, we do not need to inform clients of region
  1681. // changes.
  1682. state = state->bindLoc(location.castAs<Loc>(),
  1683. Val, /* notifyChanges = */ !atDeclInit);
  1684. const MemRegion *LocReg = 0;
  1685. if (Optional<loc::MemRegionVal> LocRegVal =
  1686. location.getAs<loc::MemRegionVal>()) {
  1687. LocReg = LocRegVal->getRegion();
  1688. }
  1689. const ProgramPoint L = PostStore(StoreE, LC, LocReg, 0);
  1690. Bldr.generateNode(L, state, PredI);
  1691. }
  1692. }
  1693. /// evalStore - Handle the semantics of a store via an assignment.
  1694. /// @param Dst The node set to store generated state nodes
  1695. /// @param AssignE The assignment expression if the store happens in an
  1696. /// assignment.
  1697. /// @param LocationE The location expression that is stored to.
  1698. /// @param state The current simulation state
  1699. /// @param location The location to store the value
  1700. /// @param Val The value to be stored
  1701. void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
  1702. const Expr *LocationE,
  1703. ExplodedNode *Pred,
  1704. ProgramStateRef state, SVal location, SVal Val,
  1705. const ProgramPointTag *tag) {
  1706. // Proceed with the store. We use AssignE as the anchor for the PostStore
  1707. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  1708. const Expr *StoreE = AssignE ? AssignE : LocationE;
  1709. // Evaluate the location (checks for bad dereferences).
  1710. ExplodedNodeSet Tmp;
  1711. evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
  1712. if (Tmp.empty())
  1713. return;
  1714. if (location.isUndef())
  1715. return;
  1716. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
  1717. evalBind(Dst, StoreE, *NI, location, Val, false);
  1718. }
  1719. void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
  1720. const Expr *NodeEx,
  1721. const Expr *BoundEx,
  1722. ExplodedNode *Pred,
  1723. ProgramStateRef state,
  1724. SVal location,
  1725. const ProgramPointTag *tag,
  1726. QualType LoadTy)
  1727. {
  1728. assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
  1729. // Are we loading from a region? This actually results in two loads; one
  1730. // to fetch the address of the referenced value and one to fetch the
  1731. // referenced value.
  1732. if (const TypedValueRegion *TR =
  1733. dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
  1734. QualType ValTy = TR->getValueType();
  1735. if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
  1736. static SimpleProgramPointTag
  1737. loadReferenceTag("ExprEngine : Load Reference");
  1738. ExplodedNodeSet Tmp;
  1739. evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
  1740. location, &loadReferenceTag,
  1741. getContext().getPointerType(RT->getPointeeType()));
  1742. // Perform the load from the referenced value.
  1743. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
  1744. state = (*I)->getState();
  1745. location = state->getSVal(BoundEx, (*I)->getLocationContext());
  1746. evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
  1747. }
  1748. return;
  1749. }
  1750. }
  1751. evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
  1752. }
  1753. void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
  1754. const Expr *NodeEx,
  1755. const Expr *BoundEx,
  1756. ExplodedNode *Pred,
  1757. ProgramStateRef state,
  1758. SVal location,
  1759. const ProgramPointTag *tag,
  1760. QualType LoadTy) {
  1761. assert(NodeEx);
  1762. assert(BoundEx);
  1763. // Evaluate the location (checks for bad dereferences).
  1764. ExplodedNodeSet Tmp;
  1765. evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
  1766. if (Tmp.empty())
  1767. return;
  1768. StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  1769. if (location.isUndef())
  1770. return;
  1771. // Proceed with the load.
  1772. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
  1773. state = (*NI)->getState();
  1774. const LocationContext *LCtx = (*NI)->getLocationContext();
  1775. SVal V = UnknownVal();
  1776. if (location.isValid()) {
  1777. if (LoadTy.isNull())
  1778. LoadTy = BoundEx->getType();
  1779. V = state->getSVal(location.castAs<Loc>(), LoadTy);
  1780. }
  1781. Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
  1782. ProgramPoint::PostLoadKind);
  1783. }
  1784. }
  1785. void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
  1786. const Stmt *NodeEx,
  1787. const Stmt *BoundEx,
  1788. ExplodedNode *Pred,
  1789. ProgramStateRef state,
  1790. SVal location,
  1791. const ProgramPointTag *tag,
  1792. bool isLoad) {
  1793. StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
  1794. // Early checks for performance reason.
  1795. if (location.isUnknown()) {
  1796. return;
  1797. }
  1798. ExplodedNodeSet Src;
  1799. BldrTop.takeNodes(Pred);
  1800. StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
  1801. if (Pred->getState() != state) {
  1802. // Associate this new state with an ExplodedNode.
  1803. // FIXME: If I pass null tag, the graph is incorrect, e.g for
  1804. // int *p;
  1805. // p = 0;
  1806. // *p = 0xDEADBEEF;
  1807. // "p = 0" is not noted as "Null pointer value stored to 'p'" but
  1808. // instead "int *p" is noted as
  1809. // "Variable 'p' initialized to a null pointer value"
  1810. static SimpleProgramPointTag tag("ExprEngine: Location");
  1811. Bldr.generateNode(NodeEx, Pred, state, &tag);
  1812. }
  1813. ExplodedNodeSet Tmp;
  1814. getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
  1815. NodeEx, BoundEx, *this);
  1816. BldrTop.addNodes(Tmp);
  1817. }
  1818. std::pair<const ProgramPointTag *, const ProgramPointTag*>
  1819. ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
  1820. static SimpleProgramPointTag
  1821. eagerlyAssumeBinOpBifurcationTrue("ExprEngine : Eagerly Assume True"),
  1822. eagerlyAssumeBinOpBifurcationFalse("ExprEngine : Eagerly Assume False");
  1823. return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
  1824. &eagerlyAssumeBinOpBifurcationFalse);
  1825. }
  1826. void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
  1827. ExplodedNodeSet &Src,
  1828. const Expr *Ex) {
  1829. StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
  1830. for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
  1831. ExplodedNode *Pred = *I;
  1832. // Test if the previous node was as the same expression. This can happen
  1833. // when the expression fails to evaluate to anything meaningful and
  1834. // (as an optimization) we don't generate a node.
  1835. ProgramPoint P = Pred->getLocation();
  1836. if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
  1837. continue;
  1838. }
  1839. ProgramStateRef state = Pred->getState();
  1840. SVal V = state->getSVal(Ex, Pred->getLocationContext());
  1841. Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
  1842. if (SEV && SEV->isExpression()) {
  1843. const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
  1844. geteagerlyAssumeBinOpBifurcationTags();
  1845. ProgramStateRef StateTrue, StateFalse;
  1846. tie(StateTrue, StateFalse) = state->assume(*SEV);
  1847. // First assume that the condition is true.
  1848. if (StateTrue) {
  1849. SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
  1850. StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
  1851. Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
  1852. }
  1853. // Next, assume that the condition is false.
  1854. if (StateFalse) {
  1855. SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
  1856. StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
  1857. Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
  1858. }
  1859. }
  1860. }
  1861. }
  1862. void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
  1863. ExplodedNodeSet &Dst) {
  1864. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  1865. // We have processed both the inputs and the outputs. All of the outputs
  1866. // should evaluate to Locs. Nuke all of their values.
  1867. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  1868. // which interprets the inline asm and stores proper results in the
  1869. // outputs.
  1870. ProgramStateRef state = Pred->getState();
  1871. for (GCCAsmStmt::const_outputs_iterator OI = A->begin_outputs(),
  1872. OE = A->end_outputs(); OI != OE; ++OI) {
  1873. SVal X = state->getSVal(*OI, Pred->getLocationContext());
  1874. assert (!X.getAs<NonLoc>()); // Should be an Lval, or unknown, undef.
  1875. if (Optional<Loc> LV = X.getAs<Loc>())
  1876. state = state->bindLoc(*LV, UnknownVal());
  1877. }
  1878. Bldr.generateNode(A, Pred, state);
  1879. }
  1880. void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
  1881. ExplodedNodeSet &Dst) {
  1882. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  1883. Bldr.generateNode(A, Pred, Pred->getState());
  1884. }
  1885. //===----------------------------------------------------------------------===//
  1886. // Visualization.
  1887. //===----------------------------------------------------------------------===//
  1888. #ifndef NDEBUG
  1889. static ExprEngine* GraphPrintCheckerState;
  1890. static SourceManager* GraphPrintSourceManager;
  1891. namespace llvm {
  1892. template<>
  1893. struct DOTGraphTraits<ExplodedNode*> :
  1894. public DefaultDOTGraphTraits {
  1895. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  1896. // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
  1897. // work.
  1898. static std::string getNodeAttributes(const ExplodedNode *N, void*) {
  1899. #if 0
  1900. // FIXME: Replace with a general scheme to tell if the node is
  1901. // an error node.
  1902. if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
  1903. GraphPrintCheckerState->isExplicitNullDeref(N) ||
  1904. GraphPrintCheckerState->isUndefDeref(N) ||
  1905. GraphPrintCheckerState->isUndefStore(N) ||
  1906. GraphPrintCheckerState->isUndefControlFlow(N) ||
  1907. GraphPrintCheckerState->isUndefResult(N) ||
  1908. GraphPrintCheckerState->isBadCall(N) ||
  1909. GraphPrintCheckerState->isUndefArg(N))
  1910. return "color=\"red\",style=\"filled\"";
  1911. if (GraphPrintCheckerState->isNoReturnCall(N))
  1912. return "color=\"blue\",style=\"filled\"";
  1913. #endif
  1914. return "";
  1915. }
  1916. static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
  1917. if (SLoc.isFileID()) {
  1918. Out << "\\lline="
  1919. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  1920. << " col="
  1921. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
  1922. << "\\l";
  1923. }
  1924. }
  1925. static std::string getNodeLabel(const ExplodedNode *N, void*){
  1926. std::string sbuf;
  1927. llvm::raw_string_ostream Out(sbuf);
  1928. // Program Location.
  1929. ProgramPoint Loc = N->getLocation();
  1930. switch (Loc.getKind()) {
  1931. case ProgramPoint::BlockEntranceKind: {
  1932. Out << "Block Entrance: B"
  1933. << Loc.castAs<BlockEntrance>().getBlock()->getBlockID();
  1934. if (const NamedDecl *ND =
  1935. dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
  1936. Out << " (";
  1937. ND->printName(Out);
  1938. Out << ")";
  1939. }
  1940. break;
  1941. }
  1942. case ProgramPoint::BlockExitKind:
  1943. assert (false);
  1944. break;
  1945. case ProgramPoint::CallEnterKind:
  1946. Out << "CallEnter";
  1947. break;
  1948. case ProgramPoint::CallExitBeginKind:
  1949. Out << "CallExitBegin";
  1950. break;
  1951. case ProgramPoint::CallExitEndKind:
  1952. Out << "CallExitEnd";
  1953. break;
  1954. case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
  1955. Out << "PostStmtPurgeDeadSymbols";
  1956. break;
  1957. case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
  1958. Out << "PreStmtPurgeDeadSymbols";
  1959. break;
  1960. case ProgramPoint::EpsilonKind:
  1961. Out << "Epsilon Point";
  1962. break;
  1963. case ProgramPoint::PreImplicitCallKind: {
  1964. ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
  1965. Out << "PreCall: ";
  1966. // FIXME: Get proper printing options.
  1967. PC.getDecl()->print(Out, LangOptions());
  1968. printLocation(Out, PC.getLocation());
  1969. break;
  1970. }
  1971. case ProgramPoint::PostImplicitCallKind: {
  1972. ImplicitCallPoint PC = Loc.castAs<ImplicitCallPoint>();
  1973. Out << "PostCall: ";
  1974. // FIXME: Get proper printing options.
  1975. PC.getDecl()->print(Out, LangOptions());
  1976. printLocation(Out, PC.getLocation());
  1977. break;
  1978. }
  1979. case ProgramPoint::PostInitializerKind: {
  1980. Out << "PostInitializer: ";
  1981. const CXXCtorInitializer *Init =
  1982. Loc.castAs<PostInitializer>().getInitializer();
  1983. if (const FieldDecl *FD = Init->getAnyMember())
  1984. Out << *FD;
  1985. else {
  1986. QualType Ty = Init->getTypeSourceInfo()->getType();
  1987. Ty = Ty.getLocalUnqualifiedType();
  1988. LangOptions LO; // FIXME.
  1989. Ty.print(Out, LO);
  1990. }
  1991. break;
  1992. }
  1993. case ProgramPoint::BlockEdgeKind: {
  1994. const BlockEdge &E = Loc.castAs<BlockEdge>();
  1995. Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
  1996. << E.getDst()->getBlockID() << ')';
  1997. if (const Stmt *T = E.getSrc()->getTerminator()) {
  1998. SourceLocation SLoc = T->getLocStart();
  1999. Out << "\\|Terminator: ";
  2000. LangOptions LO; // FIXME.
  2001. E.getSrc()->printTerminator(Out, LO);
  2002. if (SLoc.isFileID()) {
  2003. Out << "\\lline="
  2004. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  2005. << " col="
  2006. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
  2007. }
  2008. if (isa<SwitchStmt>(T)) {
  2009. const Stmt *Label = E.getDst()->getLabel();
  2010. if (Label) {
  2011. if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
  2012. Out << "\\lcase ";
  2013. LangOptions LO; // FIXME.
  2014. C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
  2015. if (const Stmt *RHS = C->getRHS()) {
  2016. Out << " .. ";
  2017. RHS->printPretty(Out, 0, PrintingPolicy(LO));
  2018. }
  2019. Out << ":";
  2020. }
  2021. else {
  2022. assert (isa<DefaultStmt>(Label));
  2023. Out << "\\ldefault:";
  2024. }
  2025. }
  2026. else
  2027. Out << "\\l(implicit) default:";
  2028. }
  2029. else if (isa<IndirectGotoStmt>(T)) {
  2030. // FIXME
  2031. }
  2032. else {
  2033. Out << "\\lCondition: ";
  2034. if (*E.getSrc()->succ_begin() == E.getDst())
  2035. Out << "true";
  2036. else
  2037. Out << "false";
  2038. }
  2039. Out << "\\l";
  2040. }
  2041. #if 0
  2042. // FIXME: Replace with a general scheme to determine
  2043. // the name of the check.
  2044. if (GraphPrintCheckerState->isUndefControlFlow(N)) {
  2045. Out << "\\|Control-flow based on\\lUndefined value.\\l";
  2046. }
  2047. #endif
  2048. break;
  2049. }
  2050. default: {
  2051. const Stmt *S = Loc.castAs<StmtPoint>().getStmt();
  2052. Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
  2053. LangOptions LO; // FIXME.
  2054. S->printPretty(Out, 0, PrintingPolicy(LO));
  2055. printLocation(Out, S->getLocStart());
  2056. if (Loc.getAs<PreStmt>())
  2057. Out << "\\lPreStmt\\l;";
  2058. else if (Loc.getAs<PostLoad>())
  2059. Out << "\\lPostLoad\\l;";
  2060. else if (Loc.getAs<PostStore>())
  2061. Out << "\\lPostStore\\l";
  2062. else if (Loc.getAs<PostLValue>())
  2063. Out << "\\lPostLValue\\l";
  2064. #if 0
  2065. // FIXME: Replace with a general scheme to determine
  2066. // the name of the check.
  2067. if (GraphPrintCheckerState->isImplicitNullDeref(N))
  2068. Out << "\\|Implicit-Null Dereference.\\l";
  2069. else if (GraphPrintCheckerState->isExplicitNullDeref(N))
  2070. Out << "\\|Explicit-Null Dereference.\\l";
  2071. else if (GraphPrintCheckerState->isUndefDeref(N))
  2072. Out << "\\|Dereference of undefialied value.\\l";
  2073. else if (GraphPrintCheckerState->isUndefStore(N))
  2074. Out << "\\|Store to Undefined Loc.";
  2075. else if (GraphPrintCheckerState->isUndefResult(N))
  2076. Out << "\\|Result of operation is undefined.";
  2077. else if (GraphPrintCheckerState->isNoReturnCall(N))
  2078. Out << "\\|Call to function marked \"noreturn\".";
  2079. else if (GraphPrintCheckerState->isBadCall(N))
  2080. Out << "\\|Call to NULL/Undefined.";
  2081. else if (GraphPrintCheckerState->isUndefArg(N))
  2082. Out << "\\|Argument in call is undefined";
  2083. #endif
  2084. break;
  2085. }
  2086. }
  2087. ProgramStateRef state = N->getState();
  2088. Out << "\\|StateID: " << (const void*) state.getPtr()
  2089. << " NodeID: " << (const void*) N << "\\|";
  2090. state->printDOT(Out);
  2091. Out << "\\l";
  2092. if (const ProgramPointTag *tag = Loc.getTag()) {
  2093. Out << "\\|Tag: " << tag->getTagDescription();
  2094. Out << "\\l";
  2095. }
  2096. return Out.str();
  2097. }
  2098. };
  2099. } // end llvm namespace
  2100. #endif
  2101. #ifndef NDEBUG
  2102. template <typename ITERATOR>
  2103. ExplodedNode *GetGraphNode(ITERATOR I) { return *I; }
  2104. template <> ExplodedNode*
  2105. GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
  2106. (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
  2107. return I->first;
  2108. }
  2109. #endif
  2110. void ExprEngine::ViewGraph(bool trim) {
  2111. #ifndef NDEBUG
  2112. if (trim) {
  2113. std::vector<const ExplodedNode*> Src;
  2114. // Flush any outstanding reports to make sure we cover all the nodes.
  2115. // This does not cause them to get displayed.
  2116. for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
  2117. const_cast<BugType*>(*I)->FlushReports(BR);
  2118. // Iterate through the reports and get their nodes.
  2119. for (BugReporter::EQClasses_iterator
  2120. EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
  2121. ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
  2122. if (N) Src.push_back(N);
  2123. }
  2124. ViewGraph(Src);
  2125. }
  2126. else {
  2127. GraphPrintCheckerState = this;
  2128. GraphPrintSourceManager = &getContext().getSourceManager();
  2129. llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
  2130. GraphPrintCheckerState = NULL;
  2131. GraphPrintSourceManager = NULL;
  2132. }
  2133. #endif
  2134. }
  2135. void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
  2136. #ifndef NDEBUG
  2137. GraphPrintCheckerState = this;
  2138. GraphPrintSourceManager = &getContext().getSourceManager();
  2139. OwningPtr<ExplodedGraph> TrimmedG(G.trim(Nodes));
  2140. if (!TrimmedG.get())
  2141. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  2142. else
  2143. llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
  2144. GraphPrintCheckerState = NULL;
  2145. GraphPrintSourceManager = NULL;
  2146. #endif
  2147. }