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