1 //== Environment.cpp - Map from Stmt* to Locations/Values -------*- 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 defined the Environment and EnvironmentManager classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ExprCXX.h"
15 #include "clang/AST/ExprObjC.h"
16 #include "clang/Analysis/AnalysisContext.h"
17 #include "clang/Analysis/CFG.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
19 
20 using namespace clang;
21 using namespace ento;
22 
23 SVal Environment::lookupExpr(const EnvironmentEntry &E) const {
24   const SVal* X = ExprBindings.lookup(E);
25   if (X) {
26     SVal V = *X;
27     return V;
28   }
29   return UnknownVal();
30 }
31 
32 SVal Environment::getSVal(const EnvironmentEntry &Entry,
33                           SValBuilder& svalBuilder,
34                           bool useOnlyDirectBindings) const {
35 
36   if (useOnlyDirectBindings) {
37     // This branch is rarely taken, but can be exercised by
38     // checkers that explicitly bind values to arbitrary
39     // expressions.  It is crucial that we do not ignore any
40     // expression here, and do a direct lookup.
41     return lookupExpr(Entry);
42   }
43 
44   const Stmt *E = Entry.getStmt();
45   const LocationContext *LCtx = Entry.getLocationContext();
46 
47   for (;;) {
48     if (const Expr *Ex = dyn_cast<Expr>(E))
49       E = Ex->IgnoreParens();
50 
51     switch (E->getStmtClass()) {
52       case Stmt::AddrLabelExprClass:
53         return svalBuilder.makeLoc(cast<AddrLabelExpr>(E));
54       case Stmt::OpaqueValueExprClass: {
55         const OpaqueValueExpr *ope = cast<OpaqueValueExpr>(E);
56         E = ope->getSourceExpr();
57         continue;
58       }
59       case Stmt::ParenExprClass:
60       case Stmt::GenericSelectionExprClass:
61         llvm_unreachable("ParenExprs and GenericSelectionExprs should "
62                          "have been handled by IgnoreParens()");
63       case Stmt::CharacterLiteralClass: {
64         const CharacterLiteral* C = cast<CharacterLiteral>(E);
65         return svalBuilder.makeIntVal(C->getValue(), C->getType());
66       }
67       case Stmt::CXXBoolLiteralExprClass: {
68         const SVal *X = ExprBindings.lookup(EnvironmentEntry(E, LCtx));
69         if (X)
70           return *X;
71         else
72           return svalBuilder.makeBoolVal(cast<CXXBoolLiteralExpr>(E));
73       }
74       case Stmt::CXXScalarValueInitExprClass:
75       case Stmt::ImplicitValueInitExprClass: {
76         QualType Ty = cast<Expr>(E)->getType();
77         return svalBuilder.makeZeroVal(Ty);
78       }
79       case Stmt::IntegerLiteralClass: {
80         // In C++, this expression may have been bound to a temporary object.
81         SVal const *X = ExprBindings.lookup(EnvironmentEntry(E, LCtx));
82         if (X)
83           return *X;
84         else
85           return svalBuilder.makeIntVal(cast<IntegerLiteral>(E));
86       }
87       case Stmt::ObjCBoolLiteralExprClass:
88         return svalBuilder.makeBoolVal(cast<ObjCBoolLiteralExpr>(E));
89 
90       // For special C0xx nullptr case, make a null pointer SVal.
91       case Stmt::CXXNullPtrLiteralExprClass:
92         return svalBuilder.makeNull();
93       case Stmt::ExprWithCleanupsClass:
94         E = cast<ExprWithCleanups>(E)->getSubExpr();
95         continue;
96       case Stmt::CXXBindTemporaryExprClass:
97         E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
98         continue;
99       case Stmt::SubstNonTypeTemplateParmExprClass:
100         E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
101         continue;
102       case Stmt::ObjCStringLiteralClass: {
103         MemRegionManager &MRMgr = svalBuilder.getRegionManager();
104         const ObjCStringLiteral *SL = cast<ObjCStringLiteral>(E);
105         return svalBuilder.makeLoc(MRMgr.getObjCStringRegion(SL));
106       }
107       case Stmt::StringLiteralClass: {
108         MemRegionManager &MRMgr = svalBuilder.getRegionManager();
109         const StringLiteral *SL = cast<StringLiteral>(E);
110         return svalBuilder.makeLoc(MRMgr.getStringRegion(SL));
111       }
112       case Stmt::ReturnStmtClass: {
113         const ReturnStmt *RS = cast<ReturnStmt>(E);
114         if (const Expr *RE = RS->getRetValue()) {
115           E = RE;
116           continue;
117         }
118         return UndefinedVal();
119       }
120 
121       // Handle all other Stmt* using a lookup.
122       default:
123         break;
124     };
125     break;
126   }
127   return lookupExpr(EnvironmentEntry(E, LCtx));
128 }
129 
130 Environment EnvironmentManager::bindExpr(Environment Env,
131                                          const EnvironmentEntry &E,
132                                          SVal V,
133                                          bool Invalidate) {
134   if (V.isUnknown()) {
135     if (Invalidate)
136       return Environment(F.remove(Env.ExprBindings, E));
137     else
138       return Env;
139   }
140   return Environment(F.add(Env.ExprBindings, E, V));
141 }
142 
143 static inline EnvironmentEntry MakeLocation(const EnvironmentEntry &E) {
144   const Stmt *S = E.getStmt();
145   S = (const Stmt*) (((uintptr_t) S) | 0x1);
146   return EnvironmentEntry(S, E.getLocationContext());
147 }
148 
149 Environment EnvironmentManager::bindExprAndLocation(Environment Env,
150                                                     const EnvironmentEntry &E,
151                                                     SVal location, SVal V) {
152   return Environment(F.add(F.add(Env.ExprBindings, MakeLocation(E), location),
153                            E, V));
154 }
155 
156 namespace {
157 class MarkLiveCallback : public SymbolVisitor {
158   SymbolReaper &SymReaper;
159 public:
160   MarkLiveCallback(SymbolReaper &symreaper) : SymReaper(symreaper) {}
161   bool VisitSymbol(SymbolRef sym) {
162     SymReaper.markLive(sym);
163     return true;
164   }
165   bool VisitMemRegion(const MemRegion *R) {
166     SymReaper.markLive(R);
167     return true;
168   }
169 };
170 } // end anonymous namespace
171 
172 // In addition to mapping from EnvironmentEntry - > SVals in the Environment,
173 // we also maintain a mapping from EnvironmentEntry -> SVals (locations)
174 // that were used during a load and store.
175 static inline bool IsLocation(const EnvironmentEntry &E) {
176   const Stmt *S = E.getStmt();
177   return (bool) (((uintptr_t) S) & 0x1);
178 }
179 
180 // removeDeadBindings:
181 //  - Remove subexpression bindings.
182 //  - Remove dead block expression bindings.
183 //  - Keep live block expression bindings:
184 //   - Mark their reachable symbols live in SymbolReaper,
185 //     see ScanReachableSymbols.
186 //   - Mark the region in DRoots if the binding is a loc::MemRegionVal.
187 Environment
188 EnvironmentManager::removeDeadBindings(Environment Env,
189                                        SymbolReaper &SymReaper,
190                                        ProgramStateRef ST) {
191 
192   // We construct a new Environment object entirely, as this is cheaper than
193   // individually removing all the subexpression bindings (which will greatly
194   // outnumber block-level expression bindings).
195   Environment NewEnv = getInitialEnvironment();
196 
197   SmallVector<std::pair<EnvironmentEntry, SVal>, 10> deferredLocations;
198 
199   MarkLiveCallback CB(SymReaper);
200   ScanReachableSymbols RSScaner(ST, CB);
201 
202   llvm::ImmutableMapRef<EnvironmentEntry,SVal>
203     EBMapRef(NewEnv.ExprBindings.getRootWithoutRetain(),
204              F.getTreeFactory());
205 
206   // Iterate over the block-expr bindings.
207   for (Environment::iterator I = Env.begin(), E = Env.end();
208        I != E; ++I) {
209 
210     const EnvironmentEntry &BlkExpr = I.getKey();
211     // For recorded locations (used when evaluating loads and stores), we
212     // consider them live only when their associated normal expression is
213     // also live.
214     // NOTE: This assumes that loads/stores that evaluated to UnknownVal
215     // still have an entry in the map.
216     if (IsLocation(BlkExpr)) {
217       deferredLocations.push_back(std::make_pair(BlkExpr, I.getData()));
218       continue;
219     }
220     const SVal &X = I.getData();
221 
222     if (SymReaper.isLive(BlkExpr.getStmt(), BlkExpr.getLocationContext())) {
223       // Copy the binding to the new map.
224       EBMapRef = EBMapRef.add(BlkExpr, X);
225 
226       // If the block expr's value is a memory region, then mark that region.
227       if (isa<loc::MemRegionVal>(X)) {
228         const MemRegion *R = cast<loc::MemRegionVal>(X).getRegion();
229         SymReaper.markLive(R);
230       }
231 
232       // Mark all symbols in the block expr's value live.
233       RSScaner.scan(X);
234       continue;
235     }
236   }
237 
238   // Go through he deferred locations and add them to the new environment if
239   // the correspond Stmt* is in the map as well.
240   for (SmallVectorImpl<std::pair<EnvironmentEntry, SVal> >::iterator
241       I = deferredLocations.begin(), E = deferredLocations.end(); I != E; ++I) {
242     const EnvironmentEntry &En = I->first;
243     const Stmt *S = (Stmt*) (((uintptr_t) En.getStmt()) & (uintptr_t) ~0x1);
244     if (EBMapRef.lookup(EnvironmentEntry(S, En.getLocationContext())))
245       EBMapRef = EBMapRef.add(En, I->second);
246   }
247 
248   NewEnv.ExprBindings = EBMapRef.asImmutableMap();
249   return NewEnv;
250 }
251 
252 void Environment::print(raw_ostream &Out, const char *NL,
253                         const char *Sep) const {
254   printAux(Out, false, NL, Sep);
255   printAux(Out, true, NL, Sep);
256 }
257 
258 void Environment::printAux(raw_ostream &Out, bool printLocations,
259                            const char *NL,
260                            const char *Sep) const{
261 
262   bool isFirst = true;
263 
264   for (Environment::iterator I = begin(), E = end(); I != E; ++I) {
265     const EnvironmentEntry &En = I.getKey();
266     if (IsLocation(En)) {
267       if (!printLocations)
268         continue;
269     }
270     else {
271       if (printLocations)
272         continue;
273     }
274 
275     if (isFirst) {
276       Out << NL << NL
277           << (printLocations ? "Load/Store locations:" : "Expressions:")
278           << NL;
279       isFirst = false;
280     } else {
281       Out << NL;
282     }
283 
284     const Stmt *S = En.getStmt();
285     if (printLocations) {
286       S = (Stmt*) (((uintptr_t) S) & ((uintptr_t) ~0x1));
287     }
288 
289     Out << " (" << (void*) En.getLocationContext() << ',' << (void*) S << ") ";
290     LangOptions LO; // FIXME.
291     S->printPretty(Out, 0, PrintingPolicy(LO));
292     Out << " : " << I.getData();
293   }
294 }
295