blob: 2ea6e0643b69dc4198972081408973b911789397 [file] [log] [blame]
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001//= CStringChecker.h - Checks calls to C string functions ----------*- 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 defines CStringChecker, which is an assortment of checks on calls
11// to functions in <string.h>.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidisa0decc92011-02-15 21:25:03 +000015#include "ClangSACheckers.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000016#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000017#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000018#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000019#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"
Jordy Roseccbf7ee2010-07-06 23:11:01 +000021#include "llvm/ADT/StringSwitch.h"
22
23using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000024using namespace ento;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000025
26namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000027class CStringChecker : public Checker< eval::Call,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000028 check::PreStmt<DeclStmt>,
29 check::LiveSymbols,
30 check::DeadSymbols,
31 check::RegionChanges
32 > {
33 mutable llvm::OwningPtr<BugType> BT_Null, BT_Bounds, BT_BoundsWrite,
Jordy Rosed5af0e12011-06-15 05:52:56 +000034 BT_Overlap, BT_NotCString,
35 BT_AdditionOverflow;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000036public:
Jordy Roseccbf7ee2010-07-06 23:11:01 +000037 static void *getTag() { static int tag; return &tag; }
38
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000039 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
40 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
41 void checkLiveSymbols(const GRState *state, SymbolReaper &SR) const;
42 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
43 bool wantsRegionChangeUpdate(const GRState *state) const;
Jordy Rosea5261542010-08-14 21:02:52 +000044
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000045 const GRState *checkRegionChanges(const GRState *state,
Ted Kremenek35bdbf42011-05-02 19:42:42 +000046 const StoreManager::InvalidatedSymbols *,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000047 const MemRegion * const *Begin,
48 const MemRegion * const *End) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000049
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000050 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
51 const CallExpr *) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000052
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000053 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000054 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000055 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
56 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000057 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
58 const GRState *state,
Jordy Rosed325ffb2010-07-08 23:57:29 +000059 const Expr *Size, const Expr *Source, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +000060 bool Restricted = false,
61 bool IsMempcpy = false) const;
Jordy Rosed325ffb2010-07-08 23:57:29 +000062
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000063 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000064
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000065 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
66 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenekbe4242c2011-02-22 04:55:05 +000067 void evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000068 bool IsStrnlen = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +000069
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000070 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
71 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
72 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek0ef473f2011-02-22 04:58:34 +000073 void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool returnEnd,
Lenny Maiorani067bbd02011-04-09 15:12:58 +000074 bool isBounded, bool isAppending) const;
75
76 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
77 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Jordy Rosee64f3112010-08-16 07:51:42 +000078
Lenny Maiorani318dd922011-04-12 17:08:43 +000079 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani357f6ee2011-04-25 22:21:00 +000080 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranibd1d16a2011-04-28 15:09:11 +000081 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani454fd2d2011-05-02 19:05:49 +000082 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani357f6ee2011-04-25 22:21:00 +000083 void evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +000084 bool isBounded = false, bool ignoreCase = false) const;
Lenny Maiorani318dd922011-04-12 17:08:43 +000085
Jordy Roseccbf7ee2010-07-06 23:11:01 +000086 // Utility methods
Jordy Rosed325ffb2010-07-08 23:57:29 +000087 std::pair<const GRState*, const GRState*>
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000088 static assumeZero(CheckerContext &C,
89 const GRState *state, SVal V, QualType Ty);
Jordy Rosed325ffb2010-07-08 23:57:29 +000090
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000091 static const GRState *setCStringLength(const GRState *state,
92 const MemRegion *MR, SVal strLength);
93 static SVal getCStringLengthForRegion(CheckerContext &C,
94 const GRState *&state,
Jordy Rosed5af0e12011-06-15 05:52:56 +000095 const Expr *Ex, const MemRegion *MR,
96 bool hypothetical);
Ted Kremenekc8413fd2010-12-02 07:49:45 +000097 SVal getCStringLength(CheckerContext &C, const GRState *&state,
Jordy Rosed5af0e12011-06-15 05:52:56 +000098 const Expr *Ex, SVal Buf,
99 bool hypothetical = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000100
Lenny Maiorani318dd922011-04-12 17:08:43 +0000101 const StringLiteral *getCStringLiteral(CheckerContext &C,
102 const GRState *&state,
103 const Expr *expr,
104 SVal val) const;
105
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000106 static const GRState *InvalidateBuffer(CheckerContext &C,
107 const GRState *state,
108 const Expr *Ex, SVal V);
Jordy Rosee64f3112010-08-16 07:51:42 +0000109
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000110 static bool SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
111 const MemRegion *MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000112
113 // Re-usable checks
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000114 const GRState *checkNonNull(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000115 const Expr *S, SVal l) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000116 const GRState *CheckLocation(CheckerContext &C, const GRState *state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000117 const Expr *S, SVal l,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000118 bool IsDestination = false) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000119 const GRState *CheckBufferAccess(CheckerContext &C, const GRState *state,
120 const Expr *Size,
121 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000122 const Expr *SecondBuf = NULL,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000123 bool FirstIsDestination = false) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000124 const GRState *CheckOverlap(CheckerContext &C, const GRState *state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000125 const Expr *Size, const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000126 const Expr *Second) const;
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000127 void emitOverlapBug(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000128 const Stmt *First, const Stmt *Second) const;
Jordy Rosed5af0e12011-06-15 05:52:56 +0000129 const GRState *checkAdditionOverflow(CheckerContext &C, const GRState *state,
130 NonLoc left, NonLoc right) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000131};
Jordy Rosea5261542010-08-14 21:02:52 +0000132
133class CStringLength {
134public:
135 typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
136};
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000137} //end anonymous namespace
138
Jordy Rosea5261542010-08-14 21:02:52 +0000139namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000140namespace ento {
Jordy Rosea5261542010-08-14 21:02:52 +0000141 template <>
142 struct GRStateTrait<CStringLength>
143 : public GRStatePartialTrait<CStringLength::EntryMap> {
144 static void *GDMIndex() { return CStringChecker::getTag(); }
145 };
146}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000147}
Jordy Rosea5261542010-08-14 21:02:52 +0000148
Jordy Rosed325ffb2010-07-08 23:57:29 +0000149//===----------------------------------------------------------------------===//
150// Individual checks and utility methods.
151//===----------------------------------------------------------------------===//
152
153std::pair<const GRState*, const GRState*>
Ted Kremenek28f47b92010-12-01 22:16:56 +0000154CStringChecker::assumeZero(CheckerContext &C, const GRState *state, SVal V,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000155 QualType Ty) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000156 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
157 if (!val)
Jordy Rosed325ffb2010-07-08 23:57:29 +0000158 return std::pair<const GRState*, const GRState *>(state, state);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000159
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000160 SValBuilder &svalBuilder = C.getSValBuilder();
161 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
162 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000163}
Jordy Rosea6b808c2010-07-07 07:48:06 +0000164
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000165const GRState *CStringChecker::checkNonNull(CheckerContext &C,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000166 const GRState *state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000167 const Expr *S, SVal l) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000168 // If a previous check has failed, propagate the failure.
169 if (!state)
170 return NULL;
171
172 const GRState *stateNull, *stateNonNull;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000173 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed325ffb2010-07-08 23:57:29 +0000174
175 if (stateNull && !stateNonNull) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000176 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000177 if (!N)
178 return NULL;
179
Jordy Rosed325ffb2010-07-08 23:57:29 +0000180 if (!BT_Null)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000181 BT_Null.reset(new BuiltinBug("API",
182 "Null pointer argument in call to byte string function"));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000183
184 // Generate a report for this bug.
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000185 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Jordy Rosea6b808c2010-07-07 07:48:06 +0000186 EnhancedBugReport *report = new EnhancedBugReport(*BT,
187 BT->getDescription(), N);
188
189 report->addRange(S->getSourceRange());
190 report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, S);
191 C.EmitReport(report);
192 return NULL;
193 }
194
195 // From here on, assume that the value is non-null.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000196 assert(stateNonNull);
197 return stateNonNull;
Jordy Rosea6b808c2010-07-07 07:48:06 +0000198}
199
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000200// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
201const GRState *CStringChecker::CheckLocation(CheckerContext &C,
202 const GRState *state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000203 const Expr *S, SVal l,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000204 bool IsDestination) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000205 // If a previous check has failed, propagate the failure.
206 if (!state)
207 return NULL;
208
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000209 // Check for out of bound array element access.
210 const MemRegion *R = l.getAsRegion();
211 if (!R)
212 return state;
213
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000214 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
215 if (!ER)
216 return state;
217
Zhongxing Xu018220c2010-08-11 06:10:55 +0000218 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000219 "CheckLocation should only be called with char* ElementRegions");
220
221 // Get the size of the array.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000222 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
223 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000224 SVal Extent =
225 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000226 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
227
228 // Get the index of the accessed element.
Gabor Greif89b06582010-09-09 10:51:37 +0000229 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000230
Ted Kremenek28f47b92010-12-01 22:16:56 +0000231 const GRState *StInBound = state->assumeInBound(Idx, Size, true);
232 const GRState *StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000233 if (StOutBound && !StInBound) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000234 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000235 if (!N)
236 return NULL;
237
Jordy Rosee64f3112010-08-16 07:51:42 +0000238 BuiltinBug *BT;
239 if (IsDestination) {
240 if (!BT_BoundsWrite) {
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000241 BT_BoundsWrite.reset(new BuiltinBug("Out-of-bound array access",
242 "Byte string function overflows destination buffer"));
Jordy Rosee64f3112010-08-16 07:51:42 +0000243 }
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000244 BT = static_cast<BuiltinBug*>(BT_BoundsWrite.get());
Jordy Rosee64f3112010-08-16 07:51:42 +0000245 } else {
246 if (!BT_Bounds) {
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000247 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
248 "Byte string function accesses out-of-bound array element"));
Jordy Rosee64f3112010-08-16 07:51:42 +0000249 }
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000250 BT = static_cast<BuiltinBug*>(BT_Bounds.get());
Jordy Rosee64f3112010-08-16 07:51:42 +0000251 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000252
253 // FIXME: It would be nice to eventually make this diagnostic more clear,
254 // e.g., by referencing the original declaration or by saying *why* this
255 // reference is outside the range.
256
257 // Generate a report for this bug.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000258 RangedBugReport *report = new RangedBugReport(*BT, BT->getDescription(), N);
259
260 report->addRange(S->getSourceRange());
261 C.EmitReport(report);
262 return NULL;
263 }
264
265 // Array bound check succeeded. From this point forward the array bound
266 // should always succeed.
267 return StInBound;
268}
269
270const GRState *CStringChecker::CheckBufferAccess(CheckerContext &C,
271 const GRState *state,
272 const Expr *Size,
273 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000274 const Expr *SecondBuf,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000275 bool FirstIsDestination) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000276 // If a previous check has failed, propagate the failure.
277 if (!state)
278 return NULL;
279
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000280 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000281 ASTContext &Ctx = svalBuilder.getContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000282
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000283 QualType sizeTy = Size->getType();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000284 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
285
Jordy Rosea6b808c2010-07-07 07:48:06 +0000286 // Check that the first buffer is non-null.
287 SVal BufVal = state->getSVal(FirstBuf);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000288 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000289 if (!state)
290 return NULL;
291
Jordy Rosed325ffb2010-07-08 23:57:29 +0000292 // Get the access length and make sure it is known.
293 SVal LengthVal = state->getSVal(Size);
294 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
295 if (!Length)
296 return state;
297
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000298 // Compute the offset of the last element to be accessed: size-1.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000299 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
300 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
301 *Length, One, sizeTy));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000302
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000303 // Check that the first buffer is sufficiently long.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000304 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000305 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000306 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
307 LastOffset, PtrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +0000308 state = CheckLocation(C, state, FirstBuf, BufEnd, FirstIsDestination);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000309
Jordy Roseb6a40262010-08-05 23:11:30 +0000310 // If the buffer isn't large enough, abort.
311 if (!state)
312 return NULL;
313 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000314
315 // If there's a second buffer, check it as well.
316 if (SecondBuf) {
317 BufVal = state->getSVal(SecondBuf);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000318 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000319 if (!state)
320 return NULL;
321
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000322 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000323 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000324 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
325 LastOffset, PtrTy);
Jordy Roseb6a40262010-08-05 23:11:30 +0000326 state = CheckLocation(C, state, SecondBuf, BufEnd);
327 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000328 }
329
330 // Large enough or not, return this state!
331 return state;
332}
333
334const GRState *CStringChecker::CheckOverlap(CheckerContext &C,
335 const GRState *state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000336 const Expr *Size,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000337 const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000338 const Expr *Second) const {
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000339 // Do a simple check for overlap: if the two arguments are from the same
340 // buffer, see if the end of the first is greater than the start of the second
341 // or vice versa.
342
Jordy Rosed325ffb2010-07-08 23:57:29 +0000343 // If a previous check has failed, propagate the failure.
344 if (!state)
345 return NULL;
346
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000347 const GRState *stateTrue, *stateFalse;
348
349 // Get the buffer values and make sure they're known locations.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000350 SVal firstVal = state->getSVal(First);
351 SVal secondVal = state->getSVal(Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000352
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000353 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
354 if (!firstLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000355 return state;
356
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000357 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
358 if (!secondLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000359 return state;
360
361 // Are the two values the same?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000362 SValBuilder &svalBuilder = C.getSValBuilder();
363 llvm::tie(stateTrue, stateFalse) =
364 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000365
366 if (stateTrue && !stateFalse) {
367 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000368 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000369 return NULL;
370 }
371
Ted Kremenek28f47b92010-12-01 22:16:56 +0000372 // assume the two expressions are not equal.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000373 assert(stateFalse);
374 state = stateFalse;
375
376 // Which value comes first?
Jordy Roseee2fde12011-06-16 05:56:50 +0000377 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000378 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
379 *firstLoc, *secondLoc, cmpTy);
380 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
381 if (!reverseTest)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000382 return state;
383
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000384 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000385 if (stateTrue) {
386 if (stateFalse) {
387 // If we don't know which one comes first, we can't perform this test.
388 return state;
389 } else {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000390 // Switch the values so that firstVal is before secondVal.
391 Loc *tmpLoc = firstLoc;
392 firstLoc = secondLoc;
393 secondLoc = tmpLoc;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000394
395 // Switch the Exprs as well, so that they still correspond.
396 const Expr *tmpExpr = First;
397 First = Second;
398 Second = tmpExpr;
399 }
400 }
401
402 // Get the length, and make sure it too is known.
403 SVal LengthVal = state->getSVal(Size);
404 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
405 if (!Length)
406 return state;
407
408 // Convert the first buffer's start address to char*.
409 // Bail out if the cast fails.
Jordy Roseee2fde12011-06-16 05:56:50 +0000410 ASTContext &Ctx = svalBuilder.getContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000411 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose1e022412011-06-16 05:51:02 +0000412 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
413 First->getType());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000414 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
415 if (!FirstStartLoc)
416 return state;
417
418 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000419 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000420 *FirstStartLoc, *Length, CharPtrTy);
421 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
422 if (!FirstEndLoc)
423 return state;
424
425 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000426 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
427 *FirstEndLoc, *secondLoc, cmpTy);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000428 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
429 if (!OverlapTest)
430 return state;
431
Ted Kremenek28f47b92010-12-01 22:16:56 +0000432 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000433
434 if (stateTrue && !stateFalse) {
435 // Overlap!
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000436 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000437 return NULL;
438 }
439
Ted Kremenek28f47b92010-12-01 22:16:56 +0000440 // assume the two expressions don't overlap.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000441 assert(stateFalse);
442 return stateFalse;
443}
444
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000445void CStringChecker::emitOverlapBug(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000446 const Stmt *First, const Stmt *Second) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000447 ExplodedNode *N = C.generateSink(state);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000448 if (!N)
449 return;
450
451 if (!BT_Overlap)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000452 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000453
454 // Generate a report for this bug.
455 RangedBugReport *report =
456 new RangedBugReport(*BT_Overlap,
457 "Arguments must not be overlapping buffers", N);
458 report->addRange(First->getSourceRange());
459 report->addRange(Second->getSourceRange());
460
461 C.EmitReport(report);
462}
463
Jordy Rosed5af0e12011-06-15 05:52:56 +0000464const GRState *CStringChecker::checkAdditionOverflow(CheckerContext &C,
465 const GRState *state,
466 NonLoc left,
467 NonLoc right) const {
468 // If a previous check has failed, propagate the failure.
469 if (!state)
470 return NULL;
471
472 SValBuilder &svalBuilder = C.getSValBuilder();
473 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
474
475 QualType sizeTy = svalBuilder.getContext().getSizeType();
476 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
477 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
478
479 SVal maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
480 sizeTy);
481
482 if (maxMinusRight.isUnknownOrUndef()) {
483 // Try switching the operands. (The order of these two assignments is
484 // important!)
485 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
486 sizeTy);
487 left = right;
488 }
489
490 if (NonLoc *maxMinusRightNL = dyn_cast<NonLoc>(&maxMinusRight)) {
491 QualType cmpTy = svalBuilder.getConditionType();
492 // If left > max - right, we have an overflow.
493 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
494 *maxMinusRightNL, cmpTy);
495
496 const GRState *stateOverflow, *stateOkay;
497 llvm::tie(stateOverflow, stateOkay) =
498 state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
499
500 if (stateOverflow && !stateOkay) {
501 // We have an overflow. Emit a bug report.
502 ExplodedNode *N = C.generateSink(stateOverflow);
503 if (!N)
504 return NULL;
505
506 if (!BT_AdditionOverflow)
507 BT_AdditionOverflow.reset(new BuiltinBug("API",
508 "Sum of expressions causes overflow"));
509
510 llvm::SmallString<120> buf;
511 llvm::raw_svector_ostream os(buf);
512 // This isn't a great error message, but this should never occur in real
513 // code anyway -- you'd have to create a buffer longer than a size_t can
514 // represent, which is sort of a contradiction.
515 os << "This expression will create a string whose length is too big to "
516 << "be represented as a size_t";
517
518 // Generate a report for this bug.
519 BugReport *report = new BugReport(*BT_AdditionOverflow, os.str(), N);
520 C.EmitReport(report);
521
522 return NULL;
523 }
524
525 // From now on, assume an overflow didn't occur.
526 assert(stateOkay);
527 state = stateOkay;
528 }
529
530 return state;
531}
532
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000533const GRState *CStringChecker::setCStringLength(const GRState *state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000534 const MemRegion *MR,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000535 SVal strLength) {
536 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rosee64f3112010-08-16 07:51:42 +0000537
538 MR = MR->StripCasts();
539
540 switch (MR->getKind()) {
541 case MemRegion::StringRegionKind:
542 // FIXME: This can happen if we strcpy() into a string region. This is
543 // undefined [C99 6.4.5p6], but we should still warn about it.
544 return state;
545
546 case MemRegion::SymbolicRegionKind:
547 case MemRegion::AllocaRegionKind:
548 case MemRegion::VarRegionKind:
549 case MemRegion::FieldRegionKind:
550 case MemRegion::ObjCIvarRegionKind:
Jordy Rose210c05b2011-06-15 05:14:03 +0000551 // These are the types we can currently track string lengths for.
552 break;
Jordy Rosee64f3112010-08-16 07:51:42 +0000553
554 case MemRegion::ElementRegionKind:
555 // FIXME: Handle element regions by upper-bounding the parent region's
556 // string length.
557 return state;
558
559 default:
560 // Other regions (mostly non-data) can't have a reliable C string length.
561 // For now, just ignore the change.
562 // FIXME: These are rare but not impossible. We should output some kind of
563 // warning for things like strcpy((char[]){'a', 0}, "b");
564 return state;
565 }
Jordy Rose210c05b2011-06-15 05:14:03 +0000566
567 if (strLength.isUnknown())
568 return state->remove<CStringLength>(MR);
569
570 return state->set<CStringLength>(MR, strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +0000571}
572
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000573SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Jordy Rosea5261542010-08-14 21:02:52 +0000574 const GRState *&state,
575 const Expr *Ex,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000576 const MemRegion *MR,
577 bool hypothetical) {
578 if (!hypothetical) {
579 // If there's a recorded length, go ahead and return it.
580 const SVal *Recorded = state->get<CStringLength>(MR);
581 if (Recorded)
582 return *Recorded;
583 }
Jordy Rosea5261542010-08-14 21:02:52 +0000584
585 // Otherwise, get a new symbol and update the state.
586 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000587 SValBuilder &svalBuilder = C.getSValBuilder();
588 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000589 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
590 MR, Ex, sizeTy, Count);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000591
592 if (!hypothetical)
593 state = state->set<CStringLength>(MR, strLength);
594
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000595 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000596}
597
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000598SVal CStringChecker::getCStringLength(CheckerContext &C, const GRState *&state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000599 const Expr *Ex, SVal Buf,
600 bool hypothetical) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000601 const MemRegion *MR = Buf.getAsRegion();
602 if (!MR) {
603 // If we can't get a region, see if it's something we /know/ isn't a
604 // C string. In the context of locations, the only time we can issue such
605 // a warning is for labels.
606 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000607 if (ExplodedNode *N = C.generateNode(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000608 if (!BT_NotCString)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000609 BT_NotCString.reset(new BuiltinBug("API",
610 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000611
612 llvm::SmallString<120> buf;
613 llvm::raw_svector_ostream os(buf);
614 os << "Argument to byte string function is the address of the label '"
Chris Lattner68106302011-02-17 05:38:27 +0000615 << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000616 << "', which is not a null-terminated string";
617
618 // Generate a report for this bug.
619 EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
620 os.str(), N);
621
622 report->addRange(Ex->getSourceRange());
623 C.EmitReport(report);
624 }
625
626 return UndefinedVal();
627 }
628
Jordy Rosea5261542010-08-14 21:02:52 +0000629 // If it's not a region and not a label, give up.
630 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000631 }
632
Jordy Rosea5261542010-08-14 21:02:52 +0000633 // If we have a region, strip casts from it and see if we can figure out
634 // its length. For anything we can't figure out, just return UnknownVal.
635 MR = MR->StripCasts();
636
637 switch (MR->getKind()) {
638 case MemRegion::StringRegionKind: {
639 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
640 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000641 SValBuilder &svalBuilder = C.getSValBuilder();
642 QualType sizeTy = svalBuilder.getContext().getSizeType();
643 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
644 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000645 }
646 case MemRegion::SymbolicRegionKind:
647 case MemRegion::AllocaRegionKind:
648 case MemRegion::VarRegionKind:
649 case MemRegion::FieldRegionKind:
650 case MemRegion::ObjCIvarRegionKind:
Jordy Rosed5af0e12011-06-15 05:52:56 +0000651 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rosea5261542010-08-14 21:02:52 +0000652 case MemRegion::CompoundLiteralRegionKind:
653 // FIXME: Can we track this? Is it necessary?
654 return UnknownVal();
655 case MemRegion::ElementRegionKind:
656 // FIXME: How can we handle this? It's not good enough to subtract the
657 // offset from the base string length; consider "123\x00567" and &a[5].
658 return UnknownVal();
659 default:
660 // Other regions (mostly non-data) can't have a reliable C string length.
661 // In this case, an error is emitted and UndefinedVal is returned.
662 // The caller should always be prepared to handle this case.
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000663 if (ExplodedNode *N = C.generateNode(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000664 if (!BT_NotCString)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000665 BT_NotCString.reset(new BuiltinBug("API",
666 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000667
668 llvm::SmallString<120> buf;
669 llvm::raw_svector_ostream os(buf);
670
671 os << "Argument to byte string function is ";
672
673 if (SummarizeRegion(os, C.getASTContext(), MR))
674 os << ", which is not a null-terminated string";
675 else
676 os << "not a null-terminated string";
677
678 // Generate a report for this bug.
679 EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
680 os.str(), N);
681
682 report->addRange(Ex->getSourceRange());
683 C.EmitReport(report);
684 }
685
686 return UndefinedVal();
687 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000688}
689
Lenny Maiorani318dd922011-04-12 17:08:43 +0000690const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
691 const GRState *&state, const Expr *expr, SVal val) const {
692
693 // Get the memory region pointed to by the val.
694 const MemRegion *bufRegion = val.getAsRegion();
695 if (!bufRegion)
696 return NULL;
697
698 // Strip casts off the memory region.
699 bufRegion = bufRegion->StripCasts();
700
701 // Cast the memory region to a string region.
702 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
703 if (!strRegion)
704 return NULL;
705
706 // Return the actual string in the string region.
707 return strRegion->getStringLiteral();
708}
709
Jordy Rosee64f3112010-08-16 07:51:42 +0000710const GRState *CStringChecker::InvalidateBuffer(CheckerContext &C,
711 const GRState *state,
712 const Expr *E, SVal V) {
713 Loc *L = dyn_cast<Loc>(&V);
714 if (!L)
715 return state;
716
717 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
718 // some assumptions about the value that CFRefCount can't. Even so, it should
719 // probably be refactored.
720 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
721 const MemRegion *R = MR->getRegion()->StripCasts();
722
723 // Are we dealing with an ElementRegion? If so, we should be invalidating
724 // the super-region.
725 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
726 R = ER->getSuperRegion();
727 // FIXME: What about layers of ElementRegions?
728 }
729
730 // Invalidate this region.
731 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek25345282011-02-11 19:48:15 +0000732 return state->invalidateRegion(R, E, Count, NULL);
Jordy Rosee64f3112010-08-16 07:51:42 +0000733 }
734
735 // If we have a non-region value by chance, just remove the binding.
736 // FIXME: is this necessary or correct? This handles the non-Region
737 // cases. Is it ever valid to store to these?
738 return state->unbindLoc(*L);
739}
740
Jordy Rose19c5dd12010-07-27 01:37:31 +0000741bool CStringChecker::SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
742 const MemRegion *MR) {
743 const TypedRegion *TR = dyn_cast<TypedRegion>(MR);
744 if (!TR)
745 return false;
746
747 switch (TR->getKind()) {
748 case MemRegion::FunctionTextRegionKind: {
749 const FunctionDecl *FD = cast<FunctionTextRegion>(TR)->getDecl();
750 if (FD)
751 os << "the address of the function '" << FD << "'";
752 else
753 os << "the address of a function";
754 return true;
755 }
756 case MemRegion::BlockTextRegionKind:
757 os << "block text";
758 return true;
759 case MemRegion::BlockDataRegionKind:
760 os << "a block";
761 return true;
762 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000763 case MemRegion::CXXTempObjectRegionKind:
764 os << "a C++ temp object of type " << TR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000765 return true;
766 case MemRegion::VarRegionKind:
Zhongxing Xu018220c2010-08-11 06:10:55 +0000767 os << "a variable of type" << TR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000768 return true;
769 case MemRegion::FieldRegionKind:
Zhongxing Xu018220c2010-08-11 06:10:55 +0000770 os << "a field of type " << TR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000771 return true;
772 case MemRegion::ObjCIvarRegionKind:
Zhongxing Xu018220c2010-08-11 06:10:55 +0000773 os << "an instance variable of type " << TR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000774 return true;
775 default:
776 return false;
777 }
778}
779
Jordy Rosed325ffb2010-07-08 23:57:29 +0000780//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000781// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000782//===----------------------------------------------------------------------===//
783
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000784void CStringChecker::evalCopyCommon(CheckerContext &C,
785 const CallExpr *CE,
786 const GRState *state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000787 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000788 const Expr *Source, bool Restricted,
789 bool IsMempcpy) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000790 // See if the size argument is zero.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000791 SVal sizeVal = state->getSVal(Size);
792 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000793
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000794 const GRState *stateZeroSize, *stateNonZeroSize;
Jordy Rose1e022412011-06-16 05:51:02 +0000795 llvm::tie(stateZeroSize, stateNonZeroSize) =
796 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000797
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000798 // Get the value of the Dest.
799 SVal destVal = state->getSVal(Dest);
800
801 // If the size is zero, there won't be any actual memory access, so
802 // just bind the return value to the destination buffer and return.
803 if (stateZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000804 stateZeroSize = stateZeroSize->BindExpr(CE, destVal);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000805 C.addTransition(stateZeroSize);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000806 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000807
808 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000809 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000810 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000811
812 // Ensure the destination is not null. If it is NULL there will be a
813 // NULL pointer dereference.
814 state = checkNonNull(C, state, Dest, destVal);
815 if (!state)
816 return;
817
818 // Get the value of the Src.
819 SVal srcVal = state->getSVal(Source);
820
821 // Ensure the source is not null. If it is NULL there will be a
822 // NULL pointer dereference.
823 state = checkNonNull(C, state, Source, srcVal);
824 if (!state)
825 return;
826
Jordy Rose7182b962011-06-04 01:50:25 +0000827 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rosee64f3112010-08-16 07:51:42 +0000828 state = CheckBufferAccess(C, state, Size, Dest, Source,
829 /* FirstIsDst = */ true);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000830 if (Restricted)
831 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000832
Jordy Rose7182b962011-06-04 01:50:25 +0000833 if (!state)
834 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000835
Jordy Rose7182b962011-06-04 01:50:25 +0000836 // If this is mempcpy, get the byte after the last byte copied and
837 // bind the expr.
838 if (IsMempcpy) {
839 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
840 assert(destRegVal && "Destination should be a known MemRegionVal here");
841
842 // Get the length to copy.
843 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
844
845 if (lenValNonLoc) {
846 // Get the byte after the last byte copied.
847 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
848 *destRegVal,
849 *lenValNonLoc,
850 Dest->getType());
851
852 // The byte after the last byte copied is the return value.
853 state = state->BindExpr(CE, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000854 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000855 // If we don't know how much we copied, we can at least
856 // conjure a return value for later.
857 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
858 SVal result =
859 C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
860 state = state->BindExpr(CE, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000861 }
862
Jordy Rose7182b962011-06-04 01:50:25 +0000863 } else {
864 // All other copies return the destination buffer.
865 // (Well, bcopy() has a void return type, but this won't hurt.)
866 state = state->BindExpr(CE, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000867 }
Jordy Rose7182b962011-06-04 01:50:25 +0000868
869 // Invalidate the destination.
870 // FIXME: Even if we can't perfectly model the copy, we should see if we
871 // can use LazyCompoundVals to copy the source values into the destination.
872 // This would probably remove any existing bindings past the end of the
873 // copied region, but that's still an improvement over blank invalidation.
874 state = InvalidateBuffer(C, state, Dest, state->getSVal(Dest));
875 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000876 }
877}
878
879
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000880void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000881 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000882 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000883 const Expr *Dest = CE->getArg(0);
884 const GRState *state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000885
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000886 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
887}
888
889void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
890 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
891 // The return value is a pointer to the byte following the last written byte.
892 const Expr *Dest = CE->getArg(0);
893 const GRState *state = C.getState();
894
895 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000896}
897
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000898void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000899 // void *memmove(void *dst, const void *src, size_t n);
900 // The return value is the address of the destination buffer.
901 const Expr *Dest = CE->getArg(0);
902 const GRState *state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000903
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000904 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000905}
906
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000907void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000908 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000909 evalCopyCommon(C, CE, C.getState(),
910 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000911}
912
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000913void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000914 // int memcmp(const void *s1, const void *s2, size_t n);
915 const Expr *Left = CE->getArg(0);
916 const Expr *Right = CE->getArg(1);
917 const Expr *Size = CE->getArg(2);
918
919 const GRState *state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000920 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000921
Jordy Rosed325ffb2010-07-08 23:57:29 +0000922 // See if the size argument is zero.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000923 SVal sizeVal = state->getSVal(Size);
924 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000925
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000926 const GRState *stateZeroSize, *stateNonZeroSize;
927 llvm::tie(stateZeroSize, stateNonZeroSize) =
928 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000929
Jordy Rosed325ffb2010-07-08 23:57:29 +0000930 // If the size can be zero, the result will be 0 in that case, and we don't
931 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000932 if (stateZeroSize) {
933 state = stateZeroSize;
934 state = state->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000935 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000936 }
937
Jordy Rosed325ffb2010-07-08 23:57:29 +0000938 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000939 if (stateNonZeroSize) {
940 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +0000941 // If we know the two buffers are the same, we know the result is 0.
942 // First, get the two buffers' addresses. Another checker will have already
943 // made sure they're not undefined.
944 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(state->getSVal(Left));
945 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(state->getSVal(Right));
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000946
Jordy Rosed325ffb2010-07-08 23:57:29 +0000947 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000948 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000949 const GRState *StSameBuf, *StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000950 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000951
Jordy Rose1e022412011-06-16 05:51:02 +0000952 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000953 // and we only need to check one size.
954 if (StSameBuf) {
955 state = StSameBuf;
956 state = CheckBufferAccess(C, state, Size, Left);
957 if (state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000958 state = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000959 C.addTransition(state);
960 }
961 }
962
963 // If the two arguments might be different buffers, we have to check the
964 // size of both of them.
965 if (StNotSameBuf) {
966 state = StNotSameBuf;
967 state = CheckBufferAccess(C, state, Size, Left, Right);
968 if (state) {
969 // The return value is the comparison result, which we don't know.
970 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000971 SVal CmpV = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000972 state = state->BindExpr(CE, CmpV);
973 C.addTransition(state);
974 }
975 }
976 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000977}
978
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000979void CStringChecker::evalstrLength(CheckerContext &C,
980 const CallExpr *CE) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000981 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +0000982 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
983}
984
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000985void CStringChecker::evalstrnLength(CheckerContext &C,
986 const CallExpr *CE) const {
Ted Kremenekbe4242c2011-02-22 04:55:05 +0000987 // size_t strnlen(const char *s, size_t maxlen);
988 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
989}
990
991void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000992 bool IsStrnlen) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000993 const GRState *state = C.getState();
Jordy Rose793bff32011-06-14 01:15:31 +0000994
995 if (IsStrnlen) {
996 const Expr *maxlenExpr = CE->getArg(1);
997 SVal maxlenVal = state->getSVal(maxlenExpr);
998
999 const GRState *stateZeroSize, *stateNonZeroSize;
1000 llvm::tie(stateZeroSize, stateNonZeroSize) =
1001 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1002
1003 // If the size can be zero, the result will be 0 in that case, and we don't
1004 // have to check the string itself.
1005 if (stateZeroSize) {
1006 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
1007 stateZeroSize = stateZeroSize->BindExpr(CE, zero);
1008 C.addTransition(stateZeroSize);
1009 }
1010
1011 // If the size is GUARANTEED to be zero, we're done!
1012 if (!stateNonZeroSize)
1013 return;
1014
1015 // Otherwise, record the assumption that the size is nonzero.
1016 state = stateNonZeroSize;
1017 }
1018
1019 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001020 const Expr *Arg = CE->getArg(0);
1021 SVal ArgVal = state->getSVal(Arg);
1022
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001023 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001024
Jordy Rosebd32bee2011-06-14 01:26:48 +00001025 if (!state)
1026 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001027
Jordy Rosebd32bee2011-06-14 01:26:48 +00001028 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001029
Jordy Rosebd32bee2011-06-14 01:26:48 +00001030 // If the argument isn't a valid C string, there's no valid state to
1031 // transition to.
1032 if (strLength.isUndef())
1033 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001034
Jordy Rosebd32bee2011-06-14 01:26:48 +00001035 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001036
Jordy Rosebd32bee2011-06-14 01:26:48 +00001037 // If the check is for strnlen() then bind the return value to no more than
1038 // the maxlen value.
1039 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001040 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001041
Jordy Rosebd32bee2011-06-14 01:26:48 +00001042 // It's a little unfortunate to be getting this again,
1043 // but it's not that expensive...
1044 const Expr *maxlenExpr = CE->getArg(1);
1045 SVal maxlenVal = state->getSVal(maxlenExpr);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001046
Jordy Rosebd32bee2011-06-14 01:26:48 +00001047 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1048 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001049
Jordy Rosebd32bee2011-06-14 01:26:48 +00001050 if (strLengthNL && maxlenValNL) {
1051 const GRState *stateStringTooLong, *stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001052
Jordy Rosebd32bee2011-06-14 01:26:48 +00001053 // Check if the strLength is greater than the maxlen.
1054 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
1055 state->assume(cast<DefinedOrUnknownSVal>
1056 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1057 *strLengthNL,
1058 *maxlenValNL,
1059 cmpTy)));
Jordy Rose793bff32011-06-14 01:15:31 +00001060
Jordy Rosebd32bee2011-06-14 01:26:48 +00001061 if (stateStringTooLong && !stateStringNotTooLong) {
1062 // If the string is longer than maxlen, return maxlen.
1063 result = *maxlenValNL;
1064 } else if (stateStringNotTooLong && !stateStringTooLong) {
1065 // If the string is shorter than maxlen, return its length.
1066 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001067 }
1068 }
1069
Jordy Rosebd32bee2011-06-14 01:26:48 +00001070 if (result.isUnknown()) {
1071 // If we don't have enough information for a comparison, there's
1072 // no guarantee the full string length will actually be returned.
1073 // All we know is the return value is the min of the string length
1074 // and the limit. This is better than nothing.
1075 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
1076 result = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
1077 NonLoc *resultNL = cast<NonLoc>(&result);
1078
1079 if (strLengthNL) {
1080 state = state->assume(cast<DefinedOrUnknownSVal>
1081 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1082 *resultNL,
1083 *strLengthNL,
1084 cmpTy)), true);
1085 }
1086
1087 if (maxlenValNL) {
1088 state = state->assume(cast<DefinedOrUnknownSVal>
1089 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1090 *resultNL,
1091 *maxlenValNL,
1092 cmpTy)), true);
1093 }
1094 }
1095
1096 } else {
1097 // This is a plain strlen(), not strnlen().
1098 result = cast<DefinedOrUnknownSVal>(strLength);
1099
1100 // If we don't know the length of the string, conjure a return
1101 // value, so it can be used in constraints, at least.
1102 if (result.isUnknown()) {
1103 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
1104 result = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
1105 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001106 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001107
1108 // Bind the return value.
1109 assert(!result.isUnknown() && "Should have conjured a value by now");
1110 state = state->BindExpr(CE, result);
1111 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001112}
1113
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001114void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosee64f3112010-08-16 07:51:42 +00001115 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001116 evalStrcpyCommon(C, CE,
1117 /* returnEnd = */ false,
1118 /* isBounded = */ false,
1119 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001120}
1121
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001122void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosec1525862011-06-04 00:05:23 +00001123 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001124 evalStrcpyCommon(C, CE,
1125 /* returnEnd = */ false,
1126 /* isBounded = */ true,
1127 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001128}
1129
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001130void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosee64f3112010-08-16 07:51:42 +00001131 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001132 evalStrcpyCommon(C, CE,
1133 /* returnEnd = */ true,
1134 /* isBounded = */ false,
1135 /* isAppending = */ false);
1136}
1137
1138void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
1139 //char *strcat(char *restrict s1, const char *restrict s2);
1140 evalStrcpyCommon(C, CE,
1141 /* returnEnd = */ false,
1142 /* isBounded = */ false,
1143 /* isAppending = */ true);
1144}
1145
1146void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
1147 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1148 evalStrcpyCommon(C, CE,
1149 /* returnEnd = */ false,
1150 /* isBounded = */ true,
1151 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001152}
1153
Ted Kremenek9c149532010-12-01 21:57:22 +00001154void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001155 bool returnEnd, bool isBounded,
1156 bool isAppending) const {
Jordy Rosee64f3112010-08-16 07:51:42 +00001157 const GRState *state = C.getState();
1158
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001159 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001160 const Expr *Dst = CE->getArg(0);
1161 SVal DstVal = state->getSVal(Dst);
1162
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001163 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001164 if (!state)
1165 return;
1166
1167 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001168 const Expr *srcExpr = CE->getArg(1);
1169 SVal srcVal = state->getSVal(srcExpr);
1170 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001171 if (!state)
1172 return;
1173
1174 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001175 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001176
1177 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001178 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001179 return;
1180
Jordy Rosed5af0e12011-06-15 05:52:56 +00001181 SValBuilder &svalBuilder = C.getSValBuilder();
1182 QualType cmpTy = svalBuilder.getConditionType();
1183
1184 SVal amountCopied = UnknownVal();
1185
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001186 // If the function is strncpy, strncat, etc... it is bounded.
1187 if (isBounded) {
1188 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001189 const Expr *lenExpr = CE->getArg(2);
1190 SVal lenVal = state->getSVal(lenExpr);
1191
Jordy Rosed5af0e12011-06-15 05:52:56 +00001192 // Protect against misdeclared strncpy().
1193 lenVal = svalBuilder.evalCast(lenVal,
1194 svalBuilder.getContext().getSizeType(),
1195 lenExpr->getType());
1196
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001197 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1198 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1199
Jordy Rosed5af0e12011-06-15 05:52:56 +00001200 // If we know both values, we might be able to figure out how much
1201 // we're copying.
1202 if (strLengthNL && lenValNL) {
1203 const GRState *stateSourceTooLong, *stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001204
Jordy Rosed5af0e12011-06-15 05:52:56 +00001205 // Check if the max number to copy is less than the length of the src.
1206 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) =
1207 state->assume(cast<DefinedOrUnknownSVal>
1208 (svalBuilder.evalBinOpNN(state, BO_GT, *strLengthNL,
1209 *lenValNL, cmpTy)));
1210
1211 if (stateSourceTooLong && !stateSourceNotTooLong) {
1212 // Max number to copy is less than the length of the src, so the actual
1213 // strLength copied is the max number arg.
1214 state = stateSourceTooLong;
1215 amountCopied = lenVal;
1216
1217 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1218 // The source buffer entirely fits in the bound.
1219 state = stateSourceNotTooLong;
1220 amountCopied = strLength;
1221 }
1222 }
1223
1224 // If we couldn't pin down the copy length, at least bound it.
1225 if (amountCopied.isUnknown()) {
1226 // Try to get a "hypothetical" string length symbol, which we can later
1227 // set as a real value if that turns out to be the case.
1228 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1229 assert(!amountCopied.isUndef());
1230
1231 if (NonLoc *amountCopiedNL = dyn_cast<NonLoc>(&amountCopied)) {
1232 if (lenValNL) {
1233 // amountCopied <= lenVal
1234 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1235 *amountCopiedNL,
1236 *lenValNL,
1237 cmpTy);
1238 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanBound),
1239 true);
1240 if (!state)
1241 return;
1242 }
1243
1244 if (strLengthNL) {
1245 // amountCopied <= strlen(source)
1246 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1247 *amountCopiedNL,
1248 *strLengthNL,
1249 cmpTy);
1250 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanSrc),
1251 true);
1252 if (!state)
1253 return;
1254 }
1255 }
1256 }
1257
1258 } else {
1259 // The function isn't bounded. The amount copied should match the length
1260 // of the source buffer.
1261 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001262 }
1263
Jordy Rosed5af0e12011-06-15 05:52:56 +00001264 assert(state);
1265
1266 // This represents the number of characters copied into the destination
1267 // buffer. (It may not actually be the strlen if the destination buffer
1268 // is not terminated.)
1269 SVal finalStrLength = UnknownVal();
1270
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001271 // If this is an appending function (strcat, strncat...) then set the
1272 // string length to strlen(src) + strlen(dst) since the buffer will
1273 // ultimately contain both.
1274 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001275 // Get the string length of the destination. If the destination is memory
1276 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001277 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1278 if (dstStrLength.isUndef())
1279 return;
1280
Jordy Rosed5af0e12011-06-15 05:52:56 +00001281 QualType sizeTy = svalBuilder.getContext().getSizeType();
1282
1283 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&amountCopied);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001284 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1285
Jordy Rosed5af0e12011-06-15 05:52:56 +00001286 // If we know both string lengths, we might know the final string length.
1287 if (srcStrLengthNL && dstStrLengthNL) {
1288 // Make sure the two lengths together don't overflow a size_t.
1289 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1290 if (!state)
1291 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001292
Jordy Rosed5af0e12011-06-15 05:52:56 +00001293 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1294 *dstStrLengthNL, sizeTy);
1295 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001296
Jordy Rosed5af0e12011-06-15 05:52:56 +00001297 // If we couldn't get a single value for the final string length,
1298 // we can at least bound it by the individual lengths.
1299 if (finalStrLength.isUnknown()) {
1300 // Try to get a "hypothetical" string length symbol, which we can later
1301 // set as a real value if that turns out to be the case.
1302 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1303 assert(!finalStrLength.isUndef());
1304
1305 if (NonLoc *finalStrLengthNL = dyn_cast<NonLoc>(&finalStrLength)) {
1306 if (srcStrLengthNL) {
1307 // finalStrLength >= srcStrLength
1308 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1309 *finalStrLengthNL,
1310 *srcStrLengthNL,
1311 cmpTy);
1312 state = state->assume(cast<DefinedOrUnknownSVal>(sourceInResult),
1313 true);
1314 if (!state)
1315 return;
1316 }
1317
1318 if (dstStrLengthNL) {
1319 // finalStrLength >= dstStrLength
1320 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1321 *finalStrLengthNL,
1322 *dstStrLengthNL,
1323 cmpTy);
1324 state = state->assume(cast<DefinedOrUnknownSVal>(destInResult),
1325 true);
1326 if (!state)
1327 return;
1328 }
1329 }
1330 }
1331
1332 } else {
1333 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1334 // the final string length will match the input string length.
1335 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001336 }
1337
Jordy Rosed5af0e12011-06-15 05:52:56 +00001338 // The final result of the function will either be a pointer past the last
1339 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001340 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001341
Jordy Rosed5af0e12011-06-15 05:52:56 +00001342 assert(state);
1343
Jordy Rosee64f3112010-08-16 07:51:42 +00001344 // If the destination is a MemRegion, try to check for a buffer overflow and
1345 // record the new string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001346 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001347 // If the final length is known, we can check for an overflow.
1348 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&finalStrLength)) {
1349 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1350 *knownStrLength,
1351 Dst->getType());
Jordy Rosee64f3112010-08-16 07:51:42 +00001352
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001353 state = CheckLocation(C, state, Dst, lastElement, /* IsDst = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001354 if (!state)
1355 return;
1356
1357 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001358 if (returnEnd)
1359 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001360 }
1361
1362 // Invalidate the destination. This must happen before we set the C string
1363 // length because invalidation will clear the length.
1364 // FIXME: Even if we can't perfectly model the copy, we should see if we
1365 // can use LazyCompoundVals to copy the source values into the destination.
1366 // This would probably remove any existing bindings past the end of the
1367 // string, but that's still an improvement over blank invalidation.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001368 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001369
1370 // Set the C string length of the destination.
Jordy Rosed5af0e12011-06-15 05:52:56 +00001371 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001372 }
1373
Jordy Rosed5af0e12011-06-15 05:52:56 +00001374 assert(state);
1375
Jordy Rosee64f3112010-08-16 07:51:42 +00001376 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1377 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001378 if (returnEnd && Result.isUnknown()) {
Jordy Rosee64f3112010-08-16 07:51:42 +00001379 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001380 Result = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rosee64f3112010-08-16 07:51:42 +00001381 }
1382
1383 // Set the return value.
1384 state = state->BindExpr(CE, Result);
1385 C.addTransition(state);
1386}
1387
Lenny Maiorani318dd922011-04-12 17:08:43 +00001388void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1389 //int strcmp(const char *restrict s1, const char *restrict s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001390 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001391}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001392
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001393void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1394 //int strncmp(const char *restrict s1, const char *restrict s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001395 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1396}
1397
1398void CStringChecker::evalStrcasecmp(CheckerContext &C,
1399 const CallExpr *CE) const {
1400 //int strcasecmp(const char *restrict s1, const char *restrict s2);
1401 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001402}
1403
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001404void CStringChecker::evalStrncasecmp(CheckerContext &C,
1405 const CallExpr *CE) const {
1406 //int strncasecmp(const char *restrict s1, const char *restrict s2, size_t n);
1407 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1408}
1409
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001410void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001411 bool isBounded, bool ignoreCase) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +00001412 const GRState *state = C.getState();
1413
1414 // Check that the first string is non-null
1415 const Expr *s1 = CE->getArg(0);
1416 SVal s1Val = state->getSVal(s1);
1417 state = checkNonNull(C, state, s1, s1Val);
1418 if (!state)
1419 return;
1420
1421 // Check that the second string is non-null.
1422 const Expr *s2 = CE->getArg(1);
1423 SVal s2Val = state->getSVal(s2);
1424 state = checkNonNull(C, state, s2, s2Val);
1425 if (!state)
1426 return;
1427
1428 // Get the string length of the first string or give up.
1429 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1430 if (s1Length.isUndef())
1431 return;
1432
1433 // Get the string length of the second string or give up.
1434 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1435 if (s2Length.isUndef())
1436 return;
1437
1438 // Get the string literal of the first string.
1439 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1440 if (!s1StrLiteral)
1441 return;
1442 llvm::StringRef s1StrRef = s1StrLiteral->getString();
1443
1444 // Get the string literal of the second string.
1445 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1446 if (!s2StrLiteral)
1447 return;
1448 llvm::StringRef s2StrRef = s2StrLiteral->getString();
1449
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001450 int result;
1451 if (isBounded) {
1452 // Get the max number of characters to compare.
1453 const Expr *lenExpr = CE->getArg(2);
1454 SVal lenVal = state->getSVal(lenExpr);
1455
1456 // Dynamically cast the length to a ConcreteInt. If it is not a ConcreteInt
1457 // then give up, otherwise get the value and use it as the bounds.
1458 nonloc::ConcreteInt *CI = dyn_cast<nonloc::ConcreteInt>(&lenVal);
1459 if (!CI)
1460 return;
1461 llvm::APSInt lenInt(CI->getValue());
1462
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001463 // Create substrings of each to compare the prefix.
1464 s1StrRef = s1StrRef.substr(0, (size_t)lenInt.getLimitedValue());
1465 s2StrRef = s2StrRef.substr(0, (size_t)lenInt.getLimitedValue());
1466 }
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001467
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001468 if (ignoreCase) {
1469 // Compare string 1 to string 2 the same way strcasecmp() does.
1470 result = s1StrRef.compare_lower(s2StrRef);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001471 } else {
1472 // Compare string 1 to string 2 the same way strcmp() does.
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001473 result = s1StrRef.compare(s2StrRef);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001474 }
Lenny Maiorani318dd922011-04-12 17:08:43 +00001475
1476 // Build the SVal of the comparison to bind the return value.
1477 SValBuilder &svalBuilder = C.getSValBuilder();
1478 QualType intTy = svalBuilder.getContext().IntTy;
1479 SVal resultVal = svalBuilder.makeIntVal(result, intTy);
1480
1481 // Bind the return value of the expression.
1482 // Set the return value.
1483 state = state->BindExpr(CE, resultVal);
1484 C.addTransition(state);
1485}
1486
Jordy Rosed325ffb2010-07-08 23:57:29 +00001487//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001488// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001489//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001490
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001491bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001492 // Get the callee. All the functions we care about are C functions
1493 // with simple identifiers.
1494 const GRState *state = C.getState();
1495 const Expr *Callee = CE->getCallee();
1496 const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl();
1497
1498 if (!FD)
1499 return false;
1500
1501 // Get the name of the callee. If it's a builtin, strip off the prefix.
Douglas Gregor90d26a42010-11-01 23:16:05 +00001502 IdentifierInfo *II = FD->getIdentifier();
1503 if (!II) // if no identifier, not a simple C function
1504 return false;
1505 llvm::StringRef Name = II->getName();
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001506 if (Name.startswith("__builtin_"))
1507 Name = Name.substr(10);
1508
Ted Kremenek9c149532010-12-01 21:57:22 +00001509 FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
1510 .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
Jordy Rosebe460d82011-06-03 23:42:56 +00001511 .Cases("mempcpy", "__mempcpy_chk", &CStringChecker::evalMempcpy)
Ted Kremenek9c149532010-12-01 21:57:22 +00001512 .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
1513 .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
1514 .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
Lenny Maiorani094ea0a2011-05-03 16:34:26 +00001515 //.Cases("strncpy", "__strncpy_chk", &CStringChecker::evalStrncpy)
Ted Kremenek9c149532010-12-01 21:57:22 +00001516 .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001517 .Cases("strcat", "__strcat_chk", &CStringChecker::evalStrcat)
1518 .Cases("strncat", "__strncat_chk", &CStringChecker::evalStrncat)
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001519 .Case("strlen", &CStringChecker::evalstrLength)
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001520 .Case("strnlen", &CStringChecker::evalstrnLength)
Lenny Maiorani318dd922011-04-12 17:08:43 +00001521 .Case("strcmp", &CStringChecker::evalStrcmp)
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001522 .Case("strncmp", &CStringChecker::evalStrncmp)
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001523 .Case("strcasecmp", &CStringChecker::evalStrcasecmp)
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001524 .Case("strncasecmp", &CStringChecker::evalStrncasecmp)
Ted Kremenek9c149532010-12-01 21:57:22 +00001525 .Case("bcopy", &CStringChecker::evalBcopy)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001526 .Default(NULL);
1527
Jordy Rosed325ffb2010-07-08 23:57:29 +00001528 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001529 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001530 return false;
1531
Jordy Rosed325ffb2010-07-08 23:57:29 +00001532 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001533 (this->*evalFunction)(C, CE);
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001534 return true;
1535}
Jordy Rosea5261542010-08-14 21:02:52 +00001536
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001537void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001538 // Record string length for char a[] = "abc";
1539 const GRState *state = C.getState();
1540
1541 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1542 I != E; ++I) {
1543 const VarDecl *D = dyn_cast<VarDecl>(*I);
1544 if (!D)
1545 continue;
1546
1547 // FIXME: Handle array fields of structs.
1548 if (!D->getType()->isArrayType())
1549 continue;
1550
1551 const Expr *Init = D->getInit();
1552 if (!Init)
1553 continue;
1554 if (!isa<StringLiteral>(Init))
1555 continue;
1556
1557 Loc VarLoc = state->getLValue(D, C.getPredecessor()->getLocationContext());
1558 const MemRegion *MR = VarLoc.getAsRegion();
1559 if (!MR)
1560 continue;
1561
1562 SVal StrVal = state->getSVal(Init);
1563 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001564 DefinedOrUnknownSVal strLength
1565 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rosea5261542010-08-14 21:02:52 +00001566
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001567 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001568 }
1569
1570 C.addTransition(state);
1571}
1572
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001573bool CStringChecker::wantsRegionChangeUpdate(const GRState *state) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001574 CStringLength::EntryMap Entries = state->get<CStringLength>();
1575 return !Entries.isEmpty();
1576}
1577
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001578const GRState *
1579CStringChecker::checkRegionChanges(const GRState *state,
Ted Kremenek35bdbf42011-05-02 19:42:42 +00001580 const StoreManager::InvalidatedSymbols *,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001581 const MemRegion * const *Begin,
1582 const MemRegion * const *End) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001583 CStringLength::EntryMap Entries = state->get<CStringLength>();
1584 if (Entries.isEmpty())
1585 return state;
1586
1587 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1588 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1589
1590 // First build sets for the changed regions and their super-regions.
1591 for ( ; Begin != End; ++Begin) {
1592 const MemRegion *MR = *Begin;
1593 Invalidated.insert(MR);
1594
1595 SuperRegions.insert(MR);
1596 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1597 MR = SR->getSuperRegion();
1598 SuperRegions.insert(MR);
1599 }
1600 }
1601
1602 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1603
1604 // Then loop over the entries in the current state.
1605 for (CStringLength::EntryMap::iterator I = Entries.begin(),
1606 E = Entries.end(); I != E; ++I) {
1607 const MemRegion *MR = I.getKey();
1608
1609 // Is this entry for a super-region of a changed region?
1610 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001611 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001612 continue;
1613 }
1614
1615 // Is this entry for a sub-region of a changed region?
1616 const MemRegion *Super = MR;
1617 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1618 Super = SR->getSuperRegion();
1619 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001620 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001621 break;
1622 }
1623 }
1624 }
1625
1626 return state->set<CStringLength>(Entries);
1627}
1628
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001629void CStringChecker::checkLiveSymbols(const GRState *state,
1630 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001631 // Mark all symbols in our string length map as valid.
1632 CStringLength::EntryMap Entries = state->get<CStringLength>();
1633
1634 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1635 I != E; ++I) {
1636 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001637
1638 for (SVal::symbol_iterator si = Len.symbol_begin(), se = Len.symbol_end();
1639 si != se; ++si)
1640 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00001641 }
1642}
1643
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001644void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1645 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001646 if (!SR.hasDeadSymbols())
1647 return;
1648
1649 const GRState *state = C.getState();
1650 CStringLength::EntryMap Entries = state->get<CStringLength>();
1651 if (Entries.isEmpty())
1652 return;
1653
1654 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1655 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1656 I != E; ++I) {
1657 SVal Len = I.getData();
1658 if (SymbolRef Sym = Len.getAsSymbol()) {
1659 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00001660 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00001661 }
1662 }
1663
1664 state = state->set<CStringLength>(Entries);
Ted Kremenekd048c6e2010-12-20 21:19:09 +00001665 C.generateNode(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001666}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001667
1668void ento::registerCStringChecker(CheckerManager &mgr) {
1669 mgr.registerChecker<CStringChecker>();
1670}