blob: c98bf5c598e20cc79e9803cd1863b41a6aeec250 [file] [log] [blame]
Jordy Rose134a2362010-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 Kyrtzidis2d3905f2011-02-15 21:25:03 +000015#include "ClangSACheckers.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000016#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis507ff532011-02-17 21:39:17 +000017#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000018#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000019#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"
Jordy Rose134a2362010-07-06 23:11:01 +000021#include "llvm/ADT/StringSwitch.h"
22
23using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000024using namespace ento;
Jordy Rose134a2362010-07-06 23:11:01 +000025
26namespace {
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000027class CStringChecker : public Checker< eval::Call,
Argyrios Kyrtzidisc26f15d2011-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,
34 BT_Overlap, BT_NotCString;
Jordy Rose134a2362010-07-06 23:11:01 +000035public:
Jordy Rose134a2362010-07-06 23:11:01 +000036 static void *getTag() { static int tag; return &tag; }
37
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000038 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
39 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
40 void checkLiveSymbols(const GRState *state, SymbolReaper &SR) const;
41 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
42 bool wantsRegionChangeUpdate(const GRState *state) const;
Jordy Rose2a2e21c2010-08-14 21:02:52 +000043
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000044 const GRState *checkRegionChanges(const GRState *state,
45 const MemRegion * const *Begin,
46 const MemRegion * const *End) const;
Jordy Rose134a2362010-07-06 23:11:01 +000047
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000048 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
49 const CallExpr *) const;
Jordy Rose134a2362010-07-06 23:11:01 +000050
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000051 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani79d74142011-03-31 21:36:53 +000052 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000053 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
54 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani79d74142011-03-31 21:36:53 +000055 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
56 const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +000057 const Expr *Size, const Expr *Source, const Expr *Dest,
Lenny Maiorani79d74142011-03-31 21:36:53 +000058 bool Restricted = false,
59 bool IsMempcpy = false) const;
Jordy Rosed5d2e502010-07-08 23:57:29 +000060
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000061 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose134a2362010-07-06 23:11:01 +000062
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000063 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
64 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek280a01f2011-02-22 04:55:05 +000065 void evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000066 bool IsStrnlen = false) const;
Jordy Roseb052e8f2010-07-27 01:37:31 +000067
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000068 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
69 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
70 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenekfb1a79a2011-02-22 04:58:34 +000071 void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool returnEnd,
Lenny Maiorani467dbd52011-04-09 15:12:58 +000072 bool isBounded, bool isAppending) const;
73
74 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
75 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose722f5582010-08-16 07:51:42 +000076
Jordy Rose134a2362010-07-06 23:11:01 +000077 // Utility methods
Jordy Rosed5d2e502010-07-08 23:57:29 +000078 std::pair<const GRState*, const GRState*>
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000079 static assumeZero(CheckerContext &C,
80 const GRState *state, SVal V, QualType Ty);
Jordy Rosed5d2e502010-07-08 23:57:29 +000081
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000082 static const GRState *setCStringLength(const GRState *state,
83 const MemRegion *MR, SVal strLength);
84 static SVal getCStringLengthForRegion(CheckerContext &C,
85 const GRState *&state,
86 const Expr *Ex, const MemRegion *MR);
Ted Kremenek90af9092010-12-02 07:49:45 +000087 SVal getCStringLength(CheckerContext &C, const GRState *&state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000088 const Expr *Ex, SVal Buf) const;
Jordy Roseb052e8f2010-07-27 01:37:31 +000089
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000090 static const GRState *InvalidateBuffer(CheckerContext &C,
91 const GRState *state,
92 const Expr *Ex, SVal V);
Jordy Rose722f5582010-08-16 07:51:42 +000093
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000094 static bool SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
95 const MemRegion *MR);
Jordy Roseb052e8f2010-07-27 01:37:31 +000096
97 // Re-usable checks
Ted Kremenek90af9092010-12-02 07:49:45 +000098 const GRState *checkNonNull(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000099 const Expr *S, SVal l) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000100 const GRState *CheckLocation(CheckerContext &C, const GRState *state,
Jordy Rose722f5582010-08-16 07:51:42 +0000101 const Expr *S, SVal l,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000102 bool IsDestination = false) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000103 const GRState *CheckBufferAccess(CheckerContext &C, const GRState *state,
104 const Expr *Size,
105 const Expr *FirstBuf,
Jordy Rose722f5582010-08-16 07:51:42 +0000106 const Expr *SecondBuf = NULL,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000107 bool FirstIsDestination = false) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000108 const GRState *CheckOverlap(CheckerContext &C, const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000109 const Expr *Size, const Expr *First,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000110 const Expr *Second) const;
Ted Kremenek90af9092010-12-02 07:49:45 +0000111 void emitOverlapBug(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000112 const Stmt *First, const Stmt *Second) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000113};
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000114
115class CStringLength {
116public:
117 typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
118};
Jordy Rose134a2362010-07-06 23:11:01 +0000119} //end anonymous namespace
120
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000121namespace clang {
Ted Kremenek98857c92010-12-23 07:20:52 +0000122namespace ento {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000123 template <>
124 struct GRStateTrait<CStringLength>
125 : public GRStatePartialTrait<CStringLength::EntryMap> {
126 static void *GDMIndex() { return CStringChecker::getTag(); }
127 };
128}
Argyrios Kyrtzidisca08fba2010-12-22 18:53:20 +0000129}
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000130
Jordy Rosed5d2e502010-07-08 23:57:29 +0000131//===----------------------------------------------------------------------===//
132// Individual checks and utility methods.
133//===----------------------------------------------------------------------===//
134
135std::pair<const GRState*, const GRState*>
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000136CStringChecker::assumeZero(CheckerContext &C, const GRState *state, SVal V,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000137 QualType Ty) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000138 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
139 if (!val)
Jordy Rosed5d2e502010-07-08 23:57:29 +0000140 return std::pair<const GRState*, const GRState *>(state, state);
Jordy Rose33c829a2010-07-07 07:48:06 +0000141
Ted Kremenek90af9092010-12-02 07:49:45 +0000142 SValBuilder &svalBuilder = C.getSValBuilder();
143 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
144 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000145}
Jordy Rose33c829a2010-07-07 07:48:06 +0000146
Ted Kremenek90af9092010-12-02 07:49:45 +0000147const GRState *CStringChecker::checkNonNull(CheckerContext &C,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000148 const GRState *state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000149 const Expr *S, SVal l) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000150 // If a previous check has failed, propagate the failure.
151 if (!state)
152 return NULL;
153
154 const GRState *stateNull, *stateNonNull;
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000155 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed5d2e502010-07-08 23:57:29 +0000156
157 if (stateNull && !stateNonNull) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000158 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rose33c829a2010-07-07 07:48:06 +0000159 if (!N)
160 return NULL;
161
Jordy Rosed5d2e502010-07-08 23:57:29 +0000162 if (!BT_Null)
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000163 BT_Null.reset(new BuiltinBug("API",
164 "Null pointer argument in call to byte string function"));
Jordy Rose33c829a2010-07-07 07:48:06 +0000165
166 // Generate a report for this bug.
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000167 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Jordy Rose33c829a2010-07-07 07:48:06 +0000168 EnhancedBugReport *report = new EnhancedBugReport(*BT,
169 BT->getDescription(), N);
170
171 report->addRange(S->getSourceRange());
172 report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, S);
173 C.EmitReport(report);
174 return NULL;
175 }
176
177 // From here on, assume that the value is non-null.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000178 assert(stateNonNull);
179 return stateNonNull;
Jordy Rose33c829a2010-07-07 07:48:06 +0000180}
181
Jordy Rose134a2362010-07-06 23:11:01 +0000182// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
183const GRState *CStringChecker::CheckLocation(CheckerContext &C,
184 const GRState *state,
Jordy Rose722f5582010-08-16 07:51:42 +0000185 const Expr *S, SVal l,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000186 bool IsDestination) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000187 // If a previous check has failed, propagate the failure.
188 if (!state)
189 return NULL;
190
Jordy Rose134a2362010-07-06 23:11:01 +0000191 // Check for out of bound array element access.
192 const MemRegion *R = l.getAsRegion();
193 if (!R)
194 return state;
195
Jordy Rose134a2362010-07-06 23:11:01 +0000196 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
197 if (!ER)
198 return state;
199
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000200 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Rose134a2362010-07-06 23:11:01 +0000201 "CheckLocation should only be called with char* ElementRegions");
202
203 // Get the size of the array.
Ted Kremenek90af9092010-12-02 07:49:45 +0000204 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
205 SValBuilder &svalBuilder = C.getSValBuilder();
206 SVal Extent = svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
Jordy Rose134a2362010-07-06 23:11:01 +0000207 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
208
209 // Get the index of the accessed element.
Gabor Greif230ddf32010-09-09 10:51:37 +0000210 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
Jordy Rose134a2362010-07-06 23:11:01 +0000211
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000212 const GRState *StInBound = state->assumeInBound(Idx, Size, true);
213 const GRState *StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Rose134a2362010-07-06 23:11:01 +0000214 if (StOutBound && !StInBound) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000215 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Rose134a2362010-07-06 23:11:01 +0000216 if (!N)
217 return NULL;
218
Jordy Rose722f5582010-08-16 07:51:42 +0000219 BuiltinBug *BT;
220 if (IsDestination) {
221 if (!BT_BoundsWrite) {
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000222 BT_BoundsWrite.reset(new BuiltinBug("Out-of-bound array access",
223 "Byte string function overflows destination buffer"));
Jordy Rose722f5582010-08-16 07:51:42 +0000224 }
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000225 BT = static_cast<BuiltinBug*>(BT_BoundsWrite.get());
Jordy Rose722f5582010-08-16 07:51:42 +0000226 } else {
227 if (!BT_Bounds) {
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000228 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
229 "Byte string function accesses out-of-bound array element"));
Jordy Rose722f5582010-08-16 07:51:42 +0000230 }
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000231 BT = static_cast<BuiltinBug*>(BT_Bounds.get());
Jordy Rose722f5582010-08-16 07:51:42 +0000232 }
Jordy Rose134a2362010-07-06 23:11:01 +0000233
234 // FIXME: It would be nice to eventually make this diagnostic more clear,
235 // e.g., by referencing the original declaration or by saying *why* this
236 // reference is outside the range.
237
238 // Generate a report for this bug.
Jordy Rose134a2362010-07-06 23:11:01 +0000239 RangedBugReport *report = new RangedBugReport(*BT, BT->getDescription(), N);
240
241 report->addRange(S->getSourceRange());
242 C.EmitReport(report);
243 return NULL;
244 }
245
246 // Array bound check succeeded. From this point forward the array bound
247 // should always succeed.
248 return StInBound;
249}
250
251const GRState *CStringChecker::CheckBufferAccess(CheckerContext &C,
252 const GRState *state,
253 const Expr *Size,
254 const Expr *FirstBuf,
Jordy Rose722f5582010-08-16 07:51:42 +0000255 const Expr *SecondBuf,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000256 bool FirstIsDestination) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000257 // If a previous check has failed, propagate the failure.
258 if (!state)
259 return NULL;
260
Ted Kremenek90af9092010-12-02 07:49:45 +0000261 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose134a2362010-07-06 23:11:01 +0000262 ASTContext &Ctx = C.getASTContext();
263
Ted Kremenek90af9092010-12-02 07:49:45 +0000264 QualType sizeTy = Size->getType();
Jordy Rose134a2362010-07-06 23:11:01 +0000265 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
266
Jordy Rose33c829a2010-07-07 07:48:06 +0000267 // Check that the first buffer is non-null.
268 SVal BufVal = state->getSVal(FirstBuf);
Ted Kremenek90af9092010-12-02 07:49:45 +0000269 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000270 if (!state)
271 return NULL;
272
Jordy Rosed5d2e502010-07-08 23:57:29 +0000273 // Get the access length and make sure it is known.
274 SVal LengthVal = state->getSVal(Size);
275 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
276 if (!Length)
277 return state;
278
Jordy Rose134a2362010-07-06 23:11:01 +0000279 // Compute the offset of the last element to be accessed: size-1.
Ted Kremenek90af9092010-12-02 07:49:45 +0000280 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
281 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
282 *Length, One, sizeTy));
Jordy Rose134a2362010-07-06 23:11:01 +0000283
Jordy Rose33c829a2010-07-07 07:48:06 +0000284 // Check that the first buffer is sufficently long.
Ted Kremenek90af9092010-12-02 07:49:45 +0000285 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
Jordy Roseafdb0532010-08-05 23:11:30 +0000286 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000287 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
288 LastOffset, PtrTy);
Jordy Rose722f5582010-08-16 07:51:42 +0000289 state = CheckLocation(C, state, FirstBuf, BufEnd, FirstIsDestination);
Jordy Rose134a2362010-07-06 23:11:01 +0000290
Jordy Roseafdb0532010-08-05 23:11:30 +0000291 // If the buffer isn't large enough, abort.
292 if (!state)
293 return NULL;
294 }
Jordy Rose134a2362010-07-06 23:11:01 +0000295
296 // If there's a second buffer, check it as well.
297 if (SecondBuf) {
298 BufVal = state->getSVal(SecondBuf);
Ted Kremenek90af9092010-12-02 07:49:45 +0000299 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000300 if (!state)
301 return NULL;
302
Ted Kremenek90af9092010-12-02 07:49:45 +0000303 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
Jordy Roseafdb0532010-08-05 23:11:30 +0000304 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000305 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
306 LastOffset, PtrTy);
Jordy Roseafdb0532010-08-05 23:11:30 +0000307 state = CheckLocation(C, state, SecondBuf, BufEnd);
308 }
Jordy Rose134a2362010-07-06 23:11:01 +0000309 }
310
311 // Large enough or not, return this state!
312 return state;
313}
314
315const GRState *CStringChecker::CheckOverlap(CheckerContext &C,
316 const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000317 const Expr *Size,
Jordy Rose134a2362010-07-06 23:11:01 +0000318 const Expr *First,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000319 const Expr *Second) const {
Jordy Rose134a2362010-07-06 23:11:01 +0000320 // Do a simple check for overlap: if the two arguments are from the same
321 // buffer, see if the end of the first is greater than the start of the second
322 // or vice versa.
323
Jordy Rosed5d2e502010-07-08 23:57:29 +0000324 // If a previous check has failed, propagate the failure.
325 if (!state)
326 return NULL;
327
Jordy Rose134a2362010-07-06 23:11:01 +0000328 const GRState *stateTrue, *stateFalse;
329
330 // Get the buffer values and make sure they're known locations.
Ted Kremenek90af9092010-12-02 07:49:45 +0000331 SVal firstVal = state->getSVal(First);
332 SVal secondVal = state->getSVal(Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000333
Ted Kremenek90af9092010-12-02 07:49:45 +0000334 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
335 if (!firstLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000336 return state;
337
Ted Kremenek90af9092010-12-02 07:49:45 +0000338 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
339 if (!secondLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000340 return state;
341
342 // Are the two values the same?
Ted Kremenek90af9092010-12-02 07:49:45 +0000343 SValBuilder &svalBuilder = C.getSValBuilder();
344 llvm::tie(stateTrue, stateFalse) =
345 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Rose134a2362010-07-06 23:11:01 +0000346
347 if (stateTrue && !stateFalse) {
348 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenek90af9092010-12-02 07:49:45 +0000349 emitOverlapBug(C, stateTrue, First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000350 return NULL;
351 }
352
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000353 // assume the two expressions are not equal.
Jordy Rose134a2362010-07-06 23:11:01 +0000354 assert(stateFalse);
355 state = stateFalse;
356
357 // Which value comes first?
Ted Kremenek90af9092010-12-02 07:49:45 +0000358 ASTContext &Ctx = svalBuilder.getContext();
359 QualType cmpTy = Ctx.IntTy;
360 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
361 *firstLoc, *secondLoc, cmpTy);
362 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
363 if (!reverseTest)
Jordy Rose134a2362010-07-06 23:11:01 +0000364 return state;
365
Ted Kremenek90af9092010-12-02 07:49:45 +0000366 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000367 if (stateTrue) {
368 if (stateFalse) {
369 // If we don't know which one comes first, we can't perform this test.
370 return state;
371 } else {
Ted Kremenek90af9092010-12-02 07:49:45 +0000372 // Switch the values so that firstVal is before secondVal.
373 Loc *tmpLoc = firstLoc;
374 firstLoc = secondLoc;
375 secondLoc = tmpLoc;
Jordy Rose134a2362010-07-06 23:11:01 +0000376
377 // Switch the Exprs as well, so that they still correspond.
378 const Expr *tmpExpr = First;
379 First = Second;
380 Second = tmpExpr;
381 }
382 }
383
384 // Get the length, and make sure it too is known.
385 SVal LengthVal = state->getSVal(Size);
386 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
387 if (!Length)
388 return state;
389
390 // Convert the first buffer's start address to char*.
391 // Bail out if the cast fails.
392 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Ted Kremenek90af9092010-12-02 07:49:45 +0000393 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy, First->getType());
Jordy Rose134a2362010-07-06 23:11:01 +0000394 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
395 if (!FirstStartLoc)
396 return state;
397
398 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenek90af9092010-12-02 07:49:45 +0000399 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Rose134a2362010-07-06 23:11:01 +0000400 *FirstStartLoc, *Length, CharPtrTy);
401 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
402 if (!FirstEndLoc)
403 return state;
404
405 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenek90af9092010-12-02 07:49:45 +0000406 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
407 *FirstEndLoc, *secondLoc, cmpTy);
Jordy Rose134a2362010-07-06 23:11:01 +0000408 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
409 if (!OverlapTest)
410 return state;
411
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000412 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000413
414 if (stateTrue && !stateFalse) {
415 // Overlap!
Ted Kremenek90af9092010-12-02 07:49:45 +0000416 emitOverlapBug(C, stateTrue, First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000417 return NULL;
418 }
419
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000420 // assume the two expressions don't overlap.
Jordy Rose134a2362010-07-06 23:11:01 +0000421 assert(stateFalse);
422 return stateFalse;
423}
424
Ted Kremenek90af9092010-12-02 07:49:45 +0000425void CStringChecker::emitOverlapBug(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000426 const Stmt *First, const Stmt *Second) const {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000427 ExplodedNode *N = C.generateSink(state);
Jordy Rose134a2362010-07-06 23:11:01 +0000428 if (!N)
429 return;
430
431 if (!BT_Overlap)
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000432 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
Jordy Rose134a2362010-07-06 23:11:01 +0000433
434 // Generate a report for this bug.
435 RangedBugReport *report =
436 new RangedBugReport(*BT_Overlap,
437 "Arguments must not be overlapping buffers", N);
438 report->addRange(First->getSourceRange());
439 report->addRange(Second->getSourceRange());
440
441 C.EmitReport(report);
442}
443
Ted Kremenek90af9092010-12-02 07:49:45 +0000444const GRState *CStringChecker::setCStringLength(const GRState *state,
Jordy Rose722f5582010-08-16 07:51:42 +0000445 const MemRegion *MR,
Ted Kremenek90af9092010-12-02 07:49:45 +0000446 SVal strLength) {
447 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
448 if (strLength.isUnknown())
Jordy Rose722f5582010-08-16 07:51:42 +0000449 return state;
450
451 MR = MR->StripCasts();
452
453 switch (MR->getKind()) {
454 case MemRegion::StringRegionKind:
455 // FIXME: This can happen if we strcpy() into a string region. This is
456 // undefined [C99 6.4.5p6], but we should still warn about it.
457 return state;
458
459 case MemRegion::SymbolicRegionKind:
460 case MemRegion::AllocaRegionKind:
461 case MemRegion::VarRegionKind:
462 case MemRegion::FieldRegionKind:
463 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek90af9092010-12-02 07:49:45 +0000464 return state->set<CStringLength>(MR, strLength);
Jordy Rose722f5582010-08-16 07:51:42 +0000465
466 case MemRegion::ElementRegionKind:
467 // FIXME: Handle element regions by upper-bounding the parent region's
468 // string length.
469 return state;
470
471 default:
472 // Other regions (mostly non-data) can't have a reliable C string length.
473 // For now, just ignore the change.
474 // FIXME: These are rare but not impossible. We should output some kind of
475 // warning for things like strcpy((char[]){'a', 0}, "b");
476 return state;
477 }
478}
479
Ted Kremenek90af9092010-12-02 07:49:45 +0000480SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000481 const GRState *&state,
482 const Expr *Ex,
483 const MemRegion *MR) {
484 // If there's a recorded length, go ahead and return it.
485 const SVal *Recorded = state->get<CStringLength>(MR);
486 if (Recorded)
487 return *Recorded;
488
489 // Otherwise, get a new symbol and update the state.
490 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000491 SValBuilder &svalBuilder = C.getSValBuilder();
492 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000493 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
494 MR, Ex, sizeTy, Count);
Ted Kremenek90af9092010-12-02 07:49:45 +0000495 state = state->set<CStringLength>(MR, strLength);
496 return strLength;
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000497}
498
Ted Kremenek90af9092010-12-02 07:49:45 +0000499SVal CStringChecker::getCStringLength(CheckerContext &C, const GRState *&state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000500 const Expr *Ex, SVal Buf) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000501 const MemRegion *MR = Buf.getAsRegion();
502 if (!MR) {
503 // If we can't get a region, see if it's something we /know/ isn't a
504 // C string. In the context of locations, the only time we can issue such
505 // a warning is for labels.
506 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000507 if (ExplodedNode *N = C.generateNode(state)) {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000508 if (!BT_NotCString)
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000509 BT_NotCString.reset(new BuiltinBug("API",
510 "Argument is not a null-terminated string."));
Jordy Roseb052e8f2010-07-27 01:37:31 +0000511
512 llvm::SmallString<120> buf;
513 llvm::raw_svector_ostream os(buf);
514 os << "Argument to byte string function is the address of the label '"
Chris Lattner5a9b1ec2011-02-17 05:38:27 +0000515 << Label->getLabel()->getName()
Jordy Roseb052e8f2010-07-27 01:37:31 +0000516 << "', which is not a null-terminated string";
517
518 // Generate a report for this bug.
519 EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
520 os.str(), N);
521
522 report->addRange(Ex->getSourceRange());
523 C.EmitReport(report);
524 }
525
526 return UndefinedVal();
527 }
528
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000529 // If it's not a region and not a label, give up.
530 return UnknownVal();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000531 }
532
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000533 // If we have a region, strip casts from it and see if we can figure out
534 // its length. For anything we can't figure out, just return UnknownVal.
535 MR = MR->StripCasts();
536
537 switch (MR->getKind()) {
538 case MemRegion::StringRegionKind: {
539 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
540 // so we can assume that the byte length is the correct C string length.
Ted Kremenek90af9092010-12-02 07:49:45 +0000541 SValBuilder &svalBuilder = C.getSValBuilder();
542 QualType sizeTy = svalBuilder.getContext().getSizeType();
543 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
544 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000545 }
546 case MemRegion::SymbolicRegionKind:
547 case MemRegion::AllocaRegionKind:
548 case MemRegion::VarRegionKind:
549 case MemRegion::FieldRegionKind:
550 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek90af9092010-12-02 07:49:45 +0000551 return getCStringLengthForRegion(C, state, Ex, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000552 case MemRegion::CompoundLiteralRegionKind:
553 // FIXME: Can we track this? Is it necessary?
554 return UnknownVal();
555 case MemRegion::ElementRegionKind:
556 // FIXME: How can we handle this? It's not good enough to subtract the
557 // offset from the base string length; consider "123\x00567" and &a[5].
558 return UnknownVal();
559 default:
560 // Other regions (mostly non-data) can't have a reliable C string length.
561 // In this case, an error is emitted and UndefinedVal is returned.
562 // The caller should always be prepared to handle this case.
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000563 if (ExplodedNode *N = C.generateNode(state)) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000564 if (!BT_NotCString)
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000565 BT_NotCString.reset(new BuiltinBug("API",
566 "Argument is not a null-terminated string."));
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000567
568 llvm::SmallString<120> buf;
569 llvm::raw_svector_ostream os(buf);
570
571 os << "Argument to byte string function is ";
572
573 if (SummarizeRegion(os, C.getASTContext(), MR))
574 os << ", which is not a null-terminated string";
575 else
576 os << "not a null-terminated string";
577
578 // Generate a report for this bug.
579 EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
580 os.str(), N);
581
582 report->addRange(Ex->getSourceRange());
583 C.EmitReport(report);
584 }
585
586 return UndefinedVal();
587 }
Jordy Roseb052e8f2010-07-27 01:37:31 +0000588}
589
Jordy Rose722f5582010-08-16 07:51:42 +0000590const GRState *CStringChecker::InvalidateBuffer(CheckerContext &C,
591 const GRState *state,
592 const Expr *E, SVal V) {
593 Loc *L = dyn_cast<Loc>(&V);
594 if (!L)
595 return state;
596
597 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
598 // some assumptions about the value that CFRefCount can't. Even so, it should
599 // probably be refactored.
600 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
601 const MemRegion *R = MR->getRegion()->StripCasts();
602
603 // Are we dealing with an ElementRegion? If so, we should be invalidating
604 // the super-region.
605 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
606 R = ER->getSuperRegion();
607 // FIXME: What about layers of ElementRegions?
608 }
609
610 // Invalidate this region.
611 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenekeddeba02011-02-11 19:48:15 +0000612 return state->invalidateRegion(R, E, Count, NULL);
Jordy Rose722f5582010-08-16 07:51:42 +0000613 }
614
615 // If we have a non-region value by chance, just remove the binding.
616 // FIXME: is this necessary or correct? This handles the non-Region
617 // cases. Is it ever valid to store to these?
618 return state->unbindLoc(*L);
619}
620
Jordy Roseb052e8f2010-07-27 01:37:31 +0000621bool CStringChecker::SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
622 const MemRegion *MR) {
623 const TypedRegion *TR = dyn_cast<TypedRegion>(MR);
624 if (!TR)
625 return false;
626
627 switch (TR->getKind()) {
628 case MemRegion::FunctionTextRegionKind: {
629 const FunctionDecl *FD = cast<FunctionTextRegion>(TR)->getDecl();
630 if (FD)
631 os << "the address of the function '" << FD << "'";
632 else
633 os << "the address of a function";
634 return true;
635 }
636 case MemRegion::BlockTextRegionKind:
637 os << "block text";
638 return true;
639 case MemRegion::BlockDataRegionKind:
640 os << "a block";
641 return true;
642 case MemRegion::CXXThisRegionKind:
Zhongxing Xu03207162010-11-26 08:52:48 +0000643 case MemRegion::CXXTempObjectRegionKind:
644 os << "a C++ temp object of type " << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000645 return true;
646 case MemRegion::VarRegionKind:
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000647 os << "a variable of type" << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000648 return true;
649 case MemRegion::FieldRegionKind:
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000650 os << "a field of type " << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000651 return true;
652 case MemRegion::ObjCIvarRegionKind:
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000653 os << "an instance variable of type " << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000654 return true;
655 default:
656 return false;
657 }
658}
659
Jordy Rosed5d2e502010-07-08 23:57:29 +0000660//===----------------------------------------------------------------------===//
Ted Kremenekdc891422010-12-01 21:57:22 +0000661// evaluation of individual function calls.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000662//===----------------------------------------------------------------------===//
663
Lenny Maiorani79d74142011-03-31 21:36:53 +0000664void CStringChecker::evalCopyCommon(CheckerContext &C,
665 const CallExpr *CE,
666 const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000667 const Expr *Size, const Expr *Dest,
Lenny Maiorani79d74142011-03-31 21:36:53 +0000668 const Expr *Source, bool Restricted,
669 bool IsMempcpy) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000670 // See if the size argument is zero.
Ted Kremenek90af9092010-12-02 07:49:45 +0000671 SVal sizeVal = state->getSVal(Size);
672 QualType sizeTy = Size->getType();
Jordy Rosed5d2e502010-07-08 23:57:29 +0000673
Ted Kremenek90af9092010-12-02 07:49:45 +0000674 const GRState *stateZeroSize, *stateNonZeroSize;
675 llvm::tie(stateZeroSize, stateNonZeroSize) = assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000676
Lenny Maiorani79d74142011-03-31 21:36:53 +0000677 // Get the value of the Dest.
678 SVal destVal = state->getSVal(Dest);
679
680 // If the size is zero, there won't be any actual memory access, so
681 // just bind the return value to the destination buffer and return.
682 if (stateZeroSize) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000683 C.addTransition(stateZeroSize);
Lenny Maiorani79d74142011-03-31 21:36:53 +0000684 if (IsMempcpy)
685 state->BindExpr(CE, destVal);
686 else
687 state->BindExpr(CE, sizeVal);
688 return;
689 }
Jordy Rosed5d2e502010-07-08 23:57:29 +0000690
691 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +0000692 if (stateNonZeroSize) {
Lenny Maiorani79d74142011-03-31 21:36:53 +0000693
694 // Ensure the destination is not null. If it is NULL there will be a
695 // NULL pointer dereference.
696 state = checkNonNull(C, state, Dest, destVal);
697 if (!state)
698 return;
699
700 // Get the value of the Src.
701 SVal srcVal = state->getSVal(Source);
702
703 // Ensure the source is not null. If it is NULL there will be a
704 // NULL pointer dereference.
705 state = checkNonNull(C, state, Source, srcVal);
706 if (!state)
707 return;
708
709 // Ensure the buffers do not overlap.
Ted Kremenek90af9092010-12-02 07:49:45 +0000710 state = stateNonZeroSize;
Jordy Rose722f5582010-08-16 07:51:42 +0000711 state = CheckBufferAccess(C, state, Size, Dest, Source,
712 /* FirstIsDst = */ true);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000713 if (Restricted)
714 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rose722f5582010-08-16 07:51:42 +0000715
716 if (state) {
Lenny Maiorani79d74142011-03-31 21:36:53 +0000717
718 // If this is mempcpy, get the byte after the last byte copied and
719 // bind the expr.
720 if (IsMempcpy) {
721 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
722
723 // Get the length to copy.
724 SVal lenVal = state->getSVal(Size);
725 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&lenVal);
726
727 // Get the byte after the last byte copied.
728 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
729 *destRegVal,
730 *lenValNonLoc,
731 Dest->getType());
732
733 // The byte after the last byte copied is the return value.
734 state = state->BindExpr(CE, lastElement);
735 }
736
Jordy Rose722f5582010-08-16 07:51:42 +0000737 // Invalidate the destination.
738 // FIXME: Even if we can't perfectly model the copy, we should see if we
739 // can use LazyCompoundVals to copy the source values into the destination.
740 // This would probably remove any existing bindings past the end of the
741 // copied region, but that's still an improvement over blank invalidation.
742 state = InvalidateBuffer(C, state, Dest, state->getSVal(Dest));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000743 C.addTransition(state);
Jordy Rose722f5582010-08-16 07:51:42 +0000744 }
Jordy Rosed5d2e502010-07-08 23:57:29 +0000745 }
746}
747
748
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000749void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose134a2362010-07-06 23:11:01 +0000750 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Rose134a2362010-07-06 23:11:01 +0000751 // The return value is the address of the destination buffer.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000752 const Expr *Dest = CE->getArg(0);
753 const GRState *state = C.getState();
754 state = state->BindExpr(CE, state->getSVal(Dest));
Lenny Maiorani79d74142011-03-31 21:36:53 +0000755 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
756}
757
758void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
759 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
760 // The return value is a pointer to the byte following the last written byte.
761 const Expr *Dest = CE->getArg(0);
762 const GRState *state = C.getState();
763
764 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Rose134a2362010-07-06 23:11:01 +0000765}
766
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000767void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000768 // void *memmove(void *dst, const void *src, size_t n);
769 // The return value is the address of the destination buffer.
770 const Expr *Dest = CE->getArg(0);
771 const GRState *state = C.getState();
772 state = state->BindExpr(CE, state->getSVal(Dest));
Lenny Maiorani79d74142011-03-31 21:36:53 +0000773 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000774}
775
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000776void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000777 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maiorani79d74142011-03-31 21:36:53 +0000778 evalCopyCommon(C, CE, C.getState(),
779 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000780}
781
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000782void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose65136fb2010-07-07 08:15:01 +0000783 // int memcmp(const void *s1, const void *s2, size_t n);
784 const Expr *Left = CE->getArg(0);
785 const Expr *Right = CE->getArg(1);
786 const Expr *Size = CE->getArg(2);
787
788 const GRState *state = C.getState();
Ted Kremenek90af9092010-12-02 07:49:45 +0000789 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose65136fb2010-07-07 08:15:01 +0000790
Jordy Rosed5d2e502010-07-08 23:57:29 +0000791 // See if the size argument is zero.
Ted Kremenek90af9092010-12-02 07:49:45 +0000792 SVal sizeVal = state->getSVal(Size);
793 QualType sizeTy = Size->getType();
Jordy Rose65136fb2010-07-07 08:15:01 +0000794
Ted Kremenek90af9092010-12-02 07:49:45 +0000795 const GRState *stateZeroSize, *stateNonZeroSize;
796 llvm::tie(stateZeroSize, stateNonZeroSize) =
797 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rose65136fb2010-07-07 08:15:01 +0000798
Jordy Rosed5d2e502010-07-08 23:57:29 +0000799 // If the size can be zero, the result will be 0 in that case, and we don't
800 // have to check either of the buffers.
Ted Kremenek90af9092010-12-02 07:49:45 +0000801 if (stateZeroSize) {
802 state = stateZeroSize;
803 state = state->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000804 C.addTransition(state);
Jordy Rose65136fb2010-07-07 08:15:01 +0000805 }
806
Jordy Rosed5d2e502010-07-08 23:57:29 +0000807 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +0000808 if (stateNonZeroSize) {
809 state = stateNonZeroSize;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000810 // If we know the two buffers are the same, we know the result is 0.
811 // First, get the two buffers' addresses. Another checker will have already
812 // made sure they're not undefined.
813 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(state->getSVal(Left));
814 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(state->getSVal(Right));
Jordy Rose65136fb2010-07-07 08:15:01 +0000815
Jordy Rosed5d2e502010-07-08 23:57:29 +0000816 // See if they are the same.
Ted Kremenek90af9092010-12-02 07:49:45 +0000817 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000818 const GRState *StSameBuf, *StNotSameBuf;
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000819 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000820
821 // If the two arguments might be the same buffer, we know the result is zero,
822 // and we only need to check one size.
823 if (StSameBuf) {
824 state = StSameBuf;
825 state = CheckBufferAccess(C, state, Size, Left);
826 if (state) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000827 state = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000828 C.addTransition(state);
829 }
830 }
831
832 // If the two arguments might be different buffers, we have to check the
833 // size of both of them.
834 if (StNotSameBuf) {
835 state = StNotSameBuf;
836 state = CheckBufferAccess(C, state, Size, Left, Right);
837 if (state) {
838 // The return value is the comparison result, which we don't know.
839 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000840 SVal CmpV = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000841 state = state->BindExpr(CE, CmpV);
842 C.addTransition(state);
843 }
844 }
845 }
Jordy Rose65136fb2010-07-07 08:15:01 +0000846}
847
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000848void CStringChecker::evalstrLength(CheckerContext &C,
849 const CallExpr *CE) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000850 // size_t strlen(const char *s);
Ted Kremenek280a01f2011-02-22 04:55:05 +0000851 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
852}
853
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000854void CStringChecker::evalstrnLength(CheckerContext &C,
855 const CallExpr *CE) const {
Ted Kremenek280a01f2011-02-22 04:55:05 +0000856 // size_t strnlen(const char *s, size_t maxlen);
857 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
858}
859
860void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000861 bool IsStrnlen) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000862 const GRState *state = C.getState();
863 const Expr *Arg = CE->getArg(0);
864 SVal ArgVal = state->getSVal(Arg);
865
866 // Check that the argument is non-null.
Ted Kremenek90af9092010-12-02 07:49:45 +0000867 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000868
869 if (state) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000870 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000871
872 // If the argument isn't a valid C string, there's no valid state to
873 // transition to.
Ted Kremenek90af9092010-12-02 07:49:45 +0000874 if (strLength.isUndef())
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000875 return;
876
Ted Kremenek280a01f2011-02-22 04:55:05 +0000877 // If the check is for strnlen() then bind the return value to no more than
878 // the maxlen value.
879 if (IsStrnlen) {
880 const Expr *maxlenExpr = CE->getArg(1);
881 SVal maxlenVal = state->getSVal(maxlenExpr);
882
883 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
884 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
885
886 QualType cmpTy = C.getSValBuilder().getContext().IntTy;
887 const GRState *stateTrue, *stateFalse;
888
889 // Check if the strLength is greater than or equal to the maxlen
890 llvm::tie(stateTrue, stateFalse) =
891 state->assume(cast<DefinedOrUnknownSVal>
892 (C.getSValBuilder().evalBinOpNN(state, BO_GE,
893 *strLengthNL, *maxlenValNL,
894 cmpTy)));
895
896 // If the strLength is greater than or equal to the maxlen, set strLength
897 // to maxlen
898 if (stateTrue && !stateFalse) {
899 strLength = maxlenVal;
900 }
901 }
902
Ted Kremenek90af9092010-12-02 07:49:45 +0000903 // If getCStringLength couldn't figure out the length, conjure a return
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000904 // value, so it can be used in constraints, at least.
Ted Kremenek90af9092010-12-02 07:49:45 +0000905 if (strLength.isUnknown()) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000906 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000907 strLength = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000908 }
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000909
910 // Bind the return value.
Ted Kremenek90af9092010-12-02 07:49:45 +0000911 state = state->BindExpr(CE, strLength);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000912 C.addTransition(state);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000913 }
914}
915
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000916void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose722f5582010-08-16 07:51:42 +0000917 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000918 evalStrcpyCommon(C, CE,
919 /* returnEnd = */ false,
920 /* isBounded = */ false,
921 /* isAppending = */ false);
Ted Kremenekfb1a79a2011-02-22 04:58:34 +0000922}
923
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000924void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenekfb1a79a2011-02-22 04:58:34 +0000925 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000926 evalStrcpyCommon(C, CE,
927 /* returnEnd = */ false,
928 /* isBounded = */ true,
929 /* isAppending = */ false);
Jordy Rose722f5582010-08-16 07:51:42 +0000930}
931
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000932void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose722f5582010-08-16 07:51:42 +0000933 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000934 evalStrcpyCommon(C, CE,
935 /* returnEnd = */ true,
936 /* isBounded = */ false,
937 /* isAppending = */ false);
938}
939
940void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
941 //char *strcat(char *restrict s1, const char *restrict s2);
942 evalStrcpyCommon(C, CE,
943 /* returnEnd = */ false,
944 /* isBounded = */ false,
945 /* isAppending = */ true);
946}
947
948void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
949 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
950 evalStrcpyCommon(C, CE,
951 /* returnEnd = */ false,
952 /* isBounded = */ true,
953 /* isAppending = */ true);
Jordy Rose722f5582010-08-16 07:51:42 +0000954}
955
Ted Kremenekdc891422010-12-01 21:57:22 +0000956void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000957 bool returnEnd, bool isBounded,
958 bool isAppending) const {
Jordy Rose722f5582010-08-16 07:51:42 +0000959 const GRState *state = C.getState();
960
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000961 // Check that the destination is non-null.
Jordy Rose722f5582010-08-16 07:51:42 +0000962 const Expr *Dst = CE->getArg(0);
963 SVal DstVal = state->getSVal(Dst);
964
Ted Kremenek90af9092010-12-02 07:49:45 +0000965 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +0000966 if (!state)
967 return;
968
969 // Check that the source is non-null.
Ted Kremenek90af9092010-12-02 07:49:45 +0000970 const Expr *srcExpr = CE->getArg(1);
971 SVal srcVal = state->getSVal(srcExpr);
972 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +0000973 if (!state)
974 return;
975
976 // Get the string length of the source.
Ted Kremenek90af9092010-12-02 07:49:45 +0000977 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +0000978
979 // If the source isn't a valid C string, give up.
Ted Kremenek90af9092010-12-02 07:49:45 +0000980 if (strLength.isUndef())
Jordy Rose722f5582010-08-16 07:51:42 +0000981 return;
982
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000983 // If the function is strncpy, strncat, etc... it is bounded.
984 if (isBounded) {
985 // Get the max number of characters to copy.
Ted Kremenekfb1a79a2011-02-22 04:58:34 +0000986 const Expr *lenExpr = CE->getArg(2);
987 SVal lenVal = state->getSVal(lenExpr);
988
989 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
990 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
991
992 QualType cmpTy = C.getSValBuilder().getContext().IntTy;
993 const GRState *stateTrue, *stateFalse;
994
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000995 // Check if the max number to copy is less than the length of the src.
Ted Kremenekfb1a79a2011-02-22 04:58:34 +0000996 llvm::tie(stateTrue, stateFalse) =
997 state->assume(cast<DefinedOrUnknownSVal>
998 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
999 *strLengthNL, *lenValNL,
1000 cmpTy)));
1001
1002 if (stateTrue) {
1003 // Max number to copy is less than the length of the src, so the actual
1004 // strLength copied is the max number arg.
1005 strLength = lenVal;
1006 }
1007 }
1008
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001009 // If this is an appending function (strcat, strncat...) then set the
1010 // string length to strlen(src) + strlen(dst) since the buffer will
1011 // ultimately contain both.
1012 if (isAppending) {
1013 // Get the string length of the destination, or give up.
1014 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1015 if (dstStrLength.isUndef())
1016 return;
1017
1018 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&strLength);
1019 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1020
1021 // If src or dst cast to NonLoc is NULL, give up.
1022 if ((!srcStrLengthNL) || (!dstStrLengthNL))
1023 return;
1024
1025 QualType addTy = C.getSValBuilder().getContext().getSizeType();
1026
1027 strLength = C.getSValBuilder().evalBinOpNN(state, BO_Add,
1028 *srcStrLengthNL, *dstStrLengthNL,
1029 addTy);
1030 }
1031
Ted Kremenek90af9092010-12-02 07:49:45 +00001032 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001033
1034 // If the destination is a MemRegion, try to check for a buffer overflow and
1035 // record the new string length.
Ted Kremenek90af9092010-12-02 07:49:45 +00001036 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rose722f5582010-08-16 07:51:42 +00001037 // If the length is known, we can check for an overflow.
Ted Kremenek90af9092010-12-02 07:49:45 +00001038 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&strLength)) {
1039 SVal lastElement =
1040 C.getSValBuilder().evalBinOpLN(state, BO_Add, *dstRegVal,
1041 *knownStrLength, Dst->getType());
Jordy Rose722f5582010-08-16 07:51:42 +00001042
Ted Kremenek90af9092010-12-02 07:49:45 +00001043 state = CheckLocation(C, state, Dst, lastElement, /* IsDst = */ true);
Jordy Rose722f5582010-08-16 07:51:42 +00001044 if (!state)
1045 return;
1046
1047 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001048 if (returnEnd)
1049 Result = lastElement;
Jordy Rose722f5582010-08-16 07:51:42 +00001050 }
1051
1052 // Invalidate the destination. This must happen before we set the C string
1053 // length because invalidation will clear the length.
1054 // FIXME: Even if we can't perfectly model the copy, we should see if we
1055 // can use LazyCompoundVals to copy the source values into the destination.
1056 // This would probably remove any existing bindings past the end of the
1057 // string, but that's still an improvement over blank invalidation.
Ted Kremenek90af9092010-12-02 07:49:45 +00001058 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001059
1060 // Set the C string length of the destination.
Ted Kremenek90af9092010-12-02 07:49:45 +00001061 state = setCStringLength(state, dstRegVal->getRegion(), strLength);
Jordy Rose722f5582010-08-16 07:51:42 +00001062 }
1063
1064 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1065 // overflow, we still need a result. Conjure a return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001066 if (returnEnd && Result.isUnknown()) {
1067 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose722f5582010-08-16 07:51:42 +00001068 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +00001069 strLength = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rose722f5582010-08-16 07:51:42 +00001070 }
1071
1072 // Set the return value.
1073 state = state->BindExpr(CE, Result);
1074 C.addTransition(state);
1075}
1076
Jordy Rosed5d2e502010-07-08 23:57:29 +00001077//===----------------------------------------------------------------------===//
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001078// The driver method, and other Checker callbacks.
Jordy Rosed5d2e502010-07-08 23:57:29 +00001079//===----------------------------------------------------------------------===//
Jordy Rose134a2362010-07-06 23:11:01 +00001080
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001081bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose134a2362010-07-06 23:11:01 +00001082 // Get the callee. All the functions we care about are C functions
1083 // with simple identifiers.
1084 const GRState *state = C.getState();
1085 const Expr *Callee = CE->getCallee();
1086 const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl();
1087
1088 if (!FD)
1089 return false;
1090
1091 // Get the name of the callee. If it's a builtin, strip off the prefix.
Douglas Gregor4b8eca82010-11-01 23:16:05 +00001092 IdentifierInfo *II = FD->getIdentifier();
1093 if (!II) // if no identifier, not a simple C function
1094 return false;
1095 llvm::StringRef Name = II->getName();
Jordy Rose134a2362010-07-06 23:11:01 +00001096 if (Name.startswith("__builtin_"))
1097 Name = Name.substr(10);
1098
Ted Kremenekdc891422010-12-01 21:57:22 +00001099 FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
1100 .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
Lenny Maiorani79d74142011-03-31 21:36:53 +00001101 .Case("mempcpy", &CStringChecker::evalMempcpy)
Ted Kremenekdc891422010-12-01 21:57:22 +00001102 .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
1103 .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
1104 .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001105 .Cases("strncpy", "__strncpy_chk", &CStringChecker::evalStrncpy)
Ted Kremenekdc891422010-12-01 21:57:22 +00001106 .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001107 .Cases("strcat", "__strcat_chk", &CStringChecker::evalStrcat)
1108 .Cases("strncat", "__strncat_chk", &CStringChecker::evalStrncat)
Ted Kremenek90af9092010-12-02 07:49:45 +00001109 .Case("strlen", &CStringChecker::evalstrLength)
Ted Kremenek280a01f2011-02-22 04:55:05 +00001110 .Case("strnlen", &CStringChecker::evalstrnLength)
Ted Kremenekdc891422010-12-01 21:57:22 +00001111 .Case("bcopy", &CStringChecker::evalBcopy)
Jordy Rose134a2362010-07-06 23:11:01 +00001112 .Default(NULL);
1113
Jordy Rosed5d2e502010-07-08 23:57:29 +00001114 // If the callee isn't a string function, let another checker handle it.
Ted Kremenekdc891422010-12-01 21:57:22 +00001115 if (!evalFunction)
Jordy Rose134a2362010-07-06 23:11:01 +00001116 return false;
1117
Jordy Rosed5d2e502010-07-08 23:57:29 +00001118 // Check and evaluate the call.
Ted Kremenekdc891422010-12-01 21:57:22 +00001119 (this->*evalFunction)(C, CE);
Jordy Rose134a2362010-07-06 23:11:01 +00001120 return true;
1121}
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001122
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001123void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001124 // Record string length for char a[] = "abc";
1125 const GRState *state = C.getState();
1126
1127 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1128 I != E; ++I) {
1129 const VarDecl *D = dyn_cast<VarDecl>(*I);
1130 if (!D)
1131 continue;
1132
1133 // FIXME: Handle array fields of structs.
1134 if (!D->getType()->isArrayType())
1135 continue;
1136
1137 const Expr *Init = D->getInit();
1138 if (!Init)
1139 continue;
1140 if (!isa<StringLiteral>(Init))
1141 continue;
1142
1143 Loc VarLoc = state->getLValue(D, C.getPredecessor()->getLocationContext());
1144 const MemRegion *MR = VarLoc.getAsRegion();
1145 if (!MR)
1146 continue;
1147
1148 SVal StrVal = state->getSVal(Init);
1149 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenek90af9092010-12-02 07:49:45 +00001150 DefinedOrUnknownSVal strLength
1151 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001152
Ted Kremenek90af9092010-12-02 07:49:45 +00001153 state = state->set<CStringLength>(MR, strLength);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001154 }
1155
1156 C.addTransition(state);
1157}
1158
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001159bool CStringChecker::wantsRegionChangeUpdate(const GRState *state) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001160 CStringLength::EntryMap Entries = state->get<CStringLength>();
1161 return !Entries.isEmpty();
1162}
1163
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001164const GRState *
1165CStringChecker::checkRegionChanges(const GRState *state,
1166 const MemRegion * const *Begin,
1167 const MemRegion * const *End) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001168 CStringLength::EntryMap Entries = state->get<CStringLength>();
1169 if (Entries.isEmpty())
1170 return state;
1171
1172 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1173 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1174
1175 // First build sets for the changed regions and their super-regions.
1176 for ( ; Begin != End; ++Begin) {
1177 const MemRegion *MR = *Begin;
1178 Invalidated.insert(MR);
1179
1180 SuperRegions.insert(MR);
1181 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1182 MR = SR->getSuperRegion();
1183 SuperRegions.insert(MR);
1184 }
1185 }
1186
1187 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1188
1189 // Then loop over the entries in the current state.
1190 for (CStringLength::EntryMap::iterator I = Entries.begin(),
1191 E = Entries.end(); I != E; ++I) {
1192 const MemRegion *MR = I.getKey();
1193
1194 // Is this entry for a super-region of a changed region?
1195 if (SuperRegions.count(MR)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001196 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001197 continue;
1198 }
1199
1200 // Is this entry for a sub-region of a changed region?
1201 const MemRegion *Super = MR;
1202 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1203 Super = SR->getSuperRegion();
1204 if (Invalidated.count(Super)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001205 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001206 break;
1207 }
1208 }
1209 }
1210
1211 return state->set<CStringLength>(Entries);
1212}
1213
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001214void CStringChecker::checkLiveSymbols(const GRState *state,
1215 SymbolReaper &SR) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001216 // Mark all symbols in our string length map as valid.
1217 CStringLength::EntryMap Entries = state->get<CStringLength>();
1218
1219 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1220 I != E; ++I) {
1221 SVal Len = I.getData();
1222 if (SymbolRef Sym = Len.getAsSymbol())
1223 SR.markInUse(Sym);
1224 }
1225}
1226
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001227void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1228 CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001229 if (!SR.hasDeadSymbols())
1230 return;
1231
1232 const GRState *state = C.getState();
1233 CStringLength::EntryMap Entries = state->get<CStringLength>();
1234 if (Entries.isEmpty())
1235 return;
1236
1237 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1238 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1239 I != E; ++I) {
1240 SVal Len = I.getData();
1241 if (SymbolRef Sym = Len.getAsSymbol()) {
1242 if (SR.isDead(Sym))
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001243 Entries = F.remove(Entries, I.getKey());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001244 }
1245 }
1246
1247 state = state->set<CStringLength>(Entries);
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001248 C.generateNode(state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001249}
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001250
1251void ento::registerCStringChecker(CheckerManager &mgr) {
1252 mgr.registerChecker<CStringChecker>();
1253}