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