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