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