Bug Summary

File:tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
Warning:line 432, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SValBuilder.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/StaticAnalyzer/Core -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
1//===- SValBuilder.cpp - Basic class for all SValBuilder implementations --===//
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 SValBuilder, the base class for all (complete) SValBuilder
11// implementations.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/Stmt.h"
22#include "clang/AST/Type.h"
23#include "clang/Basic/LLVM.h"
24#include "clang/Analysis/AnalysisDeclContext.h"
25#include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
26#include "clang/StaticAnalyzer/Core/PathSensitive/BasicValueFactory.h"
27#include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
28#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
29#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
30#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
31#include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
32#include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
33#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/None.h"
36#include "llvm/ADT/Optional.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/Compiler.h"
39#include <cassert>
40#include <tuple>
41
42using namespace clang;
43using namespace ento;
44
45//===----------------------------------------------------------------------===//
46// Basic SVal creation.
47//===----------------------------------------------------------------------===//
48
49void SValBuilder::anchor() {}
50
51DefinedOrUnknownSVal SValBuilder::makeZeroVal(QualType type) {
52 if (Loc::isLocType(type))
53 return makeNull();
54
55 if (type->isIntegralOrEnumerationType())
56 return makeIntVal(0, type);
57
58 if (type->isArrayType() || type->isRecordType() || type->isVectorType() ||
59 type->isAnyComplexType())
60 return makeCompoundVal(type, BasicVals.getEmptySValList());
61
62 // FIXME: Handle floats.
63 return UnknownVal();
64}
65
66NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
67 const llvm::APSInt& rhs, QualType type) {
68 // The Environment ensures we always get a persistent APSInt in
69 // BasicValueFactory, so we don't need to get the APSInt from
70 // BasicValueFactory again.
71 assert(lhs)(static_cast <bool> (lhs) ? void (0) : __assert_fail ("lhs"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 71, __extension__ __PRETTY_FUNCTION__))
;
72 assert(!Loc::isLocType(type))(static_cast <bool> (!Loc::isLocType(type)) ? void (0) :
__assert_fail ("!Loc::isLocType(type)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 72, __extension__ __PRETTY_FUNCTION__))
;
73 return nonloc::SymbolVal(SymMgr.getSymIntExpr(lhs, op, rhs, type));
74}
75
76NonLoc SValBuilder::makeNonLoc(const llvm::APSInt& lhs,
77 BinaryOperator::Opcode op, const SymExpr *rhs,
78 QualType type) {
79 assert(rhs)(static_cast <bool> (rhs) ? void (0) : __assert_fail ("rhs"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 79, __extension__ __PRETTY_FUNCTION__))
;
80 assert(!Loc::isLocType(type))(static_cast <bool> (!Loc::isLocType(type)) ? void (0) :
__assert_fail ("!Loc::isLocType(type)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 80, __extension__ __PRETTY_FUNCTION__))
;
81 return nonloc::SymbolVal(SymMgr.getIntSymExpr(lhs, op, rhs, type));
82}
83
84NonLoc SValBuilder::makeNonLoc(const SymExpr *lhs, BinaryOperator::Opcode op,
85 const SymExpr *rhs, QualType type) {
86 assert(lhs && rhs)(static_cast <bool> (lhs && rhs) ? void (0) : __assert_fail
("lhs && rhs", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 86, __extension__ __PRETTY_FUNCTION__))
;
87 assert(!Loc::isLocType(type))(static_cast <bool> (!Loc::isLocType(type)) ? void (0) :
__assert_fail ("!Loc::isLocType(type)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 87, __extension__ __PRETTY_FUNCTION__))
;
88 return nonloc::SymbolVal(SymMgr.getSymSymExpr(lhs, op, rhs, type));
89}
90
91NonLoc SValBuilder::makeNonLoc(const SymExpr *operand,
92 QualType fromTy, QualType toTy) {
93 assert(operand)(static_cast <bool> (operand) ? void (0) : __assert_fail
("operand", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 93, __extension__ __PRETTY_FUNCTION__))
;
94 assert(!Loc::isLocType(toTy))(static_cast <bool> (!Loc::isLocType(toTy)) ? void (0) :
__assert_fail ("!Loc::isLocType(toTy)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 94, __extension__ __PRETTY_FUNCTION__))
;
95 return nonloc::SymbolVal(SymMgr.getCastSymbol(operand, fromTy, toTy));
96}
97
98SVal SValBuilder::convertToArrayIndex(SVal val) {
99 if (val.isUnknownOrUndef())
100 return val;
101
102 // Common case: we have an appropriately sized integer.
103 if (Optional<nonloc::ConcreteInt> CI = val.getAs<nonloc::ConcreteInt>()) {
104 const llvm::APSInt& I = CI->getValue();
105 if (I.getBitWidth() == ArrayIndexWidth && I.isSigned())
106 return val;
107 }
108
109 return evalCastFromNonLoc(val.castAs<NonLoc>(), ArrayIndexTy);
110}
111
112nonloc::ConcreteInt SValBuilder::makeBoolVal(const CXXBoolLiteralExpr *boolean){
113 return makeTruthVal(boolean->getValue());
114}
115
116DefinedOrUnknownSVal
117SValBuilder::getRegionValueSymbolVal(const TypedValueRegion *region) {
118 QualType T = region->getValueType();
119
120 if (T->isNullPtrType())
121 return makeZeroVal(T);
122
123 if (!SymbolManager::canSymbolicate(T))
124 return UnknownVal();
125
126 SymbolRef sym = SymMgr.getRegionValueSymbol(region);
127
128 if (Loc::isLocType(T))
129 return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
130
131 return nonloc::SymbolVal(sym);
132}
133
134DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const void *SymbolTag,
135 const Expr *Ex,
136 const LocationContext *LCtx,
137 unsigned Count) {
138 QualType T = Ex->getType();
139
140 if (T->isNullPtrType())
141 return makeZeroVal(T);
142
143 // Compute the type of the result. If the expression is not an R-value, the
144 // result should be a location.
145 QualType ExType = Ex->getType();
146 if (Ex->isGLValue())
147 T = LCtx->getAnalysisDeclContext()->getASTContext().getPointerType(ExType);
148
149 return conjureSymbolVal(SymbolTag, Ex, LCtx, T, Count);
150}
151
152DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const void *symbolTag,
153 const Expr *expr,
154 const LocationContext *LCtx,
155 QualType type,
156 unsigned count) {
157 if (type->isNullPtrType())
158 return makeZeroVal(type);
159
160 if (!SymbolManager::canSymbolicate(type))
161 return UnknownVal();
162
163 SymbolRef sym = SymMgr.conjureSymbol(expr, LCtx, type, count, symbolTag);
164
165 if (Loc::isLocType(type))
166 return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
167
168 return nonloc::SymbolVal(sym);
169}
170
171DefinedOrUnknownSVal SValBuilder::conjureSymbolVal(const Stmt *stmt,
172 const LocationContext *LCtx,
173 QualType type,
174 unsigned visitCount) {
175 if (type->isNullPtrType())
176 return makeZeroVal(type);
177
178 if (!SymbolManager::canSymbolicate(type))
179 return UnknownVal();
180
181 SymbolRef sym = SymMgr.conjureSymbol(stmt, LCtx, type, visitCount);
182
183 if (Loc::isLocType(type))
184 return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
185
186 return nonloc::SymbolVal(sym);
187}
188
189DefinedOrUnknownSVal
190SValBuilder::getConjuredHeapSymbolVal(const Expr *E,
191 const LocationContext *LCtx,
192 unsigned VisitCount) {
193 QualType T = E->getType();
194 assert(Loc::isLocType(T))(static_cast <bool> (Loc::isLocType(T)) ? void (0) : __assert_fail
("Loc::isLocType(T)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 194, __extension__ __PRETTY_FUNCTION__))
;
195 assert(SymbolManager::canSymbolicate(T))(static_cast <bool> (SymbolManager::canSymbolicate(T)) ?
void (0) : __assert_fail ("SymbolManager::canSymbolicate(T)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 195, __extension__ __PRETTY_FUNCTION__))
;
196 if (T->isNullPtrType())
197 return makeZeroVal(T);
198
199 SymbolRef sym = SymMgr.conjureSymbol(E, LCtx, T, VisitCount);
200 return loc::MemRegionVal(MemMgr.getSymbolicHeapRegion(sym));
201}
202
203DefinedSVal SValBuilder::getMetadataSymbolVal(const void *symbolTag,
204 const MemRegion *region,
205 const Expr *expr, QualType type,
206 const LocationContext *LCtx,
207 unsigned count) {
208 assert(SymbolManager::canSymbolicate(type) && "Invalid metadata symbol type")(static_cast <bool> (SymbolManager::canSymbolicate(type
) && "Invalid metadata symbol type") ? void (0) : __assert_fail
("SymbolManager::canSymbolicate(type) && \"Invalid metadata symbol type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 208, __extension__ __PRETTY_FUNCTION__))
;
209
210 SymbolRef sym =
211 SymMgr.getMetadataSymbol(region, expr, type, LCtx, count, symbolTag);
212
213 if (Loc::isLocType(type))
214 return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
215
216 return nonloc::SymbolVal(sym);
217}
218
219DefinedOrUnknownSVal
220SValBuilder::getDerivedRegionValueSymbolVal(SymbolRef parentSymbol,
221 const TypedValueRegion *region) {
222 QualType T = region->getValueType();
223
224 if (T->isNullPtrType())
225 return makeZeroVal(T);
226
227 if (!SymbolManager::canSymbolicate(T))
228 return UnknownVal();
229
230 SymbolRef sym = SymMgr.getDerivedSymbol(parentSymbol, region);
231
232 if (Loc::isLocType(T))
233 return loc::MemRegionVal(MemMgr.getSymbolicRegion(sym));
234
235 return nonloc::SymbolVal(sym);
236}
237
238DefinedSVal SValBuilder::getMemberPointer(const DeclaratorDecl *DD) {
239 assert(!DD || isa<CXXMethodDecl>(DD) || isa<FieldDecl>(DD))(static_cast <bool> (!DD || isa<CXXMethodDecl>(DD
) || isa<FieldDecl>(DD)) ? void (0) : __assert_fail ("!DD || isa<CXXMethodDecl>(DD) || isa<FieldDecl>(DD)"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 239, __extension__ __PRETTY_FUNCTION__))
;
240
241 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DD)) {
242 // Sema treats pointers to static member functions as have function pointer
243 // type, so return a function pointer for the method.
244 // We don't need to play a similar trick for static member fields
245 // because these are represented as plain VarDecls and not FieldDecls
246 // in the AST.
247 if (MD->isStatic())
248 return getFunctionPointer(MD);
249 }
250
251 return nonloc::PointerToMember(DD);
252}
253
254DefinedSVal SValBuilder::getFunctionPointer(const FunctionDecl *func) {
255 return loc::MemRegionVal(MemMgr.getFunctionCodeRegion(func));
256}
257
258DefinedSVal SValBuilder::getBlockPointer(const BlockDecl *block,
259 CanQualType locTy,
260 const LocationContext *locContext,
261 unsigned blockCount) {
262 const BlockCodeRegion *BC =
263 MemMgr.getBlockCodeRegion(block, locTy, locContext->getAnalysisDeclContext());
264 const BlockDataRegion *BD = MemMgr.getBlockDataRegion(BC, locContext,
265 blockCount);
266 return loc::MemRegionVal(BD);
267}
268
269/// Return a memory region for the 'this' object reference.
270loc::MemRegionVal SValBuilder::getCXXThis(const CXXMethodDecl *D,
271 const StackFrameContext *SFC) {
272 return loc::MemRegionVal(getRegionManager().
273 getCXXThisRegion(D->getThisType(getContext()), SFC));
274}
275
276/// Return a memory region for the 'this' object reference.
277loc::MemRegionVal SValBuilder::getCXXThis(const CXXRecordDecl *D,
278 const StackFrameContext *SFC) {
279 const Type *T = D->getTypeForDecl();
280 QualType PT = getContext().getPointerType(QualType(T, 0));
281 return loc::MemRegionVal(getRegionManager().getCXXThisRegion(PT, SFC));
282}
283
284Optional<SVal> SValBuilder::getConstantVal(const Expr *E) {
285 E = E->IgnoreParens();
286
287 switch (E->getStmtClass()) {
288 // Handle expressions that we treat differently from the AST's constant
289 // evaluator.
290 case Stmt::AddrLabelExprClass:
291 return makeLoc(cast<AddrLabelExpr>(E));
292
293 case Stmt::CXXScalarValueInitExprClass:
294 case Stmt::ImplicitValueInitExprClass:
295 return makeZeroVal(E->getType());
296
297 case Stmt::ObjCStringLiteralClass: {
298 const auto *SL = cast<ObjCStringLiteral>(E);
299 return makeLoc(getRegionManager().getObjCStringRegion(SL));
300 }
301
302 case Stmt::StringLiteralClass: {
303 const auto *SL = cast<StringLiteral>(E);
304 return makeLoc(getRegionManager().getStringRegion(SL));
305 }
306
307 // Fast-path some expressions to avoid the overhead of going through the AST's
308 // constant evaluator
309 case Stmt::CharacterLiteralClass: {
310 const auto *C = cast<CharacterLiteral>(E);
311 return makeIntVal(C->getValue(), C->getType());
312 }
313
314 case Stmt::CXXBoolLiteralExprClass:
315 return makeBoolVal(cast<CXXBoolLiteralExpr>(E));
316
317 case Stmt::TypeTraitExprClass: {
318 const auto *TE = cast<TypeTraitExpr>(E);
319 return makeTruthVal(TE->getValue(), TE->getType());
320 }
321
322 case Stmt::IntegerLiteralClass:
323 return makeIntVal(cast<IntegerLiteral>(E));
324
325 case Stmt::ObjCBoolLiteralExprClass:
326 return makeBoolVal(cast<ObjCBoolLiteralExpr>(E));
327
328 case Stmt::CXXNullPtrLiteralExprClass:
329 return makeNull();
330
331 case Stmt::ImplicitCastExprClass: {
332 const auto *CE = cast<CastExpr>(E);
333 switch (CE->getCastKind()) {
334 default:
335 break;
336 case CK_ArrayToPointerDecay:
337 case CK_BitCast: {
338 const Expr *SE = CE->getSubExpr();
339 Optional<SVal> Val = getConstantVal(SE);
340 if (!Val)
341 return None;
342 return evalCast(*Val, CE->getType(), SE->getType());
343 }
344 }
345 // FALLTHROUGH
346 LLVM_FALLTHROUGH[[clang::fallthrough]];
347 }
348
349 // If we don't have a special case, fall back to the AST's constant evaluator.
350 default: {
351 // Don't try to come up with a value for materialized temporaries.
352 if (E->isGLValue())
353 return None;
354
355 ASTContext &Ctx = getContext();
356 llvm::APSInt Result;
357 if (E->EvaluateAsInt(Result, Ctx))
358 return makeIntVal(Result);
359
360 if (Loc::isLocType(E->getType()))
361 if (E->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
362 return makeNull();
363
364 return None;
365 }
366 }
367}
368
369SVal SValBuilder::makeSymExprValNN(ProgramStateRef State,
370 BinaryOperator::Opcode Op,
371 NonLoc LHS, NonLoc RHS,
372 QualType ResultTy) {
373 if (!State->isTainted(RHS) && !State->isTainted(LHS))
374 return UnknownVal();
375
376 const SymExpr *symLHS = LHS.getAsSymExpr();
377 const SymExpr *symRHS = RHS.getAsSymExpr();
378 // TODO: When the Max Complexity is reached, we should conjure a symbol
379 // instead of generating an Unknown value and propagate the taint info to it.
380 const unsigned MaxComp = 10000; // 100000 28X
381
382 if (symLHS && symRHS &&
383 (symLHS->computeComplexity() + symRHS->computeComplexity()) < MaxComp)
384 return makeNonLoc(symLHS, Op, symRHS, ResultTy);
385
386 if (symLHS && symLHS->computeComplexity() < MaxComp)
387 if (Optional<nonloc::ConcreteInt> rInt = RHS.getAs<nonloc::ConcreteInt>())
388 return makeNonLoc(symLHS, Op, rInt->getValue(), ResultTy);
389
390 if (symRHS && symRHS->computeComplexity() < MaxComp)
391 if (Optional<nonloc::ConcreteInt> lInt = LHS.getAs<nonloc::ConcreteInt>())
392 return makeNonLoc(lInt->getValue(), Op, symRHS, ResultTy);
393
394 return UnknownVal();
395}
396
397SVal SValBuilder::evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op,
398 SVal lhs, SVal rhs, QualType type) {
399 if (lhs.isUndef() || rhs.isUndef())
400 return UndefinedVal();
401
402 if (lhs.isUnknown() || rhs.isUnknown())
403 return UnknownVal();
404
405 if (lhs.getAs<nonloc::LazyCompoundVal>() ||
406 rhs.getAs<nonloc::LazyCompoundVal>()) {
407 return UnknownVal();
408 }
409
410 if (Optional<Loc> LV = lhs.getAs<Loc>()) {
411 if (Optional<Loc> RV = rhs.getAs<Loc>())
412 return evalBinOpLL(state, op, *LV, *RV, type);
413
414 return evalBinOpLN(state, op, *LV, rhs.castAs<NonLoc>(), type);
415 }
416
417 if (Optional<Loc> RV = rhs.getAs<Loc>()) {
418 // Support pointer arithmetic where the addend is on the left
419 // and the pointer on the right.
420 assert(op == BO_Add)(static_cast <bool> (op == BO_Add) ? void (0) : __assert_fail
("op == BO_Add", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 420, __extension__ __PRETTY_FUNCTION__))
;
421
422 // Commute the operands.
423 return evalBinOpLN(state, op, *RV, lhs.castAs<NonLoc>(), type);
424 }
425
426 return evalBinOpNN(state, op, lhs.castAs<NonLoc>(), rhs.castAs<NonLoc>(),
427 type);
428}
429
430ConditionTruthVal SValBuilder::areEqual(ProgramStateRef state, SVal lhs,
431 SVal rhs) {
432 return state->isNonNull(evalEQ(state, lhs, rhs));
1
Calling 'IntrusiveRefCntPtr::operator->'
2
Returning from 'IntrusiveRefCntPtr::operator->'
3
Called C++ object pointer is null
433}
434
435SVal SValBuilder::evalEQ(ProgramStateRef state, SVal lhs, SVal rhs) {
436 return evalBinOp(state, BO_EQ, lhs, rhs, getConditionType());
437}
438
439DefinedOrUnknownSVal SValBuilder::evalEQ(ProgramStateRef state,
440 DefinedOrUnknownSVal lhs,
441 DefinedOrUnknownSVal rhs) {
442 return evalEQ(state, static_cast<SVal>(lhs), static_cast<SVal>(rhs))
443 .castAs<DefinedOrUnknownSVal>();
444}
445
446/// Recursively check if the pointer types are equal modulo const, volatile,
447/// and restrict qualifiers. Also, assume that all types are similar to 'void'.
448/// Assumes the input types are canonical.
449static bool shouldBeModeledWithNoOp(ASTContext &Context, QualType ToTy,
450 QualType FromTy) {
451 while (Context.UnwrapSimilarPointerTypes(ToTy, FromTy)) {
452 Qualifiers Quals1, Quals2;
453 ToTy = Context.getUnqualifiedArrayType(ToTy, Quals1);
454 FromTy = Context.getUnqualifiedArrayType(FromTy, Quals2);
455
456 // Make sure that non-cvr-qualifiers the other qualifiers (e.g., address
457 // spaces) are identical.
458 Quals1.removeCVRQualifiers();
459 Quals2.removeCVRQualifiers();
460 if (Quals1 != Quals2)
461 return false;
462 }
463
464 // If we are casting to void, the 'From' value can be used to represent the
465 // 'To' value.
466 if (ToTy->isVoidType())
467 return true;
468
469 if (ToTy != FromTy)
470 return false;
471
472 return true;
473}
474
475// Handles casts of type CK_IntegralCast.
476// At the moment, this function will redirect to evalCast, except when the range
477// of the original value is known to be greater than the max of the target type.
478SVal SValBuilder::evalIntegralCast(ProgramStateRef state, SVal val,
479 QualType castTy, QualType originalTy) {
480 // No truncations if target type is big enough.
481 if (getContext().getTypeSize(castTy) >= getContext().getTypeSize(originalTy))
482 return evalCast(val, castTy, originalTy);
483
484 const SymExpr *se = val.getAsSymbolicExpression();
485 if (!se) // Let evalCast handle non symbolic expressions.
486 return evalCast(val, castTy, originalTy);
487
488 // Find the maximum value of the target type.
489 APSIntType ToType(getContext().getTypeSize(castTy),
490 castTy->isUnsignedIntegerType());
491 llvm::APSInt ToTypeMax = ToType.getMaxValue();
492 NonLoc ToTypeMaxVal =
493 makeIntVal(ToTypeMax.isUnsigned() ? ToTypeMax.getZExtValue()
494 : ToTypeMax.getSExtValue(),
495 castTy)
496 .castAs<NonLoc>();
497 // Check the range of the symbol being casted against the maximum value of the
498 // target type.
499 NonLoc FromVal = val.castAs<NonLoc>();
500 QualType CmpTy = getConditionType();
501 NonLoc CompVal =
502 evalBinOpNN(state, BO_LE, FromVal, ToTypeMaxVal, CmpTy).castAs<NonLoc>();
503 ProgramStateRef IsNotTruncated, IsTruncated;
504 std::tie(IsNotTruncated, IsTruncated) = state->assume(CompVal);
505 if (!IsNotTruncated && IsTruncated) {
506 // Symbol is truncated so we evaluate it as a cast.
507 NonLoc CastVal = makeNonLoc(se, originalTy, castTy);
508 return CastVal;
509 }
510 return evalCast(val, castTy, originalTy);
511}
512
513// FIXME: should rewrite according to the cast kind.
514SVal SValBuilder::evalCast(SVal val, QualType castTy, QualType originalTy) {
515 castTy = Context.getCanonicalType(castTy);
516 originalTy = Context.getCanonicalType(originalTy);
517 if (val.isUnknownOrUndef() || castTy == originalTy)
518 return val;
519
520 if (castTy->isBooleanType()) {
521 if (val.isUnknownOrUndef())
522 return val;
523 if (val.isConstant())
524 return makeTruthVal(!val.isZeroConstant(), castTy);
525 if (!Loc::isLocType(originalTy) &&
526 !originalTy->isIntegralOrEnumerationType() &&
527 !originalTy->isMemberPointerType())
528 return UnknownVal();
529 if (SymbolRef Sym = val.getAsSymbol(true)) {
530 BasicValueFactory &BVF = getBasicValueFactory();
531 // FIXME: If we had a state here, we could see if the symbol is known to
532 // be zero, but we don't.
533 return makeNonLoc(Sym, BO_NE, BVF.getValue(0, Sym->getType()), castTy);
534 }
535 // Loc values are not always true, they could be weakly linked functions.
536 if (Optional<Loc> L = val.getAs<Loc>())
537 return evalCastFromLoc(*L, castTy);
538
539 Loc L = val.castAs<nonloc::LocAsInteger>().getLoc();
540 return evalCastFromLoc(L, castTy);
541 }
542
543 // For const casts, casts to void, just propagate the value.
544 if (!castTy->isVariableArrayType() && !originalTy->isVariableArrayType())
545 if (shouldBeModeledWithNoOp(Context, Context.getPointerType(castTy),
546 Context.getPointerType(originalTy)))
547 return val;
548
549 // Check for casts from pointers to integers.
550 if (castTy->isIntegralOrEnumerationType() && Loc::isLocType(originalTy))
551 return evalCastFromLoc(val.castAs<Loc>(), castTy);
552
553 // Check for casts from integers to pointers.
554 if (Loc::isLocType(castTy) && originalTy->isIntegralOrEnumerationType()) {
555 if (Optional<nonloc::LocAsInteger> LV = val.getAs<nonloc::LocAsInteger>()) {
556 if (const MemRegion *R = LV->getLoc().getAsRegion()) {
557 StoreManager &storeMgr = StateMgr.getStoreManager();
558 R = storeMgr.castRegion(R, castTy);
559 return R ? SVal(loc::MemRegionVal(R)) : UnknownVal();
560 }
561 return LV->getLoc();
562 }
563 return dispatchCast(val, castTy);
564 }
565
566 // Just pass through function and block pointers.
567 if (originalTy->isBlockPointerType() || originalTy->isFunctionPointerType()) {
568 assert(Loc::isLocType(castTy))(static_cast <bool> (Loc::isLocType(castTy)) ? void (0)
: __assert_fail ("Loc::isLocType(castTy)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 568, __extension__ __PRETTY_FUNCTION__))
;
569 return val;
570 }
571
572 // Check for casts from array type to another type.
573 if (const auto *arrayT =
574 dyn_cast<ArrayType>(originalTy.getCanonicalType())) {
575 // We will always decay to a pointer.
576 QualType elemTy = arrayT->getElementType();
577 val = StateMgr.ArrayToPointer(val.castAs<Loc>(), elemTy);
578
579 // Are we casting from an array to a pointer? If so just pass on
580 // the decayed value.
581 if (castTy->isPointerType() || castTy->isReferenceType())
582 return val;
583
584 // Are we casting from an array to an integer? If so, cast the decayed
585 // pointer value to an integer.
586 assert(castTy->isIntegralOrEnumerationType())(static_cast <bool> (castTy->isIntegralOrEnumerationType
()) ? void (0) : __assert_fail ("castTy->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 586, __extension__ __PRETTY_FUNCTION__))
;
587
588 // FIXME: Keep these here for now in case we decide soon that we
589 // need the original decayed type.
590 // QualType elemTy = cast<ArrayType>(originalTy)->getElementType();
591 // QualType pointerTy = C.getPointerType(elemTy);
592 return evalCastFromLoc(val.castAs<Loc>(), castTy);
593 }
594
595 // Check for casts from a region to a specific type.
596 if (const MemRegion *R = val.getAsRegion()) {
597 // Handle other casts of locations to integers.
598 if (castTy->isIntegralOrEnumerationType())
599 return evalCastFromLoc(loc::MemRegionVal(R), castTy);
600
601 // FIXME: We should handle the case where we strip off view layers to get
602 // to a desugared type.
603 if (!Loc::isLocType(castTy)) {
604 // FIXME: There can be gross cases where one casts the result of a function
605 // (that returns a pointer) to some other value that happens to fit
606 // within that pointer value. We currently have no good way to
607 // model such operations. When this happens, the underlying operation
608 // is that the caller is reasoning about bits. Conceptually we are
609 // layering a "view" of a location on top of those bits. Perhaps
610 // we need to be more lazy about mutual possible views, even on an
611 // SVal? This may be necessary for bit-level reasoning as well.
612 return UnknownVal();
613 }
614
615 // We get a symbolic function pointer for a dereference of a function
616 // pointer, but it is of function type. Example:
617
618 // struct FPRec {
619 // void (*my_func)(int * x);
620 // };
621 //
622 // int bar(int x);
623 //
624 // int f1_a(struct FPRec* foo) {
625 // int x;
626 // (*foo->my_func)(&x);
627 // return bar(x)+1; // no-warning
628 // }
629
630 assert(Loc::isLocType(originalTy) || originalTy->isFunctionType() ||(static_cast <bool> (Loc::isLocType(originalTy) || originalTy
->isFunctionType() || originalTy->isBlockPointerType() ||
castTy->isReferenceType()) ? void (0) : __assert_fail ("Loc::isLocType(originalTy) || originalTy->isFunctionType() || originalTy->isBlockPointerType() || castTy->isReferenceType()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 631, __extension__ __PRETTY_FUNCTION__))
631 originalTy->isBlockPointerType() || castTy->isReferenceType())(static_cast <bool> (Loc::isLocType(originalTy) || originalTy
->isFunctionType() || originalTy->isBlockPointerType() ||
castTy->isReferenceType()) ? void (0) : __assert_fail ("Loc::isLocType(originalTy) || originalTy->isFunctionType() || originalTy->isBlockPointerType() || castTy->isReferenceType()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp"
, 631, __extension__ __PRETTY_FUNCTION__))
;
632
633 StoreManager &storeMgr = StateMgr.getStoreManager();
634
635 // Delegate to store manager to get the result of casting a region to a
636 // different type. If the MemRegion* returned is NULL, this expression
637 // Evaluates to UnknownVal.
638 R = storeMgr.castRegion(R, castTy);
639 return R ? SVal(loc::MemRegionVal(R)) : UnknownVal();
640 }
641
642 return dispatchCast(val, castTy);
643}