1 //=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- 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 ExprEngine's support for C expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ExprCXX.h" 15 #include "clang/AST/DeclCXX.h" 16 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 17 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 18 19 using namespace clang; 20 using namespace ento; 21 using llvm::APSInt; 22 23 void ExprEngine::VisitBinaryOperator(const BinaryOperator* B, 24 ExplodedNode *Pred, 25 ExplodedNodeSet &Dst) { 26 27 Expr *LHS = B->getLHS()->IgnoreParens(); 28 Expr *RHS = B->getRHS()->IgnoreParens(); 29 30 // FIXME: Prechecks eventually go in ::Visit(). 31 ExplodedNodeSet CheckedSet; 32 ExplodedNodeSet Tmp2; 33 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this); 34 35 // With both the LHS and RHS evaluated, process the operation itself. 36 for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end(); 37 it != ei; ++it) { 38 39 ProgramStateRef state = (*it)->getState(); 40 const LocationContext *LCtx = (*it)->getLocationContext(); 41 SVal LeftV = state->getSVal(LHS, LCtx); 42 SVal RightV = state->getSVal(RHS, LCtx); 43 44 BinaryOperator::Opcode Op = B->getOpcode(); 45 46 if (Op == BO_Assign) { 47 // EXPERIMENTAL: "Conjured" symbols. 48 // FIXME: Handle structs. 49 if (RightV.isUnknown()) { 50 unsigned Count = currBldrCtx->blockCount(); 51 RightV = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx, 52 Count); 53 } 54 // Simulate the effects of a "store": bind the value of the RHS 55 // to the L-Value represented by the LHS. 56 SVal ExprVal = B->isGLValue() ? LeftV : RightV; 57 evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal), 58 LeftV, RightV); 59 continue; 60 } 61 62 if (!B->isAssignmentOp()) { 63 StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx); 64 65 if (B->isAdditiveOp()) { 66 // If one of the operands is a location, conjure a symbol for the other 67 // one (offset) if it's unknown so that memory arithmetic always 68 // results in an ElementRegion. 69 // TODO: This can be removed after we enable history tracking with 70 // SymSymExpr. 71 unsigned Count = currBldrCtx->blockCount(); 72 if (LeftV.getAs<Loc>() && 73 RHS->getType()->isIntegralOrEnumerationType() && 74 RightV.isUnknown()) { 75 RightV = svalBuilder.conjureSymbolVal(RHS, LCtx, RHS->getType(), 76 Count); 77 } 78 if (RightV.getAs<Loc>() && 79 LHS->getType()->isIntegralOrEnumerationType() && 80 LeftV.isUnknown()) { 81 LeftV = svalBuilder.conjureSymbolVal(LHS, LCtx, LHS->getType(), 82 Count); 83 } 84 } 85 86 // Although we don't yet model pointers-to-members, we do need to make 87 // sure that the members of temporaries have a valid 'this' pointer for 88 // other checks. 89 if (B->getOpcode() == BO_PtrMemD) 90 state = createTemporaryRegionIfNeeded(state, LCtx, LHS); 91 92 // Process non-assignments except commas or short-circuited 93 // logical expressions (LAnd and LOr). 94 SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType()); 95 if (!Result.isUnknown()) { 96 state = state->BindExpr(B, LCtx, Result); 97 } 98 99 Bldr.generateNode(B, *it, state); 100 continue; 101 } 102 103 assert (B->isCompoundAssignmentOp()); 104 105 switch (Op) { 106 default: 107 llvm_unreachable("Invalid opcode for compound assignment."); 108 case BO_MulAssign: Op = BO_Mul; break; 109 case BO_DivAssign: Op = BO_Div; break; 110 case BO_RemAssign: Op = BO_Rem; break; 111 case BO_AddAssign: Op = BO_Add; break; 112 case BO_SubAssign: Op = BO_Sub; break; 113 case BO_ShlAssign: Op = BO_Shl; break; 114 case BO_ShrAssign: Op = BO_Shr; break; 115 case BO_AndAssign: Op = BO_And; break; 116 case BO_XorAssign: Op = BO_Xor; break; 117 case BO_OrAssign: Op = BO_Or; break; 118 } 119 120 // Perform a load (the LHS). This performs the checks for 121 // null dereferences, and so on. 122 ExplodedNodeSet Tmp; 123 SVal location = LeftV; 124 evalLoad(Tmp, B, LHS, *it, state, location); 125 126 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; 127 ++I) { 128 129 state = (*I)->getState(); 130 const LocationContext *LCtx = (*I)->getLocationContext(); 131 SVal V = state->getSVal(LHS, LCtx); 132 133 // Get the computation type. 134 QualType CTy = 135 cast<CompoundAssignOperator>(B)->getComputationResultType(); 136 CTy = getContext().getCanonicalType(CTy); 137 138 QualType CLHSTy = 139 cast<CompoundAssignOperator>(B)->getComputationLHSType(); 140 CLHSTy = getContext().getCanonicalType(CLHSTy); 141 142 QualType LTy = getContext().getCanonicalType(LHS->getType()); 143 144 // Promote LHS. 145 V = svalBuilder.evalCast(V, CLHSTy, LTy); 146 147 // Compute the result of the operation. 148 SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy), 149 B->getType(), CTy); 150 151 // EXPERIMENTAL: "Conjured" symbols. 152 // FIXME: Handle structs. 153 154 SVal LHSVal; 155 156 if (Result.isUnknown()) { 157 // The symbolic value is actually for the type of the left-hand side 158 // expression, not the computation type, as this is the value the 159 // LValue on the LHS will bind to. 160 LHSVal = svalBuilder.conjureSymbolVal(nullptr, B->getRHS(), LCtx, LTy, 161 currBldrCtx->blockCount()); 162 // However, we need to convert the symbol to the computation type. 163 Result = svalBuilder.evalCast(LHSVal, CTy, LTy); 164 } 165 else { 166 // The left-hand side may bind to a different value then the 167 // computation type. 168 LHSVal = svalBuilder.evalCast(Result, LTy, CTy); 169 } 170 171 // In C++, assignment and compound assignment operators return an 172 // lvalue. 173 if (B->isGLValue()) 174 state = state->BindExpr(B, LCtx, location); 175 else 176 state = state->BindExpr(B, LCtx, Result); 177 178 evalStore(Tmp2, B, LHS, *I, state, location, LHSVal); 179 } 180 } 181 182 // FIXME: postvisits eventually go in ::Visit() 183 getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this); 184 } 185 186 void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred, 187 ExplodedNodeSet &Dst) { 188 189 CanQualType T = getContext().getCanonicalType(BE->getType()); 190 191 const BlockDecl *BD = BE->getBlockDecl(); 192 // Get the value of the block itself. 193 SVal V = svalBuilder.getBlockPointer(BD, T, 194 Pred->getLocationContext(), 195 currBldrCtx->blockCount()); 196 197 ProgramStateRef State = Pred->getState(); 198 199 // If we created a new MemRegion for the block, we should explicitly bind 200 // the captured variables. 201 if (const BlockDataRegion *BDR = 202 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) { 203 204 BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(), 205 E = BDR->referenced_vars_end(); 206 207 auto CI = BD->capture_begin(); 208 auto CE = BD->capture_end(); 209 for (; I != E; ++I) { 210 const VarRegion *capturedR = I.getCapturedRegion(); 211 const VarRegion *originalR = I.getOriginalRegion(); 212 213 // If the capture had a copy expression, use the result of evaluating 214 // that expression, otherwise use the original value. 215 // We rely on the invariant that the block declaration's capture variables 216 // are a prefix of the BlockDataRegion's referenced vars (which may include 217 // referenced globals, etc.) to enable fast lookup of the capture for a 218 // given referenced var. 219 const Expr *copyExpr = nullptr; 220 if (CI != CE) { 221 assert(CI->getVariable() == capturedR->getDecl()); 222 copyExpr = CI->getCopyExpr(); 223 CI++; 224 } 225 226 if (capturedR != originalR) { 227 SVal originalV; 228 const LocationContext *LCtx = Pred->getLocationContext(); 229 if (copyExpr) { 230 originalV = State->getSVal(copyExpr, LCtx); 231 } else { 232 originalV = State->getSVal(loc::MemRegionVal(originalR)); 233 } 234 State = State->bindLoc(loc::MemRegionVal(capturedR), originalV, LCtx); 235 } 236 } 237 } 238 239 ExplodedNodeSet Tmp; 240 StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx); 241 Bldr.generateNode(BE, Pred, 242 State->BindExpr(BE, Pred->getLocationContext(), V), 243 nullptr, ProgramPoint::PostLValueKind); 244 245 // FIXME: Move all post/pre visits to ::Visit(). 246 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this); 247 } 248 249 ProgramStateRef ExprEngine::handleLValueBitCast( 250 ProgramStateRef state, const Expr* Ex, const LocationContext* LCtx, 251 QualType T, QualType ExTy, const CastExpr* CastE, StmtNodeBuilder& Bldr, 252 ExplodedNode* Pred) { 253 // Delegate to SValBuilder to process. 254 SVal V = state->getSVal(Ex, LCtx); 255 V = svalBuilder.evalCast(V, T, ExTy); 256 // Negate the result if we're treating the boolean as a signed i1 257 if (CastE->getCastKind() == CK_BooleanToSignedIntegral) 258 V = evalMinus(V); 259 state = state->BindExpr(CastE, LCtx, V); 260 Bldr.generateNode(CastE, Pred, state); 261 262 return state; 263 } 264 265 ProgramStateRef ExprEngine::handleLVectorSplat( 266 ProgramStateRef state, const LocationContext* LCtx, const CastExpr* CastE, 267 StmtNodeBuilder &Bldr, ExplodedNode* Pred) { 268 // Recover some path sensitivity by conjuring a new value. 269 QualType resultType = CastE->getType(); 270 if (CastE->isGLValue()) 271 resultType = getContext().getPointerType(resultType); 272 SVal result = svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, 273 resultType, 274 currBldrCtx->blockCount()); 275 state = state->BindExpr(CastE, LCtx, result); 276 Bldr.generateNode(CastE, Pred, state); 277 278 return state; 279 } 280 281 void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex, 282 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 283 284 ExplodedNodeSet dstPreStmt; 285 getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this); 286 287 if (CastE->getCastKind() == CK_LValueToRValue) { 288 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end(); 289 I!=E; ++I) { 290 ExplodedNode *subExprNode = *I; 291 ProgramStateRef state = subExprNode->getState(); 292 const LocationContext *LCtx = subExprNode->getLocationContext(); 293 evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx)); 294 } 295 return; 296 } 297 298 // All other casts. 299 QualType T = CastE->getType(); 300 QualType ExTy = Ex->getType(); 301 302 if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE)) 303 T = ExCast->getTypeAsWritten(); 304 305 StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx); 306 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end(); 307 I != E; ++I) { 308 309 Pred = *I; 310 ProgramStateRef state = Pred->getState(); 311 const LocationContext *LCtx = Pred->getLocationContext(); 312 313 switch (CastE->getCastKind()) { 314 case CK_LValueToRValue: 315 llvm_unreachable("LValueToRValue casts handled earlier."); 316 case CK_ToVoid: 317 continue; 318 // The analyzer doesn't do anything special with these casts, 319 // since it understands retain/release semantics already. 320 case CK_ARCProduceObject: 321 case CK_ARCConsumeObject: 322 case CK_ARCReclaimReturnedObject: 323 case CK_ARCExtendBlockObject: // Fall-through. 324 case CK_CopyAndAutoreleaseBlockObject: 325 // The analyser can ignore atomic casts for now, although some future 326 // checkers may want to make certain that you're not modifying the same 327 // value through atomic and nonatomic pointers. 328 case CK_AtomicToNonAtomic: 329 case CK_NonAtomicToAtomic: 330 // True no-ops. 331 case CK_NoOp: 332 case CK_ConstructorConversion: 333 case CK_UserDefinedConversion: 334 case CK_FunctionToPointerDecay: 335 case CK_BuiltinFnToFnPtr: { 336 // Copy the SVal of Ex to CastE. 337 ProgramStateRef state = Pred->getState(); 338 const LocationContext *LCtx = Pred->getLocationContext(); 339 SVal V = state->getSVal(Ex, LCtx); 340 state = state->BindExpr(CastE, LCtx, V); 341 Bldr.generateNode(CastE, Pred, state); 342 continue; 343 } 344 case CK_MemberPointerToBoolean: 345 case CK_PointerToBoolean: { 346 SVal V = state->getSVal(Ex, LCtx); 347 auto PTMSV = V.getAs<nonloc::PointerToMember>(); 348 if (PTMSV) 349 V = svalBuilder.makeTruthVal(!PTMSV->isNullMemberPointer(), ExTy); 350 if (V.isUndef() || PTMSV) { 351 state = state->BindExpr(CastE, LCtx, V); 352 Bldr.generateNode(CastE, Pred, state); 353 continue; 354 } 355 // Explicitly proceed with default handler for this case cascade. 356 state = 357 handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred); 358 continue; 359 } 360 case CK_Dependent: 361 case CK_ArrayToPointerDecay: 362 case CK_BitCast: 363 case CK_AddressSpaceConversion: 364 case CK_BooleanToSignedIntegral: 365 case CK_NullToPointer: 366 case CK_IntegralToPointer: 367 case CK_PointerToIntegral: { 368 SVal V = state->getSVal(Ex, LCtx); 369 if (V.getAs<nonloc::PointerToMember>()) { 370 state = state->BindExpr(CastE, LCtx, UnknownVal()); 371 Bldr.generateNode(CastE, Pred, state); 372 continue; 373 } 374 // Explicitly proceed with default handler for this case cascade. 375 state = 376 handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred); 377 continue; 378 } 379 case CK_IntegralToBoolean: 380 case CK_IntegralToFloating: 381 case CK_FloatingToIntegral: 382 case CK_FloatingToBoolean: 383 case CK_FloatingCast: 384 case CK_FloatingRealToComplex: 385 case CK_FloatingComplexToReal: 386 case CK_FloatingComplexToBoolean: 387 case CK_FloatingComplexCast: 388 case CK_FloatingComplexToIntegralComplex: 389 case CK_IntegralRealToComplex: 390 case CK_IntegralComplexToReal: 391 case CK_IntegralComplexToBoolean: 392 case CK_IntegralComplexCast: 393 case CK_IntegralComplexToFloatingComplex: 394 case CK_CPointerToObjCPointerCast: 395 case CK_BlockPointerToObjCPointerCast: 396 case CK_AnyPointerToBlockPointerCast: 397 case CK_ObjCObjectLValueCast: 398 case CK_ZeroToOCLEvent: 399 case CK_ZeroToOCLQueue: 400 case CK_IntToOCLSampler: 401 case CK_LValueBitCast: { 402 state = 403 handleLValueBitCast(state, Ex, LCtx, T, ExTy, CastE, Bldr, Pred); 404 continue; 405 } 406 case CK_IntegralCast: { 407 // Delegate to SValBuilder to process. 408 SVal V = state->getSVal(Ex, LCtx); 409 V = svalBuilder.evalIntegralCast(state, V, T, ExTy); 410 state = state->BindExpr(CastE, LCtx, V); 411 Bldr.generateNode(CastE, Pred, state); 412 continue; 413 } 414 case CK_DerivedToBase: 415 case CK_UncheckedDerivedToBase: { 416 // For DerivedToBase cast, delegate to the store manager. 417 SVal val = state->getSVal(Ex, LCtx); 418 val = getStoreManager().evalDerivedToBase(val, CastE); 419 state = state->BindExpr(CastE, LCtx, val); 420 Bldr.generateNode(CastE, Pred, state); 421 continue; 422 } 423 // Handle C++ dyn_cast. 424 case CK_Dynamic: { 425 SVal val = state->getSVal(Ex, LCtx); 426 427 // Compute the type of the result. 428 QualType resultType = CastE->getType(); 429 if (CastE->isGLValue()) 430 resultType = getContext().getPointerType(resultType); 431 432 bool Failed = false; 433 434 // Check if the value being cast evaluates to 0. 435 if (val.isZeroConstant()) 436 Failed = true; 437 // Else, evaluate the cast. 438 else 439 val = getStoreManager().attemptDownCast(val, T, Failed); 440 441 if (Failed) { 442 if (T->isReferenceType()) { 443 // A bad_cast exception is thrown if input value is a reference. 444 // Currently, we model this, by generating a sink. 445 Bldr.generateSink(CastE, Pred, state); 446 continue; 447 } else { 448 // If the cast fails on a pointer, bind to 0. 449 state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull()); 450 } 451 } else { 452 // If we don't know if the cast succeeded, conjure a new symbol. 453 if (val.isUnknown()) { 454 DefinedOrUnknownSVal NewSym = 455 svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType, 456 currBldrCtx->blockCount()); 457 state = state->BindExpr(CastE, LCtx, NewSym); 458 } else 459 // Else, bind to the derived region value. 460 state = state->BindExpr(CastE, LCtx, val); 461 } 462 Bldr.generateNode(CastE, Pred, state); 463 continue; 464 } 465 case CK_BaseToDerived: { 466 SVal val = state->getSVal(Ex, LCtx); 467 QualType resultType = CastE->getType(); 468 if (CastE->isGLValue()) 469 resultType = getContext().getPointerType(resultType); 470 471 bool Failed = false; 472 473 if (!val.isConstant()) { 474 val = getStoreManager().attemptDownCast(val, T, Failed); 475 } 476 477 // Failed to cast or the result is unknown, fall back to conservative. 478 if (Failed || val.isUnknown()) { 479 val = 480 svalBuilder.conjureSymbolVal(nullptr, CastE, LCtx, resultType, 481 currBldrCtx->blockCount()); 482 } 483 state = state->BindExpr(CastE, LCtx, val); 484 Bldr.generateNode(CastE, Pred, state); 485 continue; 486 } 487 case CK_NullToMemberPointer: { 488 SVal V = svalBuilder.getMemberPointer(nullptr); 489 state = state->BindExpr(CastE, LCtx, V); 490 Bldr.generateNode(CastE, Pred, state); 491 continue; 492 } 493 case CK_DerivedToBaseMemberPointer: 494 case CK_BaseToDerivedMemberPointer: 495 case CK_ReinterpretMemberPointer: { 496 SVal V = state->getSVal(Ex, LCtx); 497 if (auto PTMSV = V.getAs<nonloc::PointerToMember>()) { 498 SVal CastedPTMSV = svalBuilder.makePointerToMember( 499 getBasicVals().accumCXXBase( 500 llvm::make_range<CastExpr::path_const_iterator>( 501 CastE->path_begin(), CastE->path_end()), *PTMSV)); 502 state = state->BindExpr(CastE, LCtx, CastedPTMSV); 503 Bldr.generateNode(CastE, Pred, state); 504 continue; 505 } 506 // Explicitly proceed with default handler for this case cascade. 507 state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred); 508 continue; 509 } 510 // Various C++ casts that are not handled yet. 511 case CK_ToUnion: 512 case CK_VectorSplat: { 513 state = handleLVectorSplat(state, LCtx, CastE, Bldr, Pred); 514 continue; 515 } 516 } 517 } 518 } 519 520 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL, 521 ExplodedNode *Pred, 522 ExplodedNodeSet &Dst) { 523 StmtNodeBuilder B(Pred, Dst, *currBldrCtx); 524 525 ProgramStateRef State = Pred->getState(); 526 const LocationContext *LCtx = Pred->getLocationContext(); 527 528 const Expr *Init = CL->getInitializer(); 529 SVal V = State->getSVal(CL->getInitializer(), LCtx); 530 531 if (isa<CXXConstructExpr>(Init)) { 532 // No work needed. Just pass the value up to this expression. 533 } else { 534 assert(isa<InitListExpr>(Init)); 535 Loc CLLoc = State->getLValue(CL, LCtx); 536 State = State->bindLoc(CLLoc, V, LCtx); 537 538 if (CL->isGLValue()) 539 V = CLLoc; 540 } 541 542 B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V)); 543 } 544 545 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred, 546 ExplodedNodeSet &Dst) { 547 // Assumption: The CFG has one DeclStmt per Decl. 548 const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin()); 549 550 if (!VD) { 551 //TODO:AZ: remove explicit insertion after refactoring is done. 552 Dst.insert(Pred); 553 return; 554 } 555 556 // FIXME: all pre/post visits should eventually be handled by ::Visit(). 557 ExplodedNodeSet dstPreVisit; 558 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this); 559 560 ExplodedNodeSet dstEvaluated; 561 StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx); 562 for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end(); 563 I!=E; ++I) { 564 ExplodedNode *N = *I; 565 ProgramStateRef state = N->getState(); 566 const LocationContext *LC = N->getLocationContext(); 567 568 // Decls without InitExpr are not initialized explicitly. 569 if (const Expr *InitEx = VD->getInit()) { 570 571 // Note in the state that the initialization has occurred. 572 ExplodedNode *UpdatedN = N; 573 SVal InitVal = state->getSVal(InitEx, LC); 574 575 assert(DS->isSingleDecl()); 576 if (auto *CtorExpr = findDirectConstructorForCurrentCFGElement()) { 577 assert(InitEx->IgnoreImplicit() == CtorExpr); 578 (void)CtorExpr; 579 // We constructed the object directly in the variable. 580 // No need to bind anything. 581 B.generateNode(DS, UpdatedN, state); 582 } else { 583 // We bound the temp obj region to the CXXConstructExpr. Now recover 584 // the lazy compound value when the variable is not a reference. 585 if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() && 586 !VD->getType()->isReferenceType()) { 587 if (Optional<loc::MemRegionVal> M = 588 InitVal.getAs<loc::MemRegionVal>()) { 589 InitVal = state->getSVal(M->getRegion()); 590 assert(InitVal.getAs<nonloc::LazyCompoundVal>()); 591 } 592 } 593 594 // Recover some path-sensitivity if a scalar value evaluated to 595 // UnknownVal. 596 if (InitVal.isUnknown()) { 597 QualType Ty = InitEx->getType(); 598 if (InitEx->isGLValue()) { 599 Ty = getContext().getPointerType(Ty); 600 } 601 602 InitVal = svalBuilder.conjureSymbolVal(nullptr, InitEx, LC, Ty, 603 currBldrCtx->blockCount()); 604 } 605 606 607 B.takeNodes(UpdatedN); 608 ExplodedNodeSet Dst2; 609 evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true); 610 B.addNodes(Dst2); 611 } 612 } 613 else { 614 B.generateNode(DS, N, state); 615 } 616 } 617 618 getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this); 619 } 620 621 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred, 622 ExplodedNodeSet &Dst) { 623 assert(B->getOpcode() == BO_LAnd || 624 B->getOpcode() == BO_LOr); 625 626 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 627 ProgramStateRef state = Pred->getState(); 628 629 ExplodedNode *N = Pred; 630 while (!N->getLocation().getAs<BlockEntrance>()) { 631 ProgramPoint P = N->getLocation(); 632 assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>()); 633 (void) P; 634 assert(N->pred_size() == 1); 635 N = *N->pred_begin(); 636 } 637 assert(N->pred_size() == 1); 638 N = *N->pred_begin(); 639 BlockEdge BE = N->getLocation().castAs<BlockEdge>(); 640 SVal X; 641 642 // Determine the value of the expression by introspecting how we 643 // got this location in the CFG. This requires looking at the previous 644 // block we were in and what kind of control-flow transfer was involved. 645 const CFGBlock *SrcBlock = BE.getSrc(); 646 // The only terminator (if there is one) that makes sense is a logical op. 647 CFGTerminator T = SrcBlock->getTerminator(); 648 if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) { 649 (void) Term; 650 assert(Term->isLogicalOp()); 651 assert(SrcBlock->succ_size() == 2); 652 // Did we take the true or false branch? 653 unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0; 654 X = svalBuilder.makeIntVal(constant, B->getType()); 655 } 656 else { 657 // If there is no terminator, by construction the last statement 658 // in SrcBlock is the value of the enclosing expression. 659 // However, we still need to constrain that value to be 0 or 1. 660 assert(!SrcBlock->empty()); 661 CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>(); 662 const Expr *RHS = cast<Expr>(Elem.getStmt()); 663 SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext()); 664 665 if (RHSVal.isUndef()) { 666 X = RHSVal; 667 } else { 668 // We evaluate "RHSVal != 0" expression which result in 0 if the value is 669 // known to be false, 1 if the value is known to be true and a new symbol 670 // when the assumption is unknown. 671 nonloc::ConcreteInt Zero(getBasicVals().getValue(0, B->getType())); 672 X = evalBinOp(N->getState(), BO_NE, 673 svalBuilder.evalCast(RHSVal, B->getType(), RHS->getType()), 674 Zero, B->getType()); 675 } 676 } 677 Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X)); 678 } 679 680 void ExprEngine::VisitInitListExpr(const InitListExpr *IE, 681 ExplodedNode *Pred, 682 ExplodedNodeSet &Dst) { 683 StmtNodeBuilder B(Pred, Dst, *currBldrCtx); 684 685 ProgramStateRef state = Pred->getState(); 686 const LocationContext *LCtx = Pred->getLocationContext(); 687 QualType T = getContext().getCanonicalType(IE->getType()); 688 unsigned NumInitElements = IE->getNumInits(); 689 690 if (!IE->isGLValue() && 691 (T->isArrayType() || T->isRecordType() || T->isVectorType() || 692 T->isAnyComplexType())) { 693 llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList(); 694 695 // Handle base case where the initializer has no elements. 696 // e.g: static int* myArray[] = {}; 697 if (NumInitElements == 0) { 698 SVal V = svalBuilder.makeCompoundVal(T, vals); 699 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V)); 700 return; 701 } 702 703 for (InitListExpr::const_reverse_iterator it = IE->rbegin(), 704 ei = IE->rend(); it != ei; ++it) { 705 SVal V = state->getSVal(cast<Expr>(*it), LCtx); 706 vals = getBasicVals().prependSVal(V, vals); 707 } 708 709 B.generateNode(IE, Pred, 710 state->BindExpr(IE, LCtx, 711 svalBuilder.makeCompoundVal(T, vals))); 712 return; 713 } 714 715 // Handle scalars: int{5} and int{} and GLvalues. 716 // Note, if the InitListExpr is a GLvalue, it means that there is an address 717 // representing it, so it must have a single init element. 718 assert(NumInitElements <= 1); 719 720 SVal V; 721 if (NumInitElements == 0) 722 V = getSValBuilder().makeZeroVal(T); 723 else 724 V = state->getSVal(IE->getInit(0), LCtx); 725 726 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V)); 727 } 728 729 void ExprEngine::VisitGuardedExpr(const Expr *Ex, 730 const Expr *L, 731 const Expr *R, 732 ExplodedNode *Pred, 733 ExplodedNodeSet &Dst) { 734 assert(L && R); 735 736 StmtNodeBuilder B(Pred, Dst, *currBldrCtx); 737 ProgramStateRef state = Pred->getState(); 738 const LocationContext *LCtx = Pred->getLocationContext(); 739 const CFGBlock *SrcBlock = nullptr; 740 741 // Find the predecessor block. 742 ProgramStateRef SrcState = state; 743 for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) { 744 ProgramPoint PP = N->getLocation(); 745 if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) { 746 assert(N->pred_size() == 1); 747 continue; 748 } 749 SrcBlock = PP.castAs<BlockEdge>().getSrc(); 750 SrcState = N->getState(); 751 break; 752 } 753 754 assert(SrcBlock && "missing function entry"); 755 756 // Find the last expression in the predecessor block. That is the 757 // expression that is used for the value of the ternary expression. 758 bool hasValue = false; 759 SVal V; 760 761 for (CFGElement CE : llvm::reverse(*SrcBlock)) { 762 if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) { 763 const Expr *ValEx = cast<Expr>(CS->getStmt()); 764 ValEx = ValEx->IgnoreParens(); 765 766 // For GNU extension '?:' operator, the left hand side will be an 767 // OpaqueValueExpr, so get the underlying expression. 768 if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L)) 769 L = OpaqueEx->getSourceExpr(); 770 771 // If the last expression in the predecessor block matches true or false 772 // subexpression, get its the value. 773 if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) { 774 hasValue = true; 775 V = SrcState->getSVal(ValEx, LCtx); 776 } 777 break; 778 } 779 } 780 781 if (!hasValue) 782 V = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx, 783 currBldrCtx->blockCount()); 784 785 // Generate a new node with the binding from the appropriate path. 786 B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true)); 787 } 788 789 void ExprEngine:: 790 VisitOffsetOfExpr(const OffsetOfExpr *OOE, 791 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 792 StmtNodeBuilder B(Pred, Dst, *currBldrCtx); 793 APSInt IV; 794 if (OOE->EvaluateAsInt(IV, getContext())) { 795 assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType())); 796 assert(OOE->getType()->isBuiltinType()); 797 assert(OOE->getType()->getAs<BuiltinType>()->isInteger()); 798 assert(IV.isSigned() == OOE->getType()->isSignedIntegerType()); 799 SVal X = svalBuilder.makeIntVal(IV); 800 B.generateNode(OOE, Pred, 801 Pred->getState()->BindExpr(OOE, Pred->getLocationContext(), 802 X)); 803 } 804 // FIXME: Handle the case where __builtin_offsetof is not a constant. 805 } 806 807 808 void ExprEngine:: 809 VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex, 810 ExplodedNode *Pred, 811 ExplodedNodeSet &Dst) { 812 // FIXME: Prechecks eventually go in ::Visit(). 813 ExplodedNodeSet CheckedSet; 814 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, Ex, *this); 815 816 ExplodedNodeSet EvalSet; 817 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx); 818 819 QualType T = Ex->getTypeOfArgument(); 820 821 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 822 I != E; ++I) { 823 if (Ex->getKind() == UETT_SizeOf) { 824 if (!T->isIncompleteType() && !T->isConstantSizeType()) { 825 assert(T->isVariableArrayType() && "Unknown non-constant-sized type."); 826 827 // FIXME: Add support for VLA type arguments and VLA expressions. 828 // When that happens, we should probably refactor VLASizeChecker's code. 829 continue; 830 } else if (T->getAs<ObjCObjectType>()) { 831 // Some code tries to take the sizeof an ObjCObjectType, relying that 832 // the compiler has laid out its representation. Just report Unknown 833 // for these. 834 continue; 835 } 836 } 837 838 APSInt Value = Ex->EvaluateKnownConstInt(getContext()); 839 CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue()); 840 841 ProgramStateRef state = (*I)->getState(); 842 state = state->BindExpr(Ex, (*I)->getLocationContext(), 843 svalBuilder.makeIntVal(amt.getQuantity(), 844 Ex->getType())); 845 Bldr.generateNode(Ex, *I, state); 846 } 847 848 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, Ex, *this); 849 } 850 851 void ExprEngine::handleUOExtension(ExplodedNodeSet::iterator I, 852 const UnaryOperator *U, 853 StmtNodeBuilder &Bldr) { 854 // FIXME: We can probably just have some magic in Environment::getSVal() 855 // that propagates values, instead of creating a new node here. 856 // 857 // Unary "+" is a no-op, similar to a parentheses. We still have places 858 // where it may be a block-level expression, so we need to 859 // generate an extra node that just propagates the value of the 860 // subexpression. 861 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 862 ProgramStateRef state = (*I)->getState(); 863 const LocationContext *LCtx = (*I)->getLocationContext(); 864 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, 865 state->getSVal(Ex, LCtx))); 866 } 867 868 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U, ExplodedNode *Pred, 869 ExplodedNodeSet &Dst) { 870 // FIXME: Prechecks eventually go in ::Visit(). 871 ExplodedNodeSet CheckedSet; 872 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this); 873 874 ExplodedNodeSet EvalSet; 875 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx); 876 877 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end(); 878 I != E; ++I) { 879 switch (U->getOpcode()) { 880 default: { 881 Bldr.takeNodes(*I); 882 ExplodedNodeSet Tmp; 883 VisitIncrementDecrementOperator(U, *I, Tmp); 884 Bldr.addNodes(Tmp); 885 break; 886 } 887 case UO_Real: { 888 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 889 890 // FIXME: We don't have complex SValues yet. 891 if (Ex->getType()->isAnyComplexType()) { 892 // Just report "Unknown." 893 break; 894 } 895 896 // For all other types, UO_Real is an identity operation. 897 assert (U->getType() == Ex->getType()); 898 ProgramStateRef state = (*I)->getState(); 899 const LocationContext *LCtx = (*I)->getLocationContext(); 900 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, 901 state->getSVal(Ex, LCtx))); 902 break; 903 } 904 905 case UO_Imag: { 906 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 907 // FIXME: We don't have complex SValues yet. 908 if (Ex->getType()->isAnyComplexType()) { 909 // Just report "Unknown." 910 break; 911 } 912 // For all other types, UO_Imag returns 0. 913 ProgramStateRef state = (*I)->getState(); 914 const LocationContext *LCtx = (*I)->getLocationContext(); 915 SVal X = svalBuilder.makeZeroVal(Ex->getType()); 916 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X)); 917 break; 918 } 919 920 case UO_AddrOf: { 921 // Process pointer-to-member address operation. 922 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 923 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex)) { 924 const ValueDecl *VD = DRE->getDecl(); 925 926 if (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD)) { 927 ProgramStateRef State = (*I)->getState(); 928 const LocationContext *LCtx = (*I)->getLocationContext(); 929 SVal SV = svalBuilder.getMemberPointer(cast<DeclaratorDecl>(VD)); 930 Bldr.generateNode(U, *I, State->BindExpr(U, LCtx, SV)); 931 break; 932 } 933 } 934 // Explicitly proceed with default handler for this case cascade. 935 handleUOExtension(I, U, Bldr); 936 break; 937 } 938 case UO_Plus: 939 assert(!U->isGLValue()); 940 // FALL-THROUGH. 941 case UO_Deref: 942 case UO_Extension: { 943 handleUOExtension(I, U, Bldr); 944 break; 945 } 946 947 case UO_LNot: 948 case UO_Minus: 949 case UO_Not: { 950 assert (!U->isGLValue()); 951 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 952 ProgramStateRef state = (*I)->getState(); 953 const LocationContext *LCtx = (*I)->getLocationContext(); 954 955 // Get the value of the subexpression. 956 SVal V = state->getSVal(Ex, LCtx); 957 958 if (V.isUnknownOrUndef()) { 959 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V)); 960 break; 961 } 962 963 switch (U->getOpcode()) { 964 default: 965 llvm_unreachable("Invalid Opcode."); 966 case UO_Not: 967 // FIXME: Do we need to handle promotions? 968 state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>())); 969 break; 970 case UO_Minus: 971 // FIXME: Do we need to handle promotions? 972 state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>())); 973 break; 974 case UO_LNot: 975 // C99 6.5.3.3: "The expression !E is equivalent to (0==E)." 976 // 977 // Note: technically we do "E == 0", but this is the same in the 978 // transfer functions as "0 == E". 979 SVal Result; 980 if (Optional<Loc> LV = V.getAs<Loc>()) { 981 Loc X = svalBuilder.makeNullWithType(Ex->getType()); 982 Result = evalBinOp(state, BO_EQ, *LV, X, U->getType()); 983 } else if (Ex->getType()->isFloatingType()) { 984 // FIXME: handle floating point types. 985 Result = UnknownVal(); 986 } else { 987 nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType())); 988 Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X, 989 U->getType()); 990 } 991 992 state = state->BindExpr(U, LCtx, Result); 993 break; 994 } 995 Bldr.generateNode(U, *I, state); 996 break; 997 } 998 } 999 } 1000 1001 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this); 1002 } 1003 1004 void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U, 1005 ExplodedNode *Pred, 1006 ExplodedNodeSet &Dst) { 1007 // Handle ++ and -- (both pre- and post-increment). 1008 assert (U->isIncrementDecrementOp()); 1009 const Expr *Ex = U->getSubExpr()->IgnoreParens(); 1010 1011 const LocationContext *LCtx = Pred->getLocationContext(); 1012 ProgramStateRef state = Pred->getState(); 1013 SVal loc = state->getSVal(Ex, LCtx); 1014 1015 // Perform a load. 1016 ExplodedNodeSet Tmp; 1017 evalLoad(Tmp, U, Ex, Pred, state, loc); 1018 1019 ExplodedNodeSet Dst2; 1020 StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx); 1021 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) { 1022 1023 state = (*I)->getState(); 1024 assert(LCtx == (*I)->getLocationContext()); 1025 SVal V2_untested = state->getSVal(Ex, LCtx); 1026 1027 // Propagate unknown and undefined values. 1028 if (V2_untested.isUnknownOrUndef()) { 1029 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested)); 1030 continue; 1031 } 1032 DefinedSVal V2 = V2_untested.castAs<DefinedSVal>(); 1033 1034 // Handle all other values. 1035 BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub; 1036 1037 // If the UnaryOperator has non-location type, use its type to create the 1038 // constant value. If the UnaryOperator has location type, create the 1039 // constant with int type and pointer width. 1040 SVal RHS; 1041 1042 if (U->getType()->isAnyPointerType()) 1043 RHS = svalBuilder.makeArrayIndex(1); 1044 else if (U->getType()->isIntegralOrEnumerationType()) 1045 RHS = svalBuilder.makeIntVal(1, U->getType()); 1046 else 1047 RHS = UnknownVal(); 1048 1049 SVal Result = evalBinOp(state, Op, V2, RHS, U->getType()); 1050 1051 // Conjure a new symbol if necessary to recover precision. 1052 if (Result.isUnknown()){ 1053 DefinedOrUnknownSVal SymVal = 1054 svalBuilder.conjureSymbolVal(nullptr, U, LCtx, 1055 currBldrCtx->blockCount()); 1056 Result = SymVal; 1057 1058 // If the value is a location, ++/-- should always preserve 1059 // non-nullness. Check if the original value was non-null, and if so 1060 // propagate that constraint. 1061 if (Loc::isLocType(U->getType())) { 1062 DefinedOrUnknownSVal Constraint = 1063 svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType())); 1064 1065 if (!state->assume(Constraint, true)) { 1066 // It isn't feasible for the original value to be null. 1067 // Propagate this constraint. 1068 Constraint = svalBuilder.evalEQ(state, SymVal, 1069 svalBuilder.makeZeroVal(U->getType())); 1070 1071 1072 state = state->assume(Constraint, false); 1073 assert(state); 1074 } 1075 } 1076 } 1077 1078 // Since the lvalue-to-rvalue conversion is explicit in the AST, 1079 // we bind an l-value if the operator is prefix and an lvalue (in C++). 1080 if (U->isGLValue()) 1081 state = state->BindExpr(U, LCtx, loc); 1082 else 1083 state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result); 1084 1085 // Perform the store. 1086 Bldr.takeNodes(*I); 1087 ExplodedNodeSet Dst3; 1088 evalStore(Dst3, U, U, *I, state, loc, Result); 1089 Bldr.addNodes(Dst3); 1090 } 1091 Dst.insert(Dst2); 1092 } 1093