SValBuilder.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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->isIntegralOrEnumerationType())
  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 *Ex,
  90. const LocationContext *LCtx,
  91. unsigned Count) {
  92. QualType T = Ex->getType();
  93. // Compute the type of the result. If the expression is not an R-value, the
  94. // result should be a location.
  95. QualType ExType = Ex->getType();
  96. if (Ex->isGLValue())
  97. T = LCtx->getAnalysisDeclContext()->getASTContext().getPointerType(ExType);
  98. return conjureSymbolVal(SymbolTag, Ex, LCtx, T, Count);
  99. }
  100. DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const void *symbolTag,
  101. const Expr *expr,
  102. const LocationContext *LCtx,
  103. QualType type,
  104. unsigned count) {
  105. if (!SymbolManager::canSymbolicate(type))
  106. return UnknownVal();
  107. SymbolRef sym = SymMgr.conjureSymbol(expr, LCtx, type, count, symbolTag);
  108. if (Loc::isLocType(type))
  109. return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
  110. return nonloc::SymbolVal(sym);
  111. }
  112. DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const Stmt *stmt,
  113. const LocationContext *LCtx,
  114. QualType type,
  115. unsigned visitCount) {
  116. if (!SymbolManager::canSymbolicate(type))
  117. return UnknownVal();
  118. SymbolRef sym = SymMgr.conjureSymbol(stmt, LCtx, type, visitCount);
  119. if (Loc::isLocType(type))
  120. return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
  121. return nonloc::SymbolVal(sym);
  122. }
  123. DefinedOrUnknownSVal
  124. SValBuilder::getConjuredHeapSymbolVal(const Expr *E,
  125. const LocationContext *LCtx,
  126. unsigned VisitCount) {
  127. QualType T = E->getType();
  128. assert(Loc::isLocType(T));
  129. assert(SymbolManager::canSymbolicate(T));
  130. SymbolRef sym = SymMgr.conjureSymbol(E, LCtx, T, VisitCount);
  131. return loc::MemRegionVal(MemMgr.getSymbolicHeapRegion(sym));
  132. }
  133. DefinedSVal SValBuilder::getMetadataSymbolVal(const void *symbolTag,
  134. const MemRegion *region,
  135. const Expr *expr, QualType type,
  136. unsigned count) {
  137. assert(SymbolManager::canSymbolicate(type) && "Invalid metadata symbol type");
  138. SymbolRef sym =
  139. SymMgr.getMetadataSymbol(region, expr, type, count, symbolTag);
  140. if (Loc::isLocType(type))
  141. return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
  142. return nonloc::SymbolVal(sym);
  143. }
  144. DefinedOrUnknownSVal
  145. SValBuilder::getDerivedRegionValueSymbolVal(SymbolRef parentSymbol,
  146. const TypedValueRegion *region) {
  147. QualType T = region->getValueType();
  148. if (!SymbolManager::canSymbolicate(T))
  149. return UnknownVal();
  150. SymbolRef sym = SymMgr.getDerivedSymbol(parentSymbol, region);
  151. if (Loc::isLocType(T))
  152. return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
  153. return nonloc::SymbolVal(sym);
  154. }
  155. DefinedSVal SValBuilder::getFunctionPointer(const FunctionDecl *func) {
  156. return loc::MemRegionVal(MemMgr.getFunctionTextRegion(func));
  157. }
  158. DefinedSVal SValBuilder::getBlockPointer(const BlockDecl *block,
  159. CanQualType locTy,
  160. const LocationContext *locContext,
  161. unsigned blockCount) {
  162. const BlockTextRegion *BC =
  163. MemMgr.getBlockTextRegion(block, locTy, locContext->getAnalysisDeclContext());
  164. const BlockDataRegion *BD = MemMgr.getBlockDataRegion(BC, locContext,
  165. blockCount);
  166. return loc::MemRegionVal(BD);
  167. }
  168. /// Return a memory region for the 'this' object reference.
  169. loc::MemRegionVal SValBuilder::getCXXThis(const CXXMethodDecl *D,
  170. const StackFrameContext *SFC) {
  171. return loc::MemRegionVal(getRegionManager().
  172. getCXXThisRegion(D->getThisType(getContext()), SFC));
  173. }
  174. /// Return a memory region for the 'this' object reference.
  175. loc::MemRegionVal SValBuilder::getCXXThis(const CXXRecordDecl *D,
  176. const StackFrameContext *SFC) {
  177. const Type *T = D->getTypeForDecl();
  178. QualType PT = getContext().getPointerType(QualType(T, 0));
  179. return loc::MemRegionVal(getRegionManager().getCXXThisRegion(PT, SFC));
  180. }
  181. Optional<SVal> SValBuilder::getConstantVal(const Expr *E) {
  182. E = E->IgnoreParens();
  183. switch (E->getStmtClass()) {
  184. // Handle expressions that we treat differently from the AST's constant
  185. // evaluator.
  186. case Stmt::AddrLabelExprClass:
  187. return makeLoc(cast<AddrLabelExpr>(E));
  188. case Stmt::CXXScalarValueInitExprClass:
  189. case Stmt::ImplicitValueInitExprClass:
  190. return makeZeroVal(E->getType());
  191. case Stmt::ObjCStringLiteralClass: {
  192. const ObjCStringLiteral *SL = cast<ObjCStringLiteral>(E);
  193. return makeLoc(getRegionManager().getObjCStringRegion(SL));
  194. }
  195. case Stmt::StringLiteralClass: {
  196. const StringLiteral *SL = cast<StringLiteral>(E);
  197. return makeLoc(getRegionManager().getStringRegion(SL));
  198. }
  199. // Fast-path some expressions to avoid the overhead of going through the AST's
  200. // constant evaluator
  201. case Stmt::CharacterLiteralClass: {
  202. const CharacterLiteral *C = cast<CharacterLiteral>(E);
  203. return makeIntVal(C->getValue(), C->getType());
  204. }
  205. case Stmt::CXXBoolLiteralExprClass:
  206. return makeBoolVal(cast<CXXBoolLiteralExpr>(E));
  207. case Stmt::IntegerLiteralClass:
  208. return makeIntVal(cast<IntegerLiteral>(E));
  209. case Stmt::ObjCBoolLiteralExprClass:
  210. return makeBoolVal(cast<ObjCBoolLiteralExpr>(E));
  211. case Stmt::CXXNullPtrLiteralExprClass:
  212. return makeNull();
  213. case Stmt::ImplicitCastExprClass: {
  214. const CastExpr *CE = cast<CastExpr>(E);
  215. if (CE->getCastKind() == CK_ArrayToPointerDecay) {
  216. Optional<SVal> ArrayVal = getConstantVal(CE->getSubExpr());
  217. if (!ArrayVal)
  218. return None;
  219. return evalCast(*ArrayVal, CE->getType(), CE->getSubExpr()->getType());
  220. }
  221. // FALLTHROUGH
  222. }
  223. // If we don't have a special case, fall back to the AST's constant evaluator.
  224. default: {
  225. // Don't try to come up with a value for materialized temporaries.
  226. if (E->isGLValue())
  227. return None;
  228. ASTContext &Ctx = getContext();
  229. llvm::APSInt Result;
  230. if (E->EvaluateAsInt(Result, Ctx))
  231. return makeIntVal(Result);
  232. if (Loc::isLocType(E->getType()))
  233. if (E->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
  234. return makeNull();
  235. return None;
  236. }
  237. }
  238. }
  239. //===----------------------------------------------------------------------===//
  240. SVal SValBuilder::makeSymExprValNN(ProgramStateRef State,
  241. BinaryOperator::Opcode Op,
  242. NonLoc LHS, NonLoc RHS,
  243. QualType ResultTy) {
  244. if (!State->isTainted(RHS) && !State->isTainted(LHS))
  245. return UnknownVal();
  246. const SymExpr *symLHS = LHS.getAsSymExpr();
  247. const SymExpr *symRHS = RHS.getAsSymExpr();
  248. // TODO: When the Max Complexity is reached, we should conjure a symbol
  249. // instead of generating an Unknown value and propagate the taint info to it.
  250. const unsigned MaxComp = 10000; // 100000 28X
  251. if (symLHS && symRHS &&
  252. (symLHS->computeComplexity() + symRHS->computeComplexity()) < MaxComp)
  253. return makeNonLoc(symLHS, Op, symRHS, ResultTy);
  254. if (symLHS && symLHS->computeComplexity() < MaxComp)
  255. if (Optional<nonloc::ConcreteInt> rInt = RHS.getAs<nonloc::ConcreteInt>())
  256. return makeNonLoc(symLHS, Op, rInt->getValue(), ResultTy);
  257. if (symRHS && symRHS->computeComplexity() < MaxComp)
  258. if (Optional<nonloc::ConcreteInt> lInt = LHS.getAs<nonloc::ConcreteInt>())
  259. return makeNonLoc(lInt->getValue(), Op, symRHS, ResultTy);
  260. return UnknownVal();
  261. }
  262. SVal SValBuilder::evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
  263. SVal lhs, SVal rhs, QualType type) {
  264. if (lhs.isUndef() || rhs.isUndef())
  265. return UndefinedVal();
  266. if (lhs.isUnknown() || rhs.isUnknown())
  267. return UnknownVal();
  268. if (Optional<Loc> LV = lhs.getAs<Loc>()) {
  269. if (Optional<Loc> RV = rhs.getAs<Loc>())
  270. return evalBinOpLL(state, op, *LV, *RV, type);
  271. return evalBinOpLN(state, op, *LV, rhs.castAs<NonLoc>(), type);
  272. }
  273. if (Optional<Loc> RV = rhs.getAs<Loc>()) {
  274. // Support pointer arithmetic where the addend is on the left
  275. // and the pointer on the right.
  276. assert(op == BO_Add);
  277. // Commute the operands.
  278. return evalBinOpLN(state, op, *RV, lhs.castAs<NonLoc>(), type);
  279. }
  280. return evalBinOpNN(state, op, lhs.castAs<NonLoc>(), rhs.castAs<NonLoc>(),
  281. type);
  282. }
  283. DefinedOrUnknownSVal SValBuilder::evalEQ(ProgramStateRef state,
  284. DefinedOrUnknownSVal lhs,
  285. DefinedOrUnknownSVal rhs) {
  286. return evalBinOp(state, BO_EQ, lhs, rhs, getConditionType())
  287. .castAs<DefinedOrUnknownSVal>();
  288. }
  289. /// Recursively check if the pointer types are equal modulo const, volatile,
  290. /// and restrict qualifiers. Also, assume that all types are similar to 'void'.
  291. /// Assumes the input types are canonical.
  292. static bool shouldBeModeledWithNoOp(ASTContext &Context, QualType ToTy,
  293. QualType FromTy) {
  294. while (Context.UnwrapSimilarPointerTypes(ToTy, FromTy)) {
  295. Qualifiers Quals1, Quals2;
  296. ToTy = Context.getUnqualifiedArrayType(ToTy, Quals1);
  297. FromTy = Context.getUnqualifiedArrayType(FromTy, Quals2);
  298. // Make sure that non-cvr-qualifiers the other qualifiers (e.g., address
  299. // spaces) are identical.
  300. Quals1.removeCVRQualifiers();
  301. Quals2.removeCVRQualifiers();
  302. if (Quals1 != Quals2)
  303. return false;
  304. }
  305. // If we are casting to void, the 'From' value can be used to represent the
  306. // 'To' value.
  307. if (ToTy->isVoidType())
  308. return true;
  309. if (ToTy != FromTy)
  310. return false;
  311. return true;
  312. }
  313. // FIXME: should rewrite according to the cast kind.
  314. SVal SValBuilder::evalCast(SVal val, QualType castTy, QualType originalTy) {
  315. castTy = Context.getCanonicalType(castTy);
  316. originalTy = Context.getCanonicalType(originalTy);
  317. if (val.isUnknownOrUndef() || castTy == originalTy)
  318. return val;
  319. if (castTy->isBooleanType()) {
  320. if (val.isUnknownOrUndef())
  321. return val;
  322. if (val.isConstant())
  323. return makeTruthVal(!val.isZeroConstant(), castTy);
  324. if (!Loc::isLocType(originalTy) &&
  325. !originalTy->isIntegralOrEnumerationType() &&
  326. !originalTy->isMemberPointerType())
  327. return UnknownVal();
  328. if (SymbolRef Sym = val.getAsSymbol(true)) {
  329. BasicValueFactory &BVF = getBasicValueFactory();
  330. // FIXME: If we had a state here, we could see if the symbol is known to
  331. // be zero, but we don't.
  332. return makeNonLoc(Sym, BO_NE, BVF.getValue(0, Sym->getType()), castTy);
  333. }
  334. // Loc values are not always true, they could be weakly linked functions.
  335. if (Optional<Loc> L = val.getAs<Loc>())
  336. return evalCastFromLoc(*L, castTy);
  337. Loc L = val.castAs<nonloc::LocAsInteger>().getLoc();
  338. return evalCastFromLoc(L, castTy);
  339. }
  340. // For const casts, casts to void, just propagate the value.
  341. if (!castTy->isVariableArrayType() && !originalTy->isVariableArrayType())
  342. if (shouldBeModeledWithNoOp(Context, Context.getPointerType(castTy),
  343. Context.getPointerType(originalTy)))
  344. return val;
  345. // Check for casts from pointers to integers.
  346. if (castTy->isIntegralOrEnumerationType() && Loc::isLocType(originalTy))
  347. return evalCastFromLoc(val.castAs<Loc>(), castTy);
  348. // Check for casts from integers to pointers.
  349. if (Loc::isLocType(castTy) && originalTy->isIntegralOrEnumerationType()) {
  350. if (Optional<nonloc::LocAsInteger> LV = val.getAs<nonloc::LocAsInteger>()) {
  351. if (const MemRegion *R = LV->getLoc().getAsRegion()) {
  352. StoreManager &storeMgr = StateMgr.getStoreManager();
  353. R = storeMgr.castRegion(R, castTy);
  354. return R ? SVal(loc::MemRegionVal(R)) : UnknownVal();
  355. }
  356. return LV->getLoc();
  357. }
  358. return dispatchCast(val, castTy);
  359. }
  360. // Just pass through function and block pointers.
  361. if (originalTy->isBlockPointerType() || originalTy->isFunctionPointerType()) {
  362. assert(Loc::isLocType(castTy));
  363. return val;
  364. }
  365. // Check for casts from array type to another type.
  366. if (const ArrayType *arrayT =
  367. dyn_cast<ArrayType>(originalTy.getCanonicalType())) {
  368. // We will always decay to a pointer.
  369. QualType elemTy = arrayT->getElementType();
  370. val = StateMgr.ArrayToPointer(val.castAs<Loc>(), elemTy);
  371. // Are we casting from an array to a pointer? If so just pass on
  372. // the decayed value.
  373. if (castTy->isPointerType() || castTy->isReferenceType())
  374. return val;
  375. // Are we casting from an array to an integer? If so, cast the decayed
  376. // pointer value to an integer.
  377. assert(castTy->isIntegralOrEnumerationType());
  378. // FIXME: Keep these here for now in case we decide soon that we
  379. // need the original decayed type.
  380. // QualType elemTy = cast<ArrayType>(originalTy)->getElementType();
  381. // QualType pointerTy = C.getPointerType(elemTy);
  382. return evalCastFromLoc(val.castAs<Loc>(), castTy);
  383. }
  384. // Check for casts from a region to a specific type.
  385. if (const MemRegion *R = val.getAsRegion()) {
  386. // Handle other casts of locations to integers.
  387. if (castTy->isIntegralOrEnumerationType())
  388. return evalCastFromLoc(loc::MemRegionVal(R), castTy);
  389. // FIXME: We should handle the case where we strip off view layers to get
  390. // to a desugared type.
  391. if (!Loc::isLocType(castTy)) {
  392. // FIXME: There can be gross cases where one casts the result of a function
  393. // (that returns a pointer) to some other value that happens to fit
  394. // within that pointer value. We currently have no good way to
  395. // model such operations. When this happens, the underlying operation
  396. // is that the caller is reasoning about bits. Conceptually we are
  397. // layering a "view" of a location on top of those bits. Perhaps
  398. // we need to be more lazy about mutual possible views, even on an
  399. // SVal? This may be necessary for bit-level reasoning as well.
  400. return UnknownVal();
  401. }
  402. // We get a symbolic function pointer for a dereference of a function
  403. // pointer, but it is of function type. Example:
  404. // struct FPRec {
  405. // void (*my_func)(int * x);
  406. // };
  407. //
  408. // int bar(int x);
  409. //
  410. // int f1_a(struct FPRec* foo) {
  411. // int x;
  412. // (*foo->my_func)(&x);
  413. // return bar(x)+1; // no-warning
  414. // }
  415. assert(Loc::isLocType(originalTy) || originalTy->isFunctionType() ||
  416. originalTy->isBlockPointerType() || castTy->isReferenceType());
  417. StoreManager &storeMgr = StateMgr.getStoreManager();
  418. // Delegate to store manager to get the result of casting a region to a
  419. // different type. If the MemRegion* returned is NULL, this expression
  420. // Evaluates to UnknownVal.
  421. R = storeMgr.castRegion(R, castTy);
  422. return R ? SVal(loc::MemRegionVal(R)) : UnknownVal();
  423. }
  424. return dispatchCast(val, castTy);
  425. }