1 //===- SValBuilder.cpp - Basic class for all SValBuilder implementations --===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines SValBuilder, the base class for all (complete) SValBuilder 10 // implementations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Decl.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/Stmt.h" 21 #include "clang/AST/Type.h" 22 #include "clang/Basic/LLVM.h" 23 #include "clang/Analysis/AnalysisDeclContext.h" 24 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 25 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h" 26 #include "clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h" 27 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 28 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" 29 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 30 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" 31 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" 32 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h" 33 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h" 34 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h" 35 #include "llvm/ADT/APSInt.h" 36 #include "llvm/ADT/None.h" 37 #include "llvm/ADT/Optional.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/Compiler.h" 40 #include <cassert> 41 #include <tuple> 42 43 using namespace clang; 44 using namespace ento; 45 46 //===----------------------------------------------------------------------===// 47 // Basic SVal creation. 48 //===----------------------------------------------------------------------===// 49 50 void SValBuilder::anchor() {} 51 52 DefinedOrUnknownSVal SValBuilder::makeZeroVal(QualType type) { 53 if (Loc::isLocType(type)) 54 return makeNull(); 55 56 if (type->isIntegralOrEnumerationType()) 57 return makeIntVal(0, type); 58 59 if (type->isArrayType() || type->isRecordType() || type->isVectorType() || 60 type->isAnyComplexType()) 61 return makeCompoundVal(type, BasicVals.getEmptySValList()); 62 63 // FIXME: Handle floats. 64 return UnknownVal(); 65 } 66 67 NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, 68 const llvm::APSInt& rhs, QualType type) { 69 // The Environment ensures we always get a persistent APSInt in 70 // BasicValueFactory, so we don't need to get the APSInt from 71 // BasicValueFactory again. 72 assert(lhs); 73 assert(!Loc::isLocType(type)); 74 return nonloc::SymbolVal(SymMgr.getSymIntExpr(lhs, op, rhs, type)); 75 } 76 77 NonLoc SValBuilder::makeNonLoc(const llvm::APSInt& lhs, 78 BinaryOperator::Opcode op, const SymExpr *rhs, 79 QualType type) { 80 assert(rhs); 81 assert(!Loc::isLocType(type)); 82 return nonloc::SymbolVal(SymMgr.getIntSymExpr(lhs, op, rhs, type)); 83 } 84 85 NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op, 86 const SymExpr *rhs, QualType type) { 87 assert(lhs && rhs); 88 assert(!Loc::isLocType(type)); 89 return nonloc::SymbolVal(SymMgr.getSymSymExpr(lhs, op, rhs, type)); 90 } 91 92 NonLoc SValBuilder::makeNonLoc(const SymExpr *operand, 93 QualType fromTy, QualType toTy) { 94 assert(operand); 95 assert(!Loc::isLocType(toTy)); 96 return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy)); 97 } 98 99 SVal SValBuilder::convertToArrayIndex(SVal val) { 100 if (val.isUnknownOrUndef()) 101 return val; 102 103 // Common case: we have an appropriately sized integer. 104 if (Optional<nonloc::ConcreteInt> CI = val.getAs<nonloc::ConcreteInt>()) { 105 const llvm::APSInt& I = CI->getValue(); 106 if (I.getBitWidth() == ArrayIndexWidth && I.isSigned()) 107 return val; 108 } 109 110 return evalCast(val, ArrayIndexTy, QualType{}); 111 } 112 113 nonloc::ConcreteInt SValBuilder::makeBoolVal(const CXXBoolLiteralExpr *boolean){ 114 return makeTruthVal(boolean->getValue()); 115 } 116 117 DefinedOrUnknownSVal 118 SValBuilder::getRegionValueSymbolVal(const TypedValueRegion *region) { 119 QualType T = region->getValueType(); 120 121 if (T->isNullPtrType()) 122 return makeZeroVal(T); 123 124 if (!SymbolManager::canSymbolicate(T)) 125 return UnknownVal(); 126 127 SymbolRef sym = SymMgr.getRegionValueSymbol(region); 128 129 if (Loc::isLocType(T)) 130 return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym)); 131 132 return nonloc::SymbolVal(sym); 133 } 134 135 DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const void *SymbolTag, 136 const Expr *Ex, 137 const LocationContext *LCtx, 138 unsigned Count) { 139 QualType T = Ex->getType(); 140 141 if (T->isNullPtrType()) 142 return makeZeroVal(T); 143 144 // Compute the type of the result. If the expression is not an R-value, the 145 // result should be a location. 146 QualType ExType = Ex->getType(); 147 if (Ex->isGLValue()) 148 T = LCtx->getAnalysisDeclContext()->getASTContext().getPointerType(ExType); 149 150 return conjureSymbolVal(SymbolTag, Ex, LCtx, T, Count); 151 } 152 153 DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const void *symbolTag, 154 const Expr *expr, 155 const LocationContext *LCtx, 156 QualType type, 157 unsigned count) { 158 if (type->isNullPtrType()) 159 return makeZeroVal(type); 160 161 if (!SymbolManager::canSymbolicate(type)) 162 return UnknownVal(); 163 164 SymbolRef sym = SymMgr.conjureSymbol(expr, LCtx, type, count, symbolTag); 165 166 if (Loc::isLocType(type)) 167 return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym)); 168 169 return nonloc::SymbolVal(sym); 170 } 171 172 DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const Stmt *stmt, 173 const LocationContext *LCtx, 174 QualType type, 175 unsigned visitCount) { 176 if (type->isNullPtrType()) 177 return makeZeroVal(type); 178 179 if (!SymbolManager::canSymbolicate(type)) 180 return UnknownVal(); 181 182 SymbolRef sym = SymMgr.conjureSymbol(stmt, LCtx, type, visitCount); 183 184 if (Loc::isLocType(type)) 185 return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym)); 186 187 return nonloc::SymbolVal(sym); 188 } 189 190 DefinedOrUnknownSVal 191 SValBuilder::getConjuredHeapSymbolVal(const Expr *E, 192 const LocationContext *LCtx, 193 unsigned VisitCount) { 194 QualType T = E->getType(); 195 assert(Loc::isLocType(T)); 196 assert(SymbolManager::canSymbolicate(T)); 197 if (T->isNullPtrType()) 198 return makeZeroVal(T); 199 200 SymbolRef sym = SymMgr.conjureSymbol(E, LCtx, T, VisitCount); 201 return loc::MemRegionVal(MemMgr.getSymbolicHeapRegion(sym)); 202 } 203 204 DefinedSVal SValBuilder::getMetadataSymbolVal(const void *symbolTag, 205 const MemRegion *region, 206 const Expr *expr, QualType type, 207 const LocationContext *LCtx, 208 unsigned count) { 209 assert(SymbolManager::canSymbolicate(type) && "Invalid metadata symbol type"); 210 211 SymbolRef sym = 212 SymMgr.getMetadataSymbol(region, expr, type, LCtx, count, symbolTag); 213 214 if (Loc::isLocType(type)) 215 return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym)); 216 217 return nonloc::SymbolVal(sym); 218 } 219 220 DefinedOrUnknownSVal 221 SValBuilder::getDerivedRegionValueSymbolVal(SymbolRef parentSymbol, 222 const TypedValueRegion *region) { 223 QualType T = region->getValueType(); 224 225 if (T->isNullPtrType()) 226 return makeZeroVal(T); 227 228 if (!SymbolManager::canSymbolicate(T)) 229 return UnknownVal(); 230 231 SymbolRef sym = SymMgr.getDerivedSymbol(parentSymbol, region); 232 233 if (Loc::isLocType(T)) 234 return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym)); 235 236 return nonloc::SymbolVal(sym); 237 } 238 239 DefinedSVal SValBuilder::getMemberPointer(const NamedDecl *ND) { 240 assert(!ND || isa<CXXMethodDecl>(ND) || isa<FieldDecl>(ND) || 241 isa<IndirectFieldDecl>(ND)); 242 243 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(ND)) { 244 // Sema treats pointers to static member functions as have function pointer 245 // type, so return a function pointer for the method. 246 // We don't need to play a similar trick for static member fields 247 // because these are represented as plain VarDecls and not FieldDecls 248 // in the AST. 249 if (MD->isStatic()) 250 return getFunctionPointer(MD); 251 } 252 253 return nonloc::PointerToMember(ND); 254 } 255 256 DefinedSVal SValBuilder::getFunctionPointer(const FunctionDecl *func) { 257 return loc::MemRegionVal(MemMgr.getFunctionCodeRegion(func)); 258 } 259 260 DefinedSVal SValBuilder::getBlockPointer(const BlockDecl *block, 261 CanQualType locTy, 262 const LocationContext *locContext, 263 unsigned blockCount) { 264 const BlockCodeRegion *BC = 265 MemMgr.getBlockCodeRegion(block, locTy, locContext->getAnalysisDeclContext()); 266 const BlockDataRegion *BD = MemMgr.getBlockDataRegion(BC, locContext, 267 blockCount); 268 return loc::MemRegionVal(BD); 269 } 270 271 Optional<loc::MemRegionVal> 272 SValBuilder::getCastedMemRegionVal(const MemRegion *R, QualType Ty) { 273 if (auto OptR = StateMgr.getStoreManager().castRegion(R, Ty)) 274 return loc::MemRegionVal(*OptR); 275 return None; 276 } 277 278 /// Return a memory region for the 'this' object reference. 279 loc::MemRegionVal SValBuilder::getCXXThis(const CXXMethodDecl *D, 280 const StackFrameContext *SFC) { 281 return loc::MemRegionVal( 282 getRegionManager().getCXXThisRegion(D->getThisType(), SFC)); 283 } 284 285 /// Return a memory region for the 'this' object reference. 286 loc::MemRegionVal SValBuilder::getCXXThis(const CXXRecordDecl *D, 287 const StackFrameContext *SFC) { 288 const Type *T = D->getTypeForDecl(); 289 QualType PT = getContext().getPointerType(QualType(T, 0)); 290 return loc::MemRegionVal(getRegionManager().getCXXThisRegion(PT, SFC)); 291 } 292 293 Optional<SVal> SValBuilder::getConstantVal(const Expr *E) { 294 E = E->IgnoreParens(); 295 296 switch (E->getStmtClass()) { 297 // Handle expressions that we treat differently from the AST's constant 298 // evaluator. 299 case Stmt::AddrLabelExprClass: 300 return makeLoc(cast<AddrLabelExpr>(E)); 301 302 case Stmt::CXXScalarValueInitExprClass: 303 case Stmt::ImplicitValueInitExprClass: 304 return makeZeroVal(E->getType()); 305 306 case Stmt::ObjCStringLiteralClass: { 307 const auto *SL = cast<ObjCStringLiteral>(E); 308 return makeLoc(getRegionManager().getObjCStringRegion(SL)); 309 } 310 311 case Stmt::StringLiteralClass: { 312 const auto *SL = cast<StringLiteral>(E); 313 return makeLoc(getRegionManager().getStringRegion(SL)); 314 } 315 316 case Stmt::PredefinedExprClass: { 317 const auto *PE = cast<PredefinedExpr>(E); 318 assert(PE->getFunctionName() && 319 "Since we analyze only instantiated functions, PredefinedExpr " 320 "should have a function name."); 321 return makeLoc(getRegionManager().getStringRegion(PE->getFunctionName())); 322 } 323 324 // Fast-path some expressions to avoid the overhead of going through the AST's 325 // constant evaluator 326 case Stmt::CharacterLiteralClass: { 327 const auto *C = cast<CharacterLiteral>(E); 328 return makeIntVal(C->getValue(), C->getType()); 329 } 330 331 case Stmt::CXXBoolLiteralExprClass: 332 return makeBoolVal(cast<CXXBoolLiteralExpr>(E)); 333 334 case Stmt::TypeTraitExprClass: { 335 const auto *TE = cast<TypeTraitExpr>(E); 336 return makeTruthVal(TE->getValue(), TE->getType()); 337 } 338 339 case Stmt::IntegerLiteralClass: 340 return makeIntVal(cast<IntegerLiteral>(E)); 341 342 case Stmt::ObjCBoolLiteralExprClass: 343 return makeBoolVal(cast<ObjCBoolLiteralExpr>(E)); 344 345 case Stmt::CXXNullPtrLiteralExprClass: 346 return makeNull(); 347 348 case Stmt::CStyleCastExprClass: 349 case Stmt::CXXFunctionalCastExprClass: 350 case Stmt::CXXConstCastExprClass: 351 case Stmt::CXXReinterpretCastExprClass: 352 case Stmt::CXXStaticCastExprClass: 353 case Stmt::ImplicitCastExprClass: { 354 const auto *CE = cast<CastExpr>(E); 355 switch (CE->getCastKind()) { 356 default: 357 break; 358 case CK_ArrayToPointerDecay: 359 case CK_IntegralToPointer: 360 case CK_NoOp: 361 case CK_BitCast: { 362 const Expr *SE = CE->getSubExpr(); 363 Optional<SVal> Val = getConstantVal(SE); 364 if (!Val) 365 return None; 366 return evalCast(*Val, CE->getType(), SE->getType()); 367 } 368 } 369 // FALLTHROUGH 370 LLVM_FALLTHROUGH; 371 } 372 373 // If we don't have a special case, fall back to the AST's constant evaluator. 374 default: { 375 // Don't try to come up with a value for materialized temporaries. 376 if (E->isGLValue()) 377 return None; 378 379 ASTContext &Ctx = getContext(); 380 Expr::EvalResult Result; 381 if (E->EvaluateAsInt(Result, Ctx)) 382 return makeIntVal(Result.Val.getInt()); 383 384 if (Loc::isLocType(E->getType())) 385 if (E->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull)) 386 return makeNull(); 387 388 return None; 389 } 390 } 391 } 392 393 SVal SValBuilder::makeSymExprValNN(BinaryOperator::Opcode Op, 394 NonLoc LHS, NonLoc RHS, 395 QualType ResultTy) { 396 SymbolRef symLHS = LHS.getAsSymbol(); 397 SymbolRef symRHS = RHS.getAsSymbol(); 398 399 // TODO: When the Max Complexity is reached, we should conjure a symbol 400 // instead of generating an Unknown value and propagate the taint info to it. 401 const unsigned MaxComp = StateMgr.getOwningEngine() 402 .getAnalysisManager() 403 .options.MaxSymbolComplexity; 404 405 if (symLHS && symRHS && 406 (symLHS->computeComplexity() + symRHS->computeComplexity()) < MaxComp) 407 return makeNonLoc(symLHS, Op, symRHS, ResultTy); 408 409 if (symLHS && symLHS->computeComplexity() < MaxComp) 410 if (Optional<nonloc::ConcreteInt> rInt = RHS.getAs<nonloc::ConcreteInt>()) 411 return makeNonLoc(symLHS, Op, rInt->getValue(), ResultTy); 412 413 if (symRHS && symRHS->computeComplexity() < MaxComp) 414 if (Optional<nonloc::ConcreteInt> lInt = LHS.getAs<nonloc::ConcreteInt>()) 415 return makeNonLoc(lInt->getValue(), Op, symRHS, ResultTy); 416 417 return UnknownVal(); 418 } 419 420 SVal SValBuilder::evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, 421 SVal lhs, SVal rhs, QualType type) { 422 if (lhs.isUndef() || rhs.isUndef()) 423 return UndefinedVal(); 424 425 if (lhs.isUnknown() || rhs.isUnknown()) 426 return UnknownVal(); 427 428 if (lhs.getAs<nonloc::LazyCompoundVal>() || 429 rhs.getAs<nonloc::LazyCompoundVal>()) { 430 return UnknownVal(); 431 } 432 433 if (op == BinaryOperatorKind::BO_Cmp) { 434 // We can't reason about C++20 spaceship operator yet. 435 // 436 // FIXME: Support C++20 spaceship operator. 437 // The main problem here is that the result is not integer. 438 return UnknownVal(); 439 } 440 441 if (Optional<Loc> LV = lhs.getAs<Loc>()) { 442 if (Optional<Loc> RV = rhs.getAs<Loc>()) 443 return evalBinOpLL(state, op, *LV, *RV, type); 444 445 return evalBinOpLN(state, op, *LV, rhs.castAs<NonLoc>(), type); 446 } 447 448 if (Optional<Loc> RV = rhs.getAs<Loc>()) { 449 // Support pointer arithmetic where the addend is on the left 450 // and the pointer on the right. 451 assert(op == BO_Add); 452 453 // Commute the operands. 454 return evalBinOpLN(state, op, *RV, lhs.castAs<NonLoc>(), type); 455 } 456 457 return evalBinOpNN(state, op, lhs.castAs<NonLoc>(), rhs.castAs<NonLoc>(), 458 type); 459 } 460 461 ConditionTruthVal SValBuilder::areEqual(ProgramStateRef state, SVal lhs, 462 SVal rhs) { 463 return state->isNonNull(evalEQ(state, lhs, rhs)); 464 } 465 466 SVal SValBuilder::evalEQ(ProgramStateRef state, SVal lhs, SVal rhs) { 467 return evalBinOp(state, BO_EQ, lhs, rhs, getConditionType()); 468 } 469 470 DefinedOrUnknownSVal SValBuilder::evalEQ(ProgramStateRef state, 471 DefinedOrUnknownSVal lhs, 472 DefinedOrUnknownSVal rhs) { 473 return evalEQ(state, static_cast<SVal>(lhs), static_cast<SVal>(rhs)) 474 .castAs<DefinedOrUnknownSVal>(); 475 } 476 477 /// Recursively check if the pointer types are equal modulo const, volatile, 478 /// and restrict qualifiers. Also, assume that all types are similar to 'void'. 479 /// Assumes the input types are canonical. 480 static bool shouldBeModeledWithNoOp(ASTContext &Context, QualType ToTy, 481 QualType FromTy) { 482 while (Context.UnwrapSimilarTypes(ToTy, FromTy)) { 483 Qualifiers Quals1, Quals2; 484 ToTy = Context.getUnqualifiedArrayType(ToTy, Quals1); 485 FromTy = Context.getUnqualifiedArrayType(FromTy, Quals2); 486 487 // Make sure that non-cvr-qualifiers the other qualifiers (e.g., address 488 // spaces) are identical. 489 Quals1.removeCVRQualifiers(); 490 Quals2.removeCVRQualifiers(); 491 if (Quals1 != Quals2) 492 return false; 493 } 494 495 // If we are casting to void, the 'From' value can be used to represent the 496 // 'To' value. 497 // 498 // FIXME: Doing this after unwrapping the types doesn't make any sense. A 499 // cast from 'int**' to 'void**' is not special in the way that a cast from 500 // 'int*' to 'void*' is. 501 if (ToTy->isVoidType()) 502 return true; 503 504 if (ToTy != FromTy) 505 return false; 506 507 return true; 508 } 509 510 // Handles casts of type CK_IntegralCast. 511 // At the moment, this function will redirect to evalCast, except when the range 512 // of the original value is known to be greater than the max of the target type. 513 SVal SValBuilder::evalIntegralCast(ProgramStateRef state, SVal val, 514 QualType castTy, QualType originalTy) { 515 // No truncations if target type is big enough. 516 if (getContext().getTypeSize(castTy) >= getContext().getTypeSize(originalTy)) 517 return evalCast(val, castTy, originalTy); 518 519 SymbolRef se = val.getAsSymbol(); 520 if (!se) // Let evalCast handle non symbolic expressions. 521 return evalCast(val, castTy, originalTy); 522 523 // Find the maximum value of the target type. 524 APSIntType ToType(getContext().getTypeSize(castTy), 525 castTy->isUnsignedIntegerType()); 526 llvm::APSInt ToTypeMax = ToType.getMaxValue(); 527 NonLoc ToTypeMaxVal = 528 makeIntVal(ToTypeMax.isUnsigned() ? ToTypeMax.getZExtValue() 529 : ToTypeMax.getSExtValue(), 530 castTy) 531 .castAs<NonLoc>(); 532 // Check the range of the symbol being casted against the maximum value of the 533 // target type. 534 NonLoc FromVal = val.castAs<NonLoc>(); 535 QualType CmpTy = getConditionType(); 536 NonLoc CompVal = 537 evalBinOpNN(state, BO_LE, FromVal, ToTypeMaxVal, CmpTy).castAs<NonLoc>(); 538 ProgramStateRef IsNotTruncated, IsTruncated; 539 std::tie(IsNotTruncated, IsTruncated) = state->assume(CompVal); 540 if (!IsNotTruncated && IsTruncated) { 541 // Symbol is truncated so we evaluate it as a cast. 542 NonLoc CastVal = makeNonLoc(se, originalTy, castTy); 543 return CastVal; 544 } 545 return evalCast(val, castTy, originalTy); 546 } 547 548 //===----------------------------------------------------------------------===// 549 // Cast methods. 550 // `evalCast` is the main method 551 // `evalCastKind` and `evalCastSubKind` are helpers 552 //===----------------------------------------------------------------------===// 553 554 /// Cast a given SVal to another SVal using given QualType's. 555 /// \param V -- SVal that should be casted. 556 /// \param CastTy -- QualType that V should be casted according to. 557 /// \param OriginalTy -- QualType which is associated to V. It provides 558 /// additional information about what type the cast performs from. 559 /// \returns the most appropriate casted SVal. 560 /// Note: Many cases don't use an exact OriginalTy. It can be extracted 561 /// from SVal or the cast can performs unconditionaly. Always pass OriginalTy! 562 /// It can be crucial in certain cases and generates different results. 563 /// FIXME: If `OriginalTy.isNull()` is true, then cast performs based on CastTy 564 /// only. This behavior is uncertain and should be improved. 565 SVal SValBuilder::evalCast(SVal V, QualType CastTy, QualType OriginalTy) { 566 if (CastTy.isNull()) 567 return V; 568 569 CastTy = Context.getCanonicalType(CastTy); 570 571 const bool IsUnknownOriginalType = OriginalTy.isNull(); 572 if (!IsUnknownOriginalType) { 573 OriginalTy = Context.getCanonicalType(OriginalTy); 574 575 if (CastTy == OriginalTy) 576 return V; 577 578 // FIXME: Move this check to the most appropriate 579 // evalCastKind/evalCastSubKind function. For const casts, casts to void, 580 // just propagate the value. 581 if (!CastTy->isVariableArrayType() && !OriginalTy->isVariableArrayType()) 582 if (shouldBeModeledWithNoOp(Context, Context.getPointerType(CastTy), 583 Context.getPointerType(OriginalTy))) 584 return V; 585 } 586 587 // Cast SVal according to kinds. 588 switch (V.getBaseKind()) { 589 case SVal::UndefinedValKind: 590 return evalCastKind(V.castAs<UndefinedVal>(), CastTy, OriginalTy); 591 case SVal::UnknownValKind: 592 return evalCastKind(V.castAs<UnknownVal>(), CastTy, OriginalTy); 593 case SVal::LocKind: 594 return evalCastKind(V.castAs<Loc>(), CastTy, OriginalTy); 595 case SVal::NonLocKind: 596 return evalCastKind(V.castAs<NonLoc>(), CastTy, OriginalTy); 597 } 598 599 llvm_unreachable("Unknown SVal kind"); 600 } 601 602 SVal SValBuilder::evalCastKind(UndefinedVal V, QualType CastTy, 603 QualType OriginalTy) { 604 return V; 605 } 606 607 SVal SValBuilder::evalCastKind(UnknownVal V, QualType CastTy, 608 QualType OriginalTy) { 609 return V; 610 } 611 612 SVal SValBuilder::evalCastKind(Loc V, QualType CastTy, QualType OriginalTy) { 613 switch (V.getSubKind()) { 614 case loc::ConcreteIntKind: 615 return evalCastSubKind(V.castAs<loc::ConcreteInt>(), CastTy, OriginalTy); 616 case loc::GotoLabelKind: 617 return evalCastSubKind(V.castAs<loc::GotoLabel>(), CastTy, OriginalTy); 618 case loc::MemRegionValKind: 619 return evalCastSubKind(V.castAs<loc::MemRegionVal>(), CastTy, OriginalTy); 620 } 621 622 llvm_unreachable("Unknown SVal kind"); 623 } 624 625 SVal SValBuilder::evalCastKind(NonLoc V, QualType CastTy, QualType OriginalTy) { 626 switch (V.getSubKind()) { 627 case nonloc::CompoundValKind: 628 return evalCastSubKind(V.castAs<nonloc::CompoundVal>(), CastTy, OriginalTy); 629 case nonloc::ConcreteIntKind: 630 return evalCastSubKind(V.castAs<nonloc::ConcreteInt>(), CastTy, OriginalTy); 631 case nonloc::LazyCompoundValKind: 632 return evalCastSubKind(V.castAs<nonloc::LazyCompoundVal>(), CastTy, 633 OriginalTy); 634 case nonloc::LocAsIntegerKind: 635 return evalCastSubKind(V.castAs<nonloc::LocAsInteger>(), CastTy, 636 OriginalTy); 637 case nonloc::SymbolValKind: 638 return evalCastSubKind(V.castAs<nonloc::SymbolVal>(), CastTy, OriginalTy); 639 case nonloc::PointerToMemberKind: 640 return evalCastSubKind(V.castAs<nonloc::PointerToMember>(), CastTy, 641 OriginalTy); 642 } 643 644 llvm_unreachable("Unknown SVal kind"); 645 } 646 647 SVal SValBuilder::evalCastSubKind(loc::ConcreteInt V, QualType CastTy, 648 QualType OriginalTy) { 649 // Pointer to bool. 650 if (CastTy->isBooleanType()) 651 return makeTruthVal(V.getValue().getBoolValue(), CastTy); 652 653 // Pointer to integer. 654 if (CastTy->isIntegralOrEnumerationType()) { 655 llvm::APSInt Value = V.getValue(); 656 BasicVals.getAPSIntType(CastTy).apply(Value); 657 return makeIntVal(Value); 658 } 659 660 // Pointer to any pointer. 661 if (Loc::isLocType(CastTy)) 662 return V; 663 664 // Pointer to whatever else. 665 return UnknownVal(); 666 } 667 668 SVal SValBuilder::evalCastSubKind(loc::GotoLabel V, QualType CastTy, 669 QualType OriginalTy) { 670 // Pointer to bool. 671 if (CastTy->isBooleanType()) 672 // Labels are always true. 673 return makeTruthVal(true, CastTy); 674 675 // Pointer to integer. 676 if (CastTy->isIntegralOrEnumerationType()) { 677 const unsigned BitWidth = Context.getIntWidth(CastTy); 678 return makeLocAsInteger(V, BitWidth); 679 } 680 681 const bool IsUnknownOriginalType = OriginalTy.isNull(); 682 if (!IsUnknownOriginalType) { 683 // Array to pointer. 684 if (isa<ArrayType>(OriginalTy)) 685 if (CastTy->isPointerType() || CastTy->isReferenceType()) 686 return UnknownVal(); 687 } 688 689 // Pointer to any pointer. 690 if (Loc::isLocType(CastTy)) 691 return V; 692 693 // Pointer to whatever else. 694 return UnknownVal(); 695 } 696 697 static bool hasSameUnqualifiedPointeeType(QualType ty1, QualType ty2) { 698 return ty1->getPointeeType().getCanonicalType().getTypePtr() == 699 ty2->getPointeeType().getCanonicalType().getTypePtr(); 700 } 701 702 SVal SValBuilder::evalCastSubKind(loc::MemRegionVal V, QualType CastTy, 703 QualType OriginalTy) { 704 // Pointer to bool. 705 if (CastTy->isBooleanType()) { 706 const MemRegion *R = V.getRegion(); 707 if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R)) 708 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl())) 709 if (FD->isWeak()) 710 // FIXME: Currently we are using an extent symbol here, 711 // because there are no generic region address metadata 712 // symbols to use, only content metadata. 713 return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR)); 714 715 if (const SymbolicRegion *SymR = R->getSymbolicBase()) 716 return makeNonLoc(SymR->getSymbol(), BO_NE, 717 BasicVals.getZeroWithPtrWidth(), CastTy); 718 // Non-symbolic memory regions are always true. 719 return makeTruthVal(true, CastTy); 720 } 721 722 const bool IsUnknownOriginalType = OriginalTy.isNull(); 723 // Try to cast to array 724 const auto *ArrayTy = 725 IsUnknownOriginalType 726 ? nullptr 727 : dyn_cast<ArrayType>(OriginalTy.getCanonicalType()); 728 729 // Pointer to integer. 730 if (CastTy->isIntegralOrEnumerationType()) { 731 SVal Val = V; 732 // Array to integer. 733 if (ArrayTy) { 734 // We will always decay to a pointer. 735 QualType ElemTy = ArrayTy->getElementType(); 736 Val = StateMgr.ArrayToPointer(V, ElemTy); 737 // FIXME: Keep these here for now in case we decide soon that we 738 // need the original decayed type. 739 // QualType elemTy = cast<ArrayType>(originalTy)->getElementType(); 740 // QualType pointerTy = C.getPointerType(elemTy); 741 } 742 const unsigned BitWidth = Context.getIntWidth(CastTy); 743 return makeLocAsInteger(Val.castAs<Loc>(), BitWidth); 744 } 745 746 // Pointer to pointer. 747 if (Loc::isLocType(CastTy)) { 748 749 if (IsUnknownOriginalType) { 750 // When retrieving symbolic pointer and expecting a non-void pointer, 751 // wrap them into element regions of the expected type if necessary. 752 // It is necessary to make sure that the retrieved value makes sense, 753 // because there's no other cast in the AST that would tell us to cast 754 // it to the correct pointer type. We might need to do that for non-void 755 // pointers as well. 756 // FIXME: We really need a single good function to perform casts for us 757 // correctly every time we need it. 758 const MemRegion *R = V.getRegion(); 759 if (CastTy->isPointerType() && !CastTy->isVoidPointerType()) { 760 if (const auto *SR = dyn_cast<SymbolicRegion>(R)) { 761 QualType SRTy = SR->getSymbol()->getType(); 762 if (!hasSameUnqualifiedPointeeType(SRTy, CastTy)) { 763 if (auto OptMemRegV = getCastedMemRegionVal(SR, CastTy)) 764 return *OptMemRegV; 765 } 766 } 767 } 768 // Next fixes pointer dereference using type different from its initial 769 // one. See PR37503 and PR49007 for details. 770 if (const auto *ER = dyn_cast<ElementRegion>(R)) { 771 if (auto OptMemRegV = getCastedMemRegionVal(ER, CastTy)) 772 return *OptMemRegV; 773 } 774 775 return V; 776 } 777 778 if (OriginalTy->isIntegralOrEnumerationType() || 779 OriginalTy->isBlockPointerType() || OriginalTy->isFunctionPointerType()) 780 return V; 781 782 // Array to pointer. 783 if (ArrayTy) { 784 // Are we casting from an array to a pointer? If so just pass on 785 // the decayed value. 786 if (CastTy->isPointerType() || CastTy->isReferenceType()) { 787 // We will always decay to a pointer. 788 QualType ElemTy = ArrayTy->getElementType(); 789 return StateMgr.ArrayToPointer(V, ElemTy); 790 } 791 // Are we casting from an array to an integer? If so, cast the decayed 792 // pointer value to an integer. 793 assert(CastTy->isIntegralOrEnumerationType()); 794 } 795 796 // Other pointer to pointer. 797 assert(Loc::isLocType(OriginalTy) || OriginalTy->isFunctionType() || 798 CastTy->isReferenceType()); 799 800 // We get a symbolic function pointer for a dereference of a function 801 // pointer, but it is of function type. Example: 802 803 // struct FPRec { 804 // void (*my_func)(int * x); 805 // }; 806 // 807 // int bar(int x); 808 // 809 // int f1_a(struct FPRec* foo) { 810 // int x; 811 // (*foo->my_func)(&x); 812 // return bar(x)+1; // no-warning 813 // } 814 815 // Get the result of casting a region to a different type. 816 const MemRegion *R = V.getRegion(); 817 if (auto OptMemRegV = getCastedMemRegionVal(R, CastTy)) 818 return *OptMemRegV; 819 } 820 821 // Pointer to whatever else. 822 // FIXME: There can be gross cases where one casts the result of a 823 // function (that returns a pointer) to some other value that happens to 824 // fit within that pointer value. We currently have no good way to model 825 // such operations. When this happens, the underlying operation is that 826 // the caller is reasoning about bits. Conceptually we are layering a 827 // "view" of a location on top of those bits. Perhaps we need to be more 828 // lazy about mutual possible views, even on an SVal? This may be 829 // necessary for bit-level reasoning as well. 830 return UnknownVal(); 831 } 832 833 SVal SValBuilder::evalCastSubKind(nonloc::CompoundVal V, QualType CastTy, 834 QualType OriginalTy) { 835 // Compound to whatever. 836 return UnknownVal(); 837 } 838 839 SVal SValBuilder::evalCastSubKind(nonloc::ConcreteInt V, QualType CastTy, 840 QualType OriginalTy) { 841 auto CastedValue = [V, CastTy, this]() { 842 llvm::APSInt Value = V.getValue(); 843 BasicVals.getAPSIntType(CastTy).apply(Value); 844 return Value; 845 }; 846 847 // Integer to bool. 848 if (CastTy->isBooleanType()) 849 return makeTruthVal(V.getValue().getBoolValue(), CastTy); 850 851 // Integer to pointer. 852 if (CastTy->isIntegralOrEnumerationType()) 853 return makeIntVal(CastedValue()); 854 855 // Integer to pointer. 856 if (Loc::isLocType(CastTy)) 857 return makeIntLocVal(CastedValue()); 858 859 // Pointer to whatever else. 860 return UnknownVal(); 861 } 862 863 SVal SValBuilder::evalCastSubKind(nonloc::LazyCompoundVal V, QualType CastTy, 864 QualType OriginalTy) { 865 // Compound to whatever. 866 return UnknownVal(); 867 } 868 869 SVal SValBuilder::evalCastSubKind(nonloc::LocAsInteger V, QualType CastTy, 870 QualType OriginalTy) { 871 Loc L = V.getLoc(); 872 873 // Pointer as integer to bool. 874 if (CastTy->isBooleanType()) 875 // Pass to Loc function. 876 return evalCastKind(L, CastTy, OriginalTy); 877 878 const bool IsUnknownOriginalType = OriginalTy.isNull(); 879 // Pointer as integer to pointer. 880 if (!IsUnknownOriginalType && Loc::isLocType(CastTy) && 881 OriginalTy->isIntegralOrEnumerationType()) { 882 if (const MemRegion *R = L.getAsRegion()) 883 if (auto OptMemRegV = getCastedMemRegionVal(R, CastTy)) 884 return *OptMemRegV; 885 return L; 886 } 887 888 // Pointer as integer with region to integer/pointer. 889 const MemRegion *R = L.getAsRegion(); 890 if (!IsUnknownOriginalType && R) { 891 if (CastTy->isIntegralOrEnumerationType()) 892 return evalCastSubKind(loc::MemRegionVal(R), CastTy, OriginalTy); 893 894 if (Loc::isLocType(CastTy)) { 895 assert(Loc::isLocType(OriginalTy) || OriginalTy->isFunctionType() || 896 CastTy->isReferenceType()); 897 // Delegate to store manager to get the result of casting a region to a 898 // different type. If the MemRegion* returned is NULL, this expression 899 // Evaluates to UnknownVal. 900 if (auto OptMemRegV = getCastedMemRegionVal(R, CastTy)) 901 return *OptMemRegV; 902 } 903 } else { 904 if (Loc::isLocType(CastTy)) { 905 if (IsUnknownOriginalType) 906 return evalCastSubKind(loc::MemRegionVal(R), CastTy, OriginalTy); 907 return L; 908 } 909 910 SymbolRef SE = nullptr; 911 if (R) { 912 if (const SymbolicRegion *SR = 913 dyn_cast<SymbolicRegion>(R->StripCasts())) { 914 SE = SR->getSymbol(); 915 } 916 } 917 918 if (!CastTy->isFloatingType() || !SE || SE->getType()->isFloatingType()) { 919 // FIXME: Correctly support promotions/truncations. 920 const unsigned CastSize = Context.getIntWidth(CastTy); 921 if (CastSize == V.getNumBits()) 922 return V; 923 924 return makeLocAsInteger(L, CastSize); 925 } 926 } 927 928 // Pointer as integer to whatever else. 929 return UnknownVal(); 930 } 931 932 SVal SValBuilder::evalCastSubKind(nonloc::SymbolVal V, QualType CastTy, 933 QualType OriginalTy) { 934 SymbolRef SE = V.getSymbol(); 935 936 const bool IsUnknownOriginalType = OriginalTy.isNull(); 937 // Symbol to bool. 938 if (!IsUnknownOriginalType && CastTy->isBooleanType()) { 939 // Non-float to bool. 940 if (Loc::isLocType(OriginalTy) || 941 OriginalTy->isIntegralOrEnumerationType() || 942 OriginalTy->isMemberPointerType()) { 943 BasicValueFactory &BVF = getBasicValueFactory(); 944 return makeNonLoc(SE, BO_NE, BVF.getValue(0, SE->getType()), CastTy); 945 } 946 } else { 947 // Symbol to integer, float. 948 QualType T = Context.getCanonicalType(SE->getType()); 949 // If types are the same or both are integers, ignore the cast. 950 // FIXME: Remove this hack when we support symbolic truncation/extension. 951 // HACK: If both castTy and T are integers, ignore the cast. This is 952 // not a permanent solution. Eventually we want to precisely handle 953 // extension/truncation of symbolic integers. This prevents us from losing 954 // precision when we assign 'x = y' and 'y' is symbolic and x and y are 955 // different integer types. 956 if (haveSameType(T, CastTy)) 957 return V; 958 if (!Loc::isLocType(CastTy)) 959 if (!IsUnknownOriginalType || !CastTy->isFloatingType() || 960 T->isFloatingType()) 961 return makeNonLoc(SE, T, CastTy); 962 } 963 964 // Symbol to pointer and whatever else. 965 return UnknownVal(); 966 } 967 968 SVal SValBuilder::evalCastSubKind(nonloc::PointerToMember V, QualType CastTy, 969 QualType OriginalTy) { 970 // Member pointer to whatever. 971 return V; 972 } 973