SValBuilder.cpp 15 KB

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