Bug Summary

File:tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
Warning:line 440, 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-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-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/StaticAnalyzer/Core -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.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-8~svn345461/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-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/StaticAnalyzer/Core/SValBuilder.cpp -faddrsig

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

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/IntrusiveRefCntPtr.h

1//==- llvm/ADT/IntrusiveRefCntPtr.h - Smart Refcounting Pointer --*- 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 the RefCountedBase, ThreadSafeRefCountedBase, and
11// IntrusiveRefCntPtr classes.
12//
13// IntrusiveRefCntPtr is a smart pointer to an object which maintains a
14// reference count. (ThreadSafe)RefCountedBase is a mixin class that adds a
15// refcount member variable and methods for updating the refcount. An object
16// that inherits from (ThreadSafe)RefCountedBase deletes itself when its
17// refcount hits zero.
18//
19// For example:
20//
21// class MyClass : public RefCountedBase<MyClass> {};
22//
23// void foo() {
24// // Constructing an IntrusiveRefCntPtr increases the pointee's refcount by
25// // 1 (from 0 in this case).
26// IntrusiveRefCntPtr<MyClass> Ptr1(new MyClass());
27//
28// // Copying an IntrusiveRefCntPtr increases the pointee's refcount by 1.
29// IntrusiveRefCntPtr<MyClass> Ptr2(Ptr1);
30//
31// // Constructing an IntrusiveRefCntPtr has no effect on the object's
32// // refcount. After a move, the moved-from pointer is null.
33// IntrusiveRefCntPtr<MyClass> Ptr3(std::move(Ptr1));
34// assert(Ptr1 == nullptr);
35//
36// // Clearing an IntrusiveRefCntPtr decreases the pointee's refcount by 1.
37// Ptr2.reset();
38//
39// // The object deletes itself when we return from the function, because
40// // Ptr3's destructor decrements its refcount to 0.
41// }
42//
43// You can use IntrusiveRefCntPtr with isa<T>(), dyn_cast<T>(), etc.:
44//
45// IntrusiveRefCntPtr<MyClass> Ptr(new MyClass());
46// OtherClass *Other = dyn_cast<OtherClass>(Ptr); // Ptr.get() not required
47//
48// IntrusiveRefCntPtr works with any class that
49//
50// - inherits from (ThreadSafe)RefCountedBase,
51// - has Retain() and Release() methods, or
52// - specializes IntrusiveRefCntPtrInfo.
53//
54//===----------------------------------------------------------------------===//
55
56#ifndef LLVM_ADT_INTRUSIVEREFCNTPTR_H
57#define LLVM_ADT_INTRUSIVEREFCNTPTR_H
58
59#include <atomic>
60#include <cassert>
61#include <cstddef>
62
63namespace llvm {
64
65/// A CRTP mixin class that adds reference counting to a type.
66///
67/// The lifetime of an object which inherits from RefCountedBase is managed by
68/// calls to Release() and Retain(), which increment and decrement the object's
69/// refcount, respectively. When a Release() call decrements the refcount to 0,
70/// the object deletes itself.
71template <class Derived> class RefCountedBase {
72 mutable unsigned RefCount = 0;
73
74public:
75 RefCountedBase() = default;
76 RefCountedBase(const RefCountedBase &) {}
77
78 void Retain() const { ++RefCount; }
79
80 void Release() const {
81 assert(RefCount > 0 && "Reference count is already zero.")((RefCount > 0 && "Reference count is already zero."
) ? static_cast<void> (0) : __assert_fail ("RefCount > 0 && \"Reference count is already zero.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/IntrusiveRefCntPtr.h"
, 81, __PRETTY_FUNCTION__))
;
82 if (--RefCount == 0)
83 delete static_cast<const Derived *>(this);
84 }
85};
86
87/// A thread-safe version of \c RefCountedBase.
88template <class Derived> class ThreadSafeRefCountedBase {
89 mutable std::atomic<int> RefCount;
90
91protected:
92 ThreadSafeRefCountedBase() : RefCount(0) {}
93
94public:
95 void Retain() const { RefCount.fetch_add(1, std::memory_order_relaxed); }
96
97 void Release() const {
98 int NewRefCount = RefCount.fetch_sub(1, std::memory_order_acq_rel) - 1;
99 assert(NewRefCount >= 0 && "Reference count was already zero.")((NewRefCount >= 0 && "Reference count was already zero."
) ? static_cast<void> (0) : __assert_fail ("NewRefCount >= 0 && \"Reference count was already zero.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/IntrusiveRefCntPtr.h"
, 99, __PRETTY_FUNCTION__))
;
100 if (NewRefCount == 0)
101 delete static_cast<const Derived *>(this);
102 }
103};
104
105/// Class you can specialize to provide custom retain/release functionality for
106/// a type.
107///
108/// Usually specializing this class is not necessary, as IntrusiveRefCntPtr
109/// works with any type which defines Retain() and Release() functions -- you
110/// can define those functions yourself if RefCountedBase doesn't work for you.
111///
112/// One case when you might want to specialize this type is if you have
113/// - Foo.h defines type Foo and includes Bar.h, and
114/// - Bar.h uses IntrusiveRefCntPtr<Foo> in inline functions.
115///
116/// Because Foo.h includes Bar.h, Bar.h can't include Foo.h in order to pull in
117/// the declaration of Foo. Without the declaration of Foo, normally Bar.h
118/// wouldn't be able to use IntrusiveRefCntPtr<Foo>, which wants to call
119/// T::Retain and T::Release.
120///
121/// To resolve this, Bar.h could include a third header, FooFwd.h, which
122/// forward-declares Foo and specializes IntrusiveRefCntPtrInfo<Foo>. Then
123/// Bar.h could use IntrusiveRefCntPtr<Foo>, although it still couldn't call any
124/// functions on Foo itself, because Foo would be an incomplete type.
125template <typename T> struct IntrusiveRefCntPtrInfo {
126 static void retain(T *obj) { obj->Retain(); }
127 static void release(T *obj) { obj->Release(); }
128};
129
130/// A smart pointer to a reference-counted object that inherits from
131/// RefCountedBase or ThreadSafeRefCountedBase.
132///
133/// This class increments its pointee's reference count when it is created, and
134/// decrements its refcount when it's destroyed (or is changed to point to a
135/// different object).
136template <typename T> class IntrusiveRefCntPtr {
137 T *Obj = nullptr;
138
139public:
140 using element_type = T;
141
142 explicit IntrusiveRefCntPtr() = default;
143 IntrusiveRefCntPtr(T *obj) : Obj(obj) { retain(); }
144 IntrusiveRefCntPtr(const IntrusiveRefCntPtr &S) : Obj(S.Obj) { retain(); }
145 IntrusiveRefCntPtr(IntrusiveRefCntPtr &&S) : Obj(S.Obj) { S.Obj = nullptr; }
146
147 template <class X>
148 IntrusiveRefCntPtr(IntrusiveRefCntPtr<X> &&S) : Obj(S.get()) {
149 S.Obj = nullptr;
150 }
151
152 template <class X>
153 IntrusiveRefCntPtr(const IntrusiveRefCntPtr<X> &S) : Obj(S.get()) {
154 retain();
155 }
156
157 ~IntrusiveRefCntPtr() { release(); }
158
159 IntrusiveRefCntPtr &operator=(IntrusiveRefCntPtr S) {
160 swap(S);
161 return *this;
162 }
163
164 T &operator*() const { return *Obj; }
165 T *operator->() const { return Obj; }
2
Returning pointer
3
Assigning value
166 T *get() const { return Obj; }
167 explicit operator bool() const { return Obj; }
168
169 void swap(IntrusiveRefCntPtr &other) {
170 T *tmp = other.Obj;
171 other.Obj = Obj;
172 Obj = tmp;
173 }
174
175 void reset() {
176 release();
177 Obj = nullptr;
178 }
179
180 void resetWithoutRelease() { Obj = nullptr; }
181
182private:
183 void retain() {
184 if (Obj)
185 IntrusiveRefCntPtrInfo<T>::retain(Obj);
186 }
187
188 void release() {
189 if (Obj)
190 IntrusiveRefCntPtrInfo<T>::release(Obj);
191 }
192
193 template <typename X> friend class IntrusiveRefCntPtr;
194};
195
196template <class T, class U>
197inline bool operator==(const IntrusiveRefCntPtr<T> &A,
198 const IntrusiveRefCntPtr<U> &B) {
199 return A.get() == B.get();
200}
201
202template <class T, class U>
203inline bool operator!=(const IntrusiveRefCntPtr<T> &A,
204 const IntrusiveRefCntPtr<U> &B) {
205 return A.get() != B.get();
206}
207
208template <class T, class U>
209inline bool operator==(const IntrusiveRefCntPtr<T> &A, U *B) {
210 return A.get() == B;
211}
212
213template <class T, class U>
214inline bool operator!=(const IntrusiveRefCntPtr<T> &A, U *B) {
215 return A.get() != B;
216}
217
218template <class T, class U>
219inline bool operator==(T *A, const IntrusiveRefCntPtr<U> &B) {
220 return A == B.get();
221}
222
223template <class T, class U>
224inline bool operator!=(T *A, const IntrusiveRefCntPtr<U> &B) {
225 return A != B.get();
226}
227
228template <class T>
229bool operator==(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) {
230 return !B;
231}
232
233template <class T>
234bool operator==(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
235 return B == A;
236}
237
238template <class T>
239bool operator!=(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) {
240 return !(A == B);
241}
242
243template <class T>
244bool operator!=(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
245 return !(A == B);
246}
247
248// Make IntrusiveRefCntPtr work with dyn_cast, isa, and the other idioms from
249// Casting.h.
250template <typename From> struct simplify_type;
251
252template <class T> struct simplify_type<IntrusiveRefCntPtr<T>> {
253 using SimpleType = T *;
254
255 static SimpleType getSimplifiedValue(IntrusiveRefCntPtr<T> &Val) {
256 return Val.get();
257 }
258};
259
260template <class T> struct simplify_type<const IntrusiveRefCntPtr<T>> {
261 using SimpleType = /*const*/ T *;
262
263 static SimpleType getSimplifiedValue(const IntrusiveRefCntPtr<T> &Val) {
264 return Val.get();
265 }
266};
267
268} // end namespace llvm
269
270#endif // LLVM_ADT_INTRUSIVEREFCNTPTR_H