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