ExprEngine.cpp 93 KB

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