1 // SValBuilder.cpp - Basic class for all SValBuilder implementations -*- 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 SValBuilder, the base class for all (complete) SValBuilder
11 //  implementations.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
22 
23 using namespace clang;
24 using namespace ento;
25 
26 //===----------------------------------------------------------------------===//
27 // Basic SVal creation.
28 //===----------------------------------------------------------------------===//
29 
30 void SValBuilder::anchor() { }
31 
32 DefinedOrUnknownSVal SValBuilder::makeZeroVal(QualType type) {
33   if (Loc::isLocType(type))
34     return makeNull();
35 
36   if (type->isIntegralOrEnumerationType())
37     return makeIntVal(0, type);
38 
39   // FIXME: Handle floats.
40   // FIXME: Handle structs.
41   return UnknownVal();
42 }
43 
44 NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
45                                 const llvm::APSInt& rhs, QualType type) {
46   // The Environment ensures we always get a persistent APSInt in
47   // BasicValueFactory, so we don't need to get the APSInt from
48   // BasicValueFactory again.
49   assert(lhs);
50   assert(!Loc::isLocType(type));
51   return nonloc::SymbolVal(SymMgr.getSymIntExpr(lhs, op, rhs, type));
52 }
53 
54 NonLoc SValBuilder::makeNonLoc(const llvm::APSInt& lhs,
55                                BinaryOperator::Opcode op, const SymExpr *rhs,
56                                QualType type) {
57   assert(rhs);
58   assert(!Loc::isLocType(type));
59   return nonloc::SymbolVal(SymMgr.getIntSymExpr(lhs, op, rhs, type));
60 }
61 
62 NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
63                                const SymExpr *rhs, QualType type) {
64   assert(lhs && rhs);
65   assert(!Loc::isLocType(type));
66   return nonloc::SymbolVal(SymMgr.getSymSymExpr(lhs, op, rhs, type));
67 }
68 
69 NonLoc SValBuilder::makeNonLoc(const SymExpr *operand,
70                                QualType fromTy, QualType toTy) {
71   assert(operand);
72   assert(!Loc::isLocType(toTy));
73   return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy));
74 }
75 
76 SVal SValBuilder::convertToArrayIndex(SVal val) {
77   if (val.isUnknownOrUndef())
78     return val;
79 
80   // Common case: we have an appropriately sized integer.
81   if (Optional<nonloc::ConcreteInt> CI = val.getAs<nonloc::ConcreteInt>()) {
82     const llvm::APSInt& I = CI->getValue();
83     if (I.getBitWidth() == ArrayIndexWidth && I.isSigned())
84       return val;
85   }
86 
87   return evalCastFromNonLoc(val.castAs<NonLoc>(), ArrayIndexTy);
88 }
89 
90 nonloc::ConcreteInt SValBuilder::makeBoolVal(const CXXBoolLiteralExpr *boolean){
91   return makeTruthVal(boolean->getValue());
92 }
93 
94 DefinedOrUnknownSVal
95 SValBuilder::getRegionValueSymbolVal(const TypedValueRegion* region) {
96   QualType T = region->getValueType();
97 
98   if (!SymbolManager::canSymbolicate(T))
99     return UnknownVal();
100 
101   SymbolRef sym = SymMgr.getRegionValueSymbol(region);
102 
103   if (Loc::isLocType(T))
104     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
105 
106   return nonloc::SymbolVal(sym);
107 }
108 
109 DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const void *SymbolTag,
110                                                    const Expr *Ex,
111                                                    const LocationContext *LCtx,
112                                                    unsigned Count) {
113   QualType T = Ex->getType();
114 
115   // Compute the type of the result. If the expression is not an R-value, the
116   // result should be a location.
117   QualType ExType = Ex->getType();
118   if (Ex->isGLValue())
119     T = LCtx->getAnalysisDeclContext()->getASTContext().getPointerType(ExType);
120 
121   return conjureSymbolVal(SymbolTag, Ex, LCtx, T, Count);
122 }
123 
124 DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const void *symbolTag,
125                                                    const Expr *expr,
126                                                    const LocationContext *LCtx,
127                                                    QualType type,
128                                                    unsigned count) {
129   if (!SymbolManager::canSymbolicate(type))
130     return UnknownVal();
131 
132   SymbolRef sym = SymMgr.conjureSymbol(expr, LCtx, type, count, symbolTag);
133 
134   if (Loc::isLocType(type))
135     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
136 
137   return nonloc::SymbolVal(sym);
138 }
139 
140 
141 DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const Stmt *stmt,
142                                                    const LocationContext *LCtx,
143                                                    QualType type,
144                                                    unsigned visitCount) {
145   if (!SymbolManager::canSymbolicate(type))
146     return UnknownVal();
147 
148   SymbolRef sym = SymMgr.conjureSymbol(stmt, LCtx, type, visitCount);
149 
150   if (Loc::isLocType(type))
151     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
152 
153   return nonloc::SymbolVal(sym);
154 }
155 
156 DefinedOrUnknownSVal
157 SValBuilder::getConjuredHeapSymbolVal(const Expr *E,
158                                       const LocationContext *LCtx,
159                                       unsigned VisitCount) {
160   QualType T = E->getType();
161   assert(Loc::isLocType(T));
162   assert(SymbolManager::canSymbolicate(T));
163 
164   SymbolRef sym = SymMgr.conjureSymbol(E, LCtx, T, VisitCount);
165   return loc::MemRegionVal(MemMgr.getSymbolicHeapRegion(sym));
166 }
167 
168 DefinedSVal SValBuilder::getMetadataSymbolVal(const void *symbolTag,
169                                               const MemRegion *region,
170                                               const Expr *expr, QualType type,
171                                               unsigned count) {
172   assert(SymbolManager::canSymbolicate(type) && "Invalid metadata symbol type");
173 
174   SymbolRef sym =
175       SymMgr.getMetadataSymbol(region, expr, type, count, symbolTag);
176 
177   if (Loc::isLocType(type))
178     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
179 
180   return nonloc::SymbolVal(sym);
181 }
182 
183 DefinedOrUnknownSVal
184 SValBuilder::getDerivedRegionValueSymbolVal(SymbolRef parentSymbol,
185                                              const TypedValueRegion *region) {
186   QualType T = region->getValueType();
187 
188   if (!SymbolManager::canSymbolicate(T))
189     return UnknownVal();
190 
191   SymbolRef sym = SymMgr.getDerivedSymbol(parentSymbol, region);
192 
193   if (Loc::isLocType(T))
194     return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
195 
196   return nonloc::SymbolVal(sym);
197 }
198 
199 DefinedSVal SValBuilder::getFunctionPointer(const FunctionDecl *func) {
200   return loc::MemRegionVal(MemMgr.getFunctionTextRegion(func));
201 }
202 
203 DefinedSVal SValBuilder::getBlockPointer(const BlockDecl *block,
204                                          CanQualType locTy,
205                                          const LocationContext *locContext) {
206   const BlockTextRegion *BC =
207     MemMgr.getBlockTextRegion(block, locTy, locContext->getAnalysisDeclContext());
208   const BlockDataRegion *BD = MemMgr.getBlockDataRegion(BC, locContext);
209   return loc::MemRegionVal(BD);
210 }
211 
212 /// Return a memory region for the 'this' object reference.
213 loc::MemRegionVal SValBuilder::getCXXThis(const CXXMethodDecl *D,
214                                           const StackFrameContext *SFC) {
215   return loc::MemRegionVal(getRegionManager().
216                            getCXXThisRegion(D->getThisType(getContext()), SFC));
217 }
218 
219 /// Return a memory region for the 'this' object reference.
220 loc::MemRegionVal SValBuilder::getCXXThis(const CXXRecordDecl *D,
221                                           const StackFrameContext *SFC) {
222   const Type *T = D->getTypeForDecl();
223   QualType PT = getContext().getPointerType(QualType(T, 0));
224   return loc::MemRegionVal(getRegionManager().getCXXThisRegion(PT, SFC));
225 }
226 
227 //===----------------------------------------------------------------------===//
228 
229 SVal SValBuilder::makeSymExprValNN(ProgramStateRef State,
230                                    BinaryOperator::Opcode Op,
231                                    NonLoc LHS, NonLoc RHS,
232                                    QualType ResultTy) {
233   if (!State->isTainted(RHS) && !State->isTainted(LHS))
234     return UnknownVal();
235 
236   const SymExpr *symLHS = LHS.getAsSymExpr();
237   const SymExpr *symRHS = RHS.getAsSymExpr();
238   // TODO: When the Max Complexity is reached, we should conjure a symbol
239   // instead of generating an Unknown value and propagate the taint info to it.
240   const unsigned MaxComp = 10000; // 100000 28X
241 
242   if (symLHS && symRHS &&
243       (symLHS->computeComplexity() + symRHS->computeComplexity()) <  MaxComp)
244     return makeNonLoc(symLHS, Op, symRHS, ResultTy);
245 
246   if (symLHS && symLHS->computeComplexity() < MaxComp)
247     if (Optional<nonloc::ConcreteInt> rInt = RHS.getAs<nonloc::ConcreteInt>())
248       return makeNonLoc(symLHS, Op, rInt->getValue(), ResultTy);
249 
250   if (symRHS && symRHS->computeComplexity() < MaxComp)
251     if (Optional<nonloc::ConcreteInt> lInt = LHS.getAs<nonloc::ConcreteInt>())
252       return makeNonLoc(lInt->getValue(), Op, symRHS, ResultTy);
253 
254   return UnknownVal();
255 }
256 
257 
258 SVal SValBuilder::evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
259                             SVal lhs, SVal rhs, QualType type) {
260 
261   if (lhs.isUndef() || rhs.isUndef())
262     return UndefinedVal();
263 
264   if (lhs.isUnknown() || rhs.isUnknown())
265     return UnknownVal();
266 
267   if (Optional<Loc> LV = lhs.getAs<Loc>()) {
268     if (Optional<Loc> RV = rhs.getAs<Loc>())
269       return evalBinOpLL(state, op, *LV, *RV, type);
270 
271     return evalBinOpLN(state, op, *LV, rhs.castAs<NonLoc>(), type);
272   }
273 
274   if (Optional<Loc> RV = rhs.getAs<Loc>()) {
275     // Support pointer arithmetic where the addend is on the left
276     // and the pointer on the right.
277     assert(op == BO_Add);
278 
279     // Commute the operands.
280     return evalBinOpLN(state, op, *RV, lhs.castAs<NonLoc>(), type);
281   }
282 
283   return evalBinOpNN(state, op, lhs.castAs<NonLoc>(), rhs.castAs<NonLoc>(),
284                      type);
285 }
286 
287 DefinedOrUnknownSVal SValBuilder::evalEQ(ProgramStateRef state,
288                                          DefinedOrUnknownSVal lhs,
289                                          DefinedOrUnknownSVal rhs) {
290   return evalBinOp(state, BO_EQ, lhs, rhs, Context.IntTy)
291       .castAs<DefinedOrUnknownSVal>();
292 }
293 
294 /// Recursively check if the pointer types are equal modulo const, volatile,
295 /// and restrict qualifiers. Also, assume that all types are similar to 'void'.
296 /// Assumes the input types are canonical.
297 static bool shouldBeModeledWithNoOp(ASTContext &Context, QualType ToTy,
298                                                          QualType FromTy) {
299   while (Context.UnwrapSimilarPointerTypes(ToTy, FromTy)) {
300     Qualifiers Quals1, Quals2;
301     ToTy = Context.getUnqualifiedArrayType(ToTy, Quals1);
302     FromTy = Context.getUnqualifiedArrayType(FromTy, Quals2);
303 
304     // Make sure that non cvr-qualifiers the other qualifiers (e.g., address
305     // spaces) are identical.
306     Quals1.removeCVRQualifiers();
307     Quals2.removeCVRQualifiers();
308     if (Quals1 != Quals2)
309       return false;
310   }
311 
312   // If we are casting to void, the 'From' value can be used to represent the
313   // 'To' value.
314   if (ToTy->isVoidType())
315     return true;
316 
317   if (ToTy != FromTy)
318     return false;
319 
320   return true;
321 }
322 
323 // FIXME: should rewrite according to the cast kind.
324 SVal SValBuilder::evalCast(SVal val, QualType castTy, QualType originalTy) {
325   castTy = Context.getCanonicalType(castTy);
326   originalTy = Context.getCanonicalType(originalTy);
327   if (val.isUnknownOrUndef() || castTy == originalTy)
328     return val;
329 
330   // For const casts, casts to void, just propagate the value.
331   if (!castTy->isVariableArrayType() && !originalTy->isVariableArrayType())
332     if (shouldBeModeledWithNoOp(Context, Context.getPointerType(castTy),
333                                          Context.getPointerType(originalTy)))
334       return val;
335 
336   // Check for casts from pointers to integers.
337   if (castTy->isIntegralOrEnumerationType() && Loc::isLocType(originalTy))
338     return evalCastFromLoc(val.castAs<Loc>(), castTy);
339 
340   // Check for casts from integers to pointers.
341   if (Loc::isLocType(castTy) && originalTy->isIntegralOrEnumerationType()) {
342     if (Optional<nonloc::LocAsInteger> LV = val.getAs<nonloc::LocAsInteger>()) {
343       if (const MemRegion *R = LV->getLoc().getAsRegion()) {
344         StoreManager &storeMgr = StateMgr.getStoreManager();
345         R = storeMgr.castRegion(R, castTy);
346         return R ? SVal(loc::MemRegionVal(R)) : UnknownVal();
347       }
348       return LV->getLoc();
349     }
350     return dispatchCast(val, castTy);
351   }
352 
353   // Just pass through function and block pointers.
354   if (originalTy->isBlockPointerType() || originalTy->isFunctionPointerType()) {
355     assert(Loc::isLocType(castTy));
356     return val;
357   }
358 
359   // Check for casts from array type to another type.
360   if (originalTy->isArrayType()) {
361     // We will always decay to a pointer.
362     val = StateMgr.ArrayToPointer(val.castAs<Loc>());
363 
364     // Are we casting from an array to a pointer?  If so just pass on
365     // the decayed value.
366     if (castTy->isPointerType() || castTy->isReferenceType())
367       return val;
368 
369     // Are we casting from an array to an integer?  If so, cast the decayed
370     // pointer value to an integer.
371     assert(castTy->isIntegralOrEnumerationType());
372 
373     // FIXME: Keep these here for now in case we decide soon that we
374     // need the original decayed type.
375     //    QualType elemTy = cast<ArrayType>(originalTy)->getElementType();
376     //    QualType pointerTy = C.getPointerType(elemTy);
377     return evalCastFromLoc(val.castAs<Loc>(), castTy);
378   }
379 
380   // Check for casts from a region to a specific type.
381   if (const MemRegion *R = val.getAsRegion()) {
382     // Handle other casts of locations to integers.
383     if (castTy->isIntegralOrEnumerationType())
384       return evalCastFromLoc(loc::MemRegionVal(R), castTy);
385 
386     // FIXME: We should handle the case where we strip off view layers to get
387     //  to a desugared type.
388     if (!Loc::isLocType(castTy)) {
389       // FIXME: There can be gross cases where one casts the result of a function
390       // (that returns a pointer) to some other value that happens to fit
391       // within that pointer value.  We currently have no good way to
392       // model such operations.  When this happens, the underlying operation
393       // is that the caller is reasoning about bits.  Conceptually we are
394       // layering a "view" of a location on top of those bits.  Perhaps
395       // we need to be more lazy about mutual possible views, even on an
396       // SVal?  This may be necessary for bit-level reasoning as well.
397       return UnknownVal();
398     }
399 
400     // We get a symbolic function pointer for a dereference of a function
401     // pointer, but it is of function type. Example:
402 
403     //  struct FPRec {
404     //    void (*my_func)(int * x);
405     //  };
406     //
407     //  int bar(int x);
408     //
409     //  int f1_a(struct FPRec* foo) {
410     //    int x;
411     //    (*foo->my_func)(&x);
412     //    return bar(x)+1; // no-warning
413     //  }
414 
415     assert(Loc::isLocType(originalTy) || originalTy->isFunctionType() ||
416            originalTy->isBlockPointerType() || castTy->isReferenceType());
417 
418     StoreManager &storeMgr = StateMgr.getStoreManager();
419 
420     // Delegate to store manager to get the result of casting a region to a
421     // different type.  If the MemRegion* returned is NULL, this expression
422     // Evaluates to UnknownVal.
423     R = storeMgr.castRegion(R, castTy);
424     return R ? SVal(loc::MemRegionVal(R)) : UnknownVal();
425   }
426 
427   return dispatchCast(val, castTy);
428 }
429