blob: 46f9e6e565d16816b29339a928cd954b2a1afd33 [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
Lenny Maioranif3539ad2011-04-12 17:08:43 +000077 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
78
Jordy Rose134a2362010-07-06 23:11:01 +000079 // Utility methods
Jordy Rosed5d2e502010-07-08 23:57:29 +000080 std::pair<const GRState*, const GRState*>
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000081 static assumeZero(CheckerContext &C,
82 const GRState *state, SVal V, QualType Ty);
Jordy Rosed5d2e502010-07-08 23:57:29 +000083
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000084 static const GRState *setCStringLength(const GRState *state,
85 const MemRegion *MR, SVal strLength);
86 static SVal getCStringLengthForRegion(CheckerContext &C,
87 const GRState *&state,
88 const Expr *Ex, const MemRegion *MR);
Ted Kremenek90af9092010-12-02 07:49:45 +000089 SVal getCStringLength(CheckerContext &C, const GRState *&state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000090 const Expr *Ex, SVal Buf) const;
Jordy Roseb052e8f2010-07-27 01:37:31 +000091
Lenny Maioranif3539ad2011-04-12 17:08:43 +000092 const StringLiteral *getCStringLiteral(CheckerContext &C,
93 const GRState *&state,
94 const Expr *expr,
95 SVal val) const;
96
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000097 static const GRState *InvalidateBuffer(CheckerContext &C,
98 const GRState *state,
99 const Expr *Ex, SVal V);
Jordy Rose722f5582010-08-16 07:51:42 +0000100
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000101 static bool SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
102 const MemRegion *MR);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000103
104 // Re-usable checks
Ted Kremenek90af9092010-12-02 07:49:45 +0000105 const GRState *checkNonNull(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000106 const Expr *S, SVal l) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000107 const GRState *CheckLocation(CheckerContext &C, const GRState *state,
Jordy Rose722f5582010-08-16 07:51:42 +0000108 const Expr *S, SVal l,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000109 bool IsDestination = false) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000110 const GRState *CheckBufferAccess(CheckerContext &C, const GRState *state,
111 const Expr *Size,
112 const Expr *FirstBuf,
Jordy Rose722f5582010-08-16 07:51:42 +0000113 const Expr *SecondBuf = NULL,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000114 bool FirstIsDestination = false) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000115 const GRState *CheckOverlap(CheckerContext &C, const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000116 const Expr *Size, const Expr *First,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000117 const Expr *Second) const;
Ted Kremenek90af9092010-12-02 07:49:45 +0000118 void emitOverlapBug(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000119 const Stmt *First, const Stmt *Second) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000120};
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000121
122class CStringLength {
123public:
124 typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
125};
Jordy Rose134a2362010-07-06 23:11:01 +0000126} //end anonymous namespace
127
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000128namespace clang {
Ted Kremenek98857c92010-12-23 07:20:52 +0000129namespace ento {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000130 template <>
131 struct GRStateTrait<CStringLength>
132 : public GRStatePartialTrait<CStringLength::EntryMap> {
133 static void *GDMIndex() { return CStringChecker::getTag(); }
134 };
135}
Argyrios Kyrtzidisca08fba2010-12-22 18:53:20 +0000136}
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000137
Jordy Rosed5d2e502010-07-08 23:57:29 +0000138//===----------------------------------------------------------------------===//
139// Individual checks and utility methods.
140//===----------------------------------------------------------------------===//
141
142std::pair<const GRState*, const GRState*>
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000143CStringChecker::assumeZero(CheckerContext &C, const GRState *state, SVal V,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000144 QualType Ty) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000145 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
146 if (!val)
Jordy Rosed5d2e502010-07-08 23:57:29 +0000147 return std::pair<const GRState*, const GRState *>(state, state);
Jordy Rose33c829a2010-07-07 07:48:06 +0000148
Ted Kremenek90af9092010-12-02 07:49:45 +0000149 SValBuilder &svalBuilder = C.getSValBuilder();
150 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
151 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000152}
Jordy Rose33c829a2010-07-07 07:48:06 +0000153
Ted Kremenek90af9092010-12-02 07:49:45 +0000154const GRState *CStringChecker::checkNonNull(CheckerContext &C,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000155 const GRState *state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000156 const Expr *S, SVal l) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000157 // If a previous check has failed, propagate the failure.
158 if (!state)
159 return NULL;
160
161 const GRState *stateNull, *stateNonNull;
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000162 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed5d2e502010-07-08 23:57:29 +0000163
164 if (stateNull && !stateNonNull) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000165 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rose33c829a2010-07-07 07:48:06 +0000166 if (!N)
167 return NULL;
168
Jordy Rosed5d2e502010-07-08 23:57:29 +0000169 if (!BT_Null)
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000170 BT_Null.reset(new BuiltinBug("API",
171 "Null pointer argument in call to byte string function"));
Jordy Rose33c829a2010-07-07 07:48:06 +0000172
173 // Generate a report for this bug.
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000174 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Jordy Rose33c829a2010-07-07 07:48:06 +0000175 EnhancedBugReport *report = new EnhancedBugReport(*BT,
176 BT->getDescription(), N);
177
178 report->addRange(S->getSourceRange());
179 report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, S);
180 C.EmitReport(report);
181 return NULL;
182 }
183
184 // From here on, assume that the value is non-null.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000185 assert(stateNonNull);
186 return stateNonNull;
Jordy Rose33c829a2010-07-07 07:48:06 +0000187}
188
Jordy Rose134a2362010-07-06 23:11:01 +0000189// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
190const GRState *CStringChecker::CheckLocation(CheckerContext &C,
191 const GRState *state,
Jordy Rose722f5582010-08-16 07:51:42 +0000192 const Expr *S, SVal l,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000193 bool IsDestination) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000194 // If a previous check has failed, propagate the failure.
195 if (!state)
196 return NULL;
197
Jordy Rose134a2362010-07-06 23:11:01 +0000198 // Check for out of bound array element access.
199 const MemRegion *R = l.getAsRegion();
200 if (!R)
201 return state;
202
Jordy Rose134a2362010-07-06 23:11:01 +0000203 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
204 if (!ER)
205 return state;
206
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000207 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Rose134a2362010-07-06 23:11:01 +0000208 "CheckLocation should only be called with char* ElementRegions");
209
210 // Get the size of the array.
Ted Kremenek90af9092010-12-02 07:49:45 +0000211 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
212 SValBuilder &svalBuilder = C.getSValBuilder();
213 SVal Extent = svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
Jordy Rose134a2362010-07-06 23:11:01 +0000214 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
215
216 // Get the index of the accessed element.
Gabor Greif230ddf32010-09-09 10:51:37 +0000217 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
Jordy Rose134a2362010-07-06 23:11:01 +0000218
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000219 const GRState *StInBound = state->assumeInBound(Idx, Size, true);
220 const GRState *StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Rose134a2362010-07-06 23:11:01 +0000221 if (StOutBound && !StInBound) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000222 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Rose134a2362010-07-06 23:11:01 +0000223 if (!N)
224 return NULL;
225
Jordy Rose722f5582010-08-16 07:51:42 +0000226 BuiltinBug *BT;
227 if (IsDestination) {
228 if (!BT_BoundsWrite) {
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000229 BT_BoundsWrite.reset(new BuiltinBug("Out-of-bound array access",
230 "Byte string function overflows destination buffer"));
Jordy Rose722f5582010-08-16 07:51:42 +0000231 }
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000232 BT = static_cast<BuiltinBug*>(BT_BoundsWrite.get());
Jordy Rose722f5582010-08-16 07:51:42 +0000233 } else {
234 if (!BT_Bounds) {
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000235 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
236 "Byte string function accesses out-of-bound array element"));
Jordy Rose722f5582010-08-16 07:51:42 +0000237 }
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000238 BT = static_cast<BuiltinBug*>(BT_Bounds.get());
Jordy Rose722f5582010-08-16 07:51:42 +0000239 }
Jordy Rose134a2362010-07-06 23:11:01 +0000240
241 // FIXME: It would be nice to eventually make this diagnostic more clear,
242 // e.g., by referencing the original declaration or by saying *why* this
243 // reference is outside the range.
244
245 // Generate a report for this bug.
Jordy Rose134a2362010-07-06 23:11:01 +0000246 RangedBugReport *report = new RangedBugReport(*BT, BT->getDescription(), N);
247
248 report->addRange(S->getSourceRange());
249 C.EmitReport(report);
250 return NULL;
251 }
252
253 // Array bound check succeeded. From this point forward the array bound
254 // should always succeed.
255 return StInBound;
256}
257
258const GRState *CStringChecker::CheckBufferAccess(CheckerContext &C,
259 const GRState *state,
260 const Expr *Size,
261 const Expr *FirstBuf,
Jordy Rose722f5582010-08-16 07:51:42 +0000262 const Expr *SecondBuf,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000263 bool FirstIsDestination) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000264 // If a previous check has failed, propagate the failure.
265 if (!state)
266 return NULL;
267
Ted Kremenek90af9092010-12-02 07:49:45 +0000268 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose134a2362010-07-06 23:11:01 +0000269 ASTContext &Ctx = C.getASTContext();
270
Ted Kremenek90af9092010-12-02 07:49:45 +0000271 QualType sizeTy = Size->getType();
Jordy Rose134a2362010-07-06 23:11:01 +0000272 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
273
Jordy Rose33c829a2010-07-07 07:48:06 +0000274 // Check that the first buffer is non-null.
275 SVal BufVal = state->getSVal(FirstBuf);
Ted Kremenek90af9092010-12-02 07:49:45 +0000276 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000277 if (!state)
278 return NULL;
279
Jordy Rosed5d2e502010-07-08 23:57:29 +0000280 // Get the access length and make sure it is known.
281 SVal LengthVal = state->getSVal(Size);
282 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
283 if (!Length)
284 return state;
285
Jordy Rose134a2362010-07-06 23:11:01 +0000286 // Compute the offset of the last element to be accessed: size-1.
Ted Kremenek90af9092010-12-02 07:49:45 +0000287 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
288 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
289 *Length, One, sizeTy));
Jordy Rose134a2362010-07-06 23:11:01 +0000290
Chris Lattner57540c52011-04-15 05:22:18 +0000291 // Check that the first buffer is sufficiently long.
Ted Kremenek90af9092010-12-02 07:49:45 +0000292 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
Jordy Roseafdb0532010-08-05 23:11:30 +0000293 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000294 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
295 LastOffset, PtrTy);
Jordy Rose722f5582010-08-16 07:51:42 +0000296 state = CheckLocation(C, state, FirstBuf, BufEnd, FirstIsDestination);
Jordy Rose134a2362010-07-06 23:11:01 +0000297
Jordy Roseafdb0532010-08-05 23:11:30 +0000298 // If the buffer isn't large enough, abort.
299 if (!state)
300 return NULL;
301 }
Jordy Rose134a2362010-07-06 23:11:01 +0000302
303 // If there's a second buffer, check it as well.
304 if (SecondBuf) {
305 BufVal = state->getSVal(SecondBuf);
Ted Kremenek90af9092010-12-02 07:49:45 +0000306 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000307 if (!state)
308 return NULL;
309
Ted Kremenek90af9092010-12-02 07:49:45 +0000310 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
Jordy Roseafdb0532010-08-05 23:11:30 +0000311 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000312 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
313 LastOffset, PtrTy);
Jordy Roseafdb0532010-08-05 23:11:30 +0000314 state = CheckLocation(C, state, SecondBuf, BufEnd);
315 }
Jordy Rose134a2362010-07-06 23:11:01 +0000316 }
317
318 // Large enough or not, return this state!
319 return state;
320}
321
322const GRState *CStringChecker::CheckOverlap(CheckerContext &C,
323 const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000324 const Expr *Size,
Jordy Rose134a2362010-07-06 23:11:01 +0000325 const Expr *First,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000326 const Expr *Second) const {
Jordy Rose134a2362010-07-06 23:11:01 +0000327 // Do a simple check for overlap: if the two arguments are from the same
328 // buffer, see if the end of the first is greater than the start of the second
329 // or vice versa.
330
Jordy Rosed5d2e502010-07-08 23:57:29 +0000331 // If a previous check has failed, propagate the failure.
332 if (!state)
333 return NULL;
334
Jordy Rose134a2362010-07-06 23:11:01 +0000335 const GRState *stateTrue, *stateFalse;
336
337 // Get the buffer values and make sure they're known locations.
Ted Kremenek90af9092010-12-02 07:49:45 +0000338 SVal firstVal = state->getSVal(First);
339 SVal secondVal = state->getSVal(Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000340
Ted Kremenek90af9092010-12-02 07:49:45 +0000341 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
342 if (!firstLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000343 return state;
344
Ted Kremenek90af9092010-12-02 07:49:45 +0000345 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
346 if (!secondLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000347 return state;
348
349 // Are the two values the same?
Ted Kremenek90af9092010-12-02 07:49:45 +0000350 SValBuilder &svalBuilder = C.getSValBuilder();
351 llvm::tie(stateTrue, stateFalse) =
352 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Rose134a2362010-07-06 23:11:01 +0000353
354 if (stateTrue && !stateFalse) {
355 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenek90af9092010-12-02 07:49:45 +0000356 emitOverlapBug(C, stateTrue, First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000357 return NULL;
358 }
359
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000360 // assume the two expressions are not equal.
Jordy Rose134a2362010-07-06 23:11:01 +0000361 assert(stateFalse);
362 state = stateFalse;
363
364 // Which value comes first?
Ted Kremenek90af9092010-12-02 07:49:45 +0000365 ASTContext &Ctx = svalBuilder.getContext();
366 QualType cmpTy = Ctx.IntTy;
367 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
368 *firstLoc, *secondLoc, cmpTy);
369 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
370 if (!reverseTest)
Jordy Rose134a2362010-07-06 23:11:01 +0000371 return state;
372
Ted Kremenek90af9092010-12-02 07:49:45 +0000373 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000374 if (stateTrue) {
375 if (stateFalse) {
376 // If we don't know which one comes first, we can't perform this test.
377 return state;
378 } else {
Ted Kremenek90af9092010-12-02 07:49:45 +0000379 // Switch the values so that firstVal is before secondVal.
380 Loc *tmpLoc = firstLoc;
381 firstLoc = secondLoc;
382 secondLoc = tmpLoc;
Jordy Rose134a2362010-07-06 23:11:01 +0000383
384 // Switch the Exprs as well, so that they still correspond.
385 const Expr *tmpExpr = First;
386 First = Second;
387 Second = tmpExpr;
388 }
389 }
390
391 // Get the length, and make sure it too is known.
392 SVal LengthVal = state->getSVal(Size);
393 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
394 if (!Length)
395 return state;
396
397 // Convert the first buffer's start address to char*.
398 // Bail out if the cast fails.
399 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Ted Kremenek90af9092010-12-02 07:49:45 +0000400 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy, First->getType());
Jordy Rose134a2362010-07-06 23:11:01 +0000401 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
402 if (!FirstStartLoc)
403 return state;
404
405 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenek90af9092010-12-02 07:49:45 +0000406 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Rose134a2362010-07-06 23:11:01 +0000407 *FirstStartLoc, *Length, CharPtrTy);
408 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
409 if (!FirstEndLoc)
410 return state;
411
412 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenek90af9092010-12-02 07:49:45 +0000413 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
414 *FirstEndLoc, *secondLoc, cmpTy);
Jordy Rose134a2362010-07-06 23:11:01 +0000415 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
416 if (!OverlapTest)
417 return state;
418
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000419 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000420
421 if (stateTrue && !stateFalse) {
422 // Overlap!
Ted Kremenek90af9092010-12-02 07:49:45 +0000423 emitOverlapBug(C, stateTrue, First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000424 return NULL;
425 }
426
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000427 // assume the two expressions don't overlap.
Jordy Rose134a2362010-07-06 23:11:01 +0000428 assert(stateFalse);
429 return stateFalse;
430}
431
Ted Kremenek90af9092010-12-02 07:49:45 +0000432void CStringChecker::emitOverlapBug(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000433 const Stmt *First, const Stmt *Second) const {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000434 ExplodedNode *N = C.generateSink(state);
Jordy Rose134a2362010-07-06 23:11:01 +0000435 if (!N)
436 return;
437
438 if (!BT_Overlap)
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000439 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
Jordy Rose134a2362010-07-06 23:11:01 +0000440
441 // Generate a report for this bug.
442 RangedBugReport *report =
443 new RangedBugReport(*BT_Overlap,
444 "Arguments must not be overlapping buffers", N);
445 report->addRange(First->getSourceRange());
446 report->addRange(Second->getSourceRange());
447
448 C.EmitReport(report);
449}
450
Ted Kremenek90af9092010-12-02 07:49:45 +0000451const GRState *CStringChecker::setCStringLength(const GRState *state,
Jordy Rose722f5582010-08-16 07:51:42 +0000452 const MemRegion *MR,
Ted Kremenek90af9092010-12-02 07:49:45 +0000453 SVal strLength) {
454 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
455 if (strLength.isUnknown())
Jordy Rose722f5582010-08-16 07:51:42 +0000456 return state;
457
458 MR = MR->StripCasts();
459
460 switch (MR->getKind()) {
461 case MemRegion::StringRegionKind:
462 // FIXME: This can happen if we strcpy() into a string region. This is
463 // undefined [C99 6.4.5p6], but we should still warn about it.
464 return state;
465
466 case MemRegion::SymbolicRegionKind:
467 case MemRegion::AllocaRegionKind:
468 case MemRegion::VarRegionKind:
469 case MemRegion::FieldRegionKind:
470 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek90af9092010-12-02 07:49:45 +0000471 return state->set<CStringLength>(MR, strLength);
Jordy Rose722f5582010-08-16 07:51:42 +0000472
473 case MemRegion::ElementRegionKind:
474 // FIXME: Handle element regions by upper-bounding the parent region's
475 // string length.
476 return state;
477
478 default:
479 // Other regions (mostly non-data) can't have a reliable C string length.
480 // For now, just ignore the change.
481 // FIXME: These are rare but not impossible. We should output some kind of
482 // warning for things like strcpy((char[]){'a', 0}, "b");
483 return state;
484 }
485}
486
Ted Kremenek90af9092010-12-02 07:49:45 +0000487SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000488 const GRState *&state,
489 const Expr *Ex,
490 const MemRegion *MR) {
491 // If there's a recorded length, go ahead and return it.
492 const SVal *Recorded = state->get<CStringLength>(MR);
493 if (Recorded)
494 return *Recorded;
495
496 // Otherwise, get a new symbol and update the state.
497 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000498 SValBuilder &svalBuilder = C.getSValBuilder();
499 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000500 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
501 MR, Ex, sizeTy, Count);
Ted Kremenek90af9092010-12-02 07:49:45 +0000502 state = state->set<CStringLength>(MR, strLength);
503 return strLength;
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000504}
505
Ted Kremenek90af9092010-12-02 07:49:45 +0000506SVal CStringChecker::getCStringLength(CheckerContext &C, const GRState *&state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000507 const Expr *Ex, SVal Buf) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000508 const MemRegion *MR = Buf.getAsRegion();
509 if (!MR) {
510 // If we can't get a region, see if it's something we /know/ isn't a
511 // C string. In the context of locations, the only time we can issue such
512 // a warning is for labels.
513 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000514 if (ExplodedNode *N = C.generateNode(state)) {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000515 if (!BT_NotCString)
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000516 BT_NotCString.reset(new BuiltinBug("API",
517 "Argument is not a null-terminated string."));
Jordy Roseb052e8f2010-07-27 01:37:31 +0000518
519 llvm::SmallString<120> buf;
520 llvm::raw_svector_ostream os(buf);
521 os << "Argument to byte string function is the address of the label '"
Chris Lattner5a9b1ec2011-02-17 05:38:27 +0000522 << Label->getLabel()->getName()
Jordy Roseb052e8f2010-07-27 01:37:31 +0000523 << "', which is not a null-terminated string";
524
525 // Generate a report for this bug.
526 EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
527 os.str(), N);
528
529 report->addRange(Ex->getSourceRange());
530 C.EmitReport(report);
531 }
532
533 return UndefinedVal();
534 }
535
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000536 // If it's not a region and not a label, give up.
537 return UnknownVal();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000538 }
539
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000540 // If we have a region, strip casts from it and see if we can figure out
541 // its length. For anything we can't figure out, just return UnknownVal.
542 MR = MR->StripCasts();
543
544 switch (MR->getKind()) {
545 case MemRegion::StringRegionKind: {
546 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
547 // so we can assume that the byte length is the correct C string length.
Ted Kremenek90af9092010-12-02 07:49:45 +0000548 SValBuilder &svalBuilder = C.getSValBuilder();
549 QualType sizeTy = svalBuilder.getContext().getSizeType();
550 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
551 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000552 }
553 case MemRegion::SymbolicRegionKind:
554 case MemRegion::AllocaRegionKind:
555 case MemRegion::VarRegionKind:
556 case MemRegion::FieldRegionKind:
557 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek90af9092010-12-02 07:49:45 +0000558 return getCStringLengthForRegion(C, state, Ex, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000559 case MemRegion::CompoundLiteralRegionKind:
560 // FIXME: Can we track this? Is it necessary?
561 return UnknownVal();
562 case MemRegion::ElementRegionKind:
563 // FIXME: How can we handle this? It's not good enough to subtract the
564 // offset from the base string length; consider "123\x00567" and &a[5].
565 return UnknownVal();
566 default:
567 // Other regions (mostly non-data) can't have a reliable C string length.
568 // In this case, an error is emitted and UndefinedVal is returned.
569 // The caller should always be prepared to handle this case.
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000570 if (ExplodedNode *N = C.generateNode(state)) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000571 if (!BT_NotCString)
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000572 BT_NotCString.reset(new BuiltinBug("API",
573 "Argument is not a null-terminated string."));
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000574
575 llvm::SmallString<120> buf;
576 llvm::raw_svector_ostream os(buf);
577
578 os << "Argument to byte string function is ";
579
580 if (SummarizeRegion(os, C.getASTContext(), MR))
581 os << ", which is not a null-terminated string";
582 else
583 os << "not a null-terminated string";
584
585 // Generate a report for this bug.
586 EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
587 os.str(), N);
588
589 report->addRange(Ex->getSourceRange());
590 C.EmitReport(report);
591 }
592
593 return UndefinedVal();
594 }
Jordy Roseb052e8f2010-07-27 01:37:31 +0000595}
596
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000597const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
598 const GRState *&state, const Expr *expr, SVal val) const {
599
600 // Get the memory region pointed to by the val.
601 const MemRegion *bufRegion = val.getAsRegion();
602 if (!bufRegion)
603 return NULL;
604
605 // Strip casts off the memory region.
606 bufRegion = bufRegion->StripCasts();
607
608 // Cast the memory region to a string region.
609 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
610 if (!strRegion)
611 return NULL;
612
613 // Return the actual string in the string region.
614 return strRegion->getStringLiteral();
615}
616
Jordy Rose722f5582010-08-16 07:51:42 +0000617const GRState *CStringChecker::InvalidateBuffer(CheckerContext &C,
618 const GRState *state,
619 const Expr *E, SVal V) {
620 Loc *L = dyn_cast<Loc>(&V);
621 if (!L)
622 return state;
623
624 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
625 // some assumptions about the value that CFRefCount can't. Even so, it should
626 // probably be refactored.
627 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
628 const MemRegion *R = MR->getRegion()->StripCasts();
629
630 // Are we dealing with an ElementRegion? If so, we should be invalidating
631 // the super-region.
632 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
633 R = ER->getSuperRegion();
634 // FIXME: What about layers of ElementRegions?
635 }
636
637 // Invalidate this region.
638 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenekeddeba02011-02-11 19:48:15 +0000639 return state->invalidateRegion(R, E, Count, NULL);
Jordy Rose722f5582010-08-16 07:51:42 +0000640 }
641
642 // If we have a non-region value by chance, just remove the binding.
643 // FIXME: is this necessary or correct? This handles the non-Region
644 // cases. Is it ever valid to store to these?
645 return state->unbindLoc(*L);
646}
647
Jordy Roseb052e8f2010-07-27 01:37:31 +0000648bool CStringChecker::SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
649 const MemRegion *MR) {
650 const TypedRegion *TR = dyn_cast<TypedRegion>(MR);
651 if (!TR)
652 return false;
653
654 switch (TR->getKind()) {
655 case MemRegion::FunctionTextRegionKind: {
656 const FunctionDecl *FD = cast<FunctionTextRegion>(TR)->getDecl();
657 if (FD)
658 os << "the address of the function '" << FD << "'";
659 else
660 os << "the address of a function";
661 return true;
662 }
663 case MemRegion::BlockTextRegionKind:
664 os << "block text";
665 return true;
666 case MemRegion::BlockDataRegionKind:
667 os << "a block";
668 return true;
669 case MemRegion::CXXThisRegionKind:
Zhongxing Xu03207162010-11-26 08:52:48 +0000670 case MemRegion::CXXTempObjectRegionKind:
671 os << "a C++ temp object of type " << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000672 return true;
673 case MemRegion::VarRegionKind:
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000674 os << "a variable of type" << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000675 return true;
676 case MemRegion::FieldRegionKind:
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000677 os << "a field of type " << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000678 return true;
679 case MemRegion::ObjCIvarRegionKind:
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000680 os << "an instance variable of type " << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000681 return true;
682 default:
683 return false;
684 }
685}
686
Jordy Rosed5d2e502010-07-08 23:57:29 +0000687//===----------------------------------------------------------------------===//
Ted Kremenekdc891422010-12-01 21:57:22 +0000688// evaluation of individual function calls.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000689//===----------------------------------------------------------------------===//
690
Lenny Maiorani79d74142011-03-31 21:36:53 +0000691void CStringChecker::evalCopyCommon(CheckerContext &C,
692 const CallExpr *CE,
693 const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000694 const Expr *Size, const Expr *Dest,
Lenny Maiorani79d74142011-03-31 21:36:53 +0000695 const Expr *Source, bool Restricted,
696 bool IsMempcpy) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000697 // See if the size argument is zero.
Ted Kremenek90af9092010-12-02 07:49:45 +0000698 SVal sizeVal = state->getSVal(Size);
699 QualType sizeTy = Size->getType();
Jordy Rosed5d2e502010-07-08 23:57:29 +0000700
Ted Kremenek90af9092010-12-02 07:49:45 +0000701 const GRState *stateZeroSize, *stateNonZeroSize;
702 llvm::tie(stateZeroSize, stateNonZeroSize) = assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000703
Lenny Maiorani79d74142011-03-31 21:36:53 +0000704 // Get the value of the Dest.
705 SVal destVal = state->getSVal(Dest);
706
707 // If the size is zero, there won't be any actual memory access, so
708 // just bind the return value to the destination buffer and return.
709 if (stateZeroSize) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000710 C.addTransition(stateZeroSize);
Lenny Maiorani79d74142011-03-31 21:36:53 +0000711 if (IsMempcpy)
712 state->BindExpr(CE, destVal);
713 else
714 state->BindExpr(CE, sizeVal);
715 return;
716 }
Jordy Rosed5d2e502010-07-08 23:57:29 +0000717
718 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +0000719 if (stateNonZeroSize) {
Lenny Maiorani79d74142011-03-31 21:36:53 +0000720
721 // Ensure the destination is not null. If it is NULL there will be a
722 // NULL pointer dereference.
723 state = checkNonNull(C, state, Dest, destVal);
724 if (!state)
725 return;
726
727 // Get the value of the Src.
728 SVal srcVal = state->getSVal(Source);
729
730 // Ensure the source is not null. If it is NULL there will be a
731 // NULL pointer dereference.
732 state = checkNonNull(C, state, Source, srcVal);
733 if (!state)
734 return;
735
736 // Ensure the buffers do not overlap.
Ted Kremenek90af9092010-12-02 07:49:45 +0000737 state = stateNonZeroSize;
Jordy Rose722f5582010-08-16 07:51:42 +0000738 state = CheckBufferAccess(C, state, Size, Dest, Source,
739 /* FirstIsDst = */ true);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000740 if (Restricted)
741 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rose722f5582010-08-16 07:51:42 +0000742
743 if (state) {
Lenny Maiorani79d74142011-03-31 21:36:53 +0000744
745 // If this is mempcpy, get the byte after the last byte copied and
746 // bind the expr.
747 if (IsMempcpy) {
748 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
749
750 // Get the length to copy.
751 SVal lenVal = state->getSVal(Size);
752 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&lenVal);
753
754 // Get the byte after the last byte copied.
755 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
756 *destRegVal,
757 *lenValNonLoc,
758 Dest->getType());
759
760 // The byte after the last byte copied is the return value.
761 state = state->BindExpr(CE, lastElement);
762 }
763
Jordy Rose722f5582010-08-16 07:51:42 +0000764 // Invalidate the destination.
765 // FIXME: Even if we can't perfectly model the copy, we should see if we
766 // can use LazyCompoundVals to copy the source values into the destination.
767 // This would probably remove any existing bindings past the end of the
768 // copied region, but that's still an improvement over blank invalidation.
769 state = InvalidateBuffer(C, state, Dest, state->getSVal(Dest));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000770 C.addTransition(state);
Jordy Rose722f5582010-08-16 07:51:42 +0000771 }
Jordy Rosed5d2e502010-07-08 23:57:29 +0000772 }
773}
774
775
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000776void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose134a2362010-07-06 23:11:01 +0000777 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Rose134a2362010-07-06 23:11:01 +0000778 // The return value is the address of the destination buffer.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000779 const Expr *Dest = CE->getArg(0);
780 const GRState *state = C.getState();
781 state = state->BindExpr(CE, state->getSVal(Dest));
Lenny Maiorani79d74142011-03-31 21:36:53 +0000782 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
783}
784
785void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
786 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
787 // The return value is a pointer to the byte following the last written byte.
788 const Expr *Dest = CE->getArg(0);
789 const GRState *state = C.getState();
790
791 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Rose134a2362010-07-06 23:11:01 +0000792}
793
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000794void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000795 // void *memmove(void *dst, const void *src, size_t n);
796 // The return value is the address of the destination buffer.
797 const Expr *Dest = CE->getArg(0);
798 const GRState *state = C.getState();
799 state = state->BindExpr(CE, state->getSVal(Dest));
Lenny Maiorani79d74142011-03-31 21:36:53 +0000800 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000801}
802
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000803void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000804 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maiorani79d74142011-03-31 21:36:53 +0000805 evalCopyCommon(C, CE, C.getState(),
806 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000807}
808
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000809void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose65136fb2010-07-07 08:15:01 +0000810 // int memcmp(const void *s1, const void *s2, size_t n);
811 const Expr *Left = CE->getArg(0);
812 const Expr *Right = CE->getArg(1);
813 const Expr *Size = CE->getArg(2);
814
815 const GRState *state = C.getState();
Ted Kremenek90af9092010-12-02 07:49:45 +0000816 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose65136fb2010-07-07 08:15:01 +0000817
Jordy Rosed5d2e502010-07-08 23:57:29 +0000818 // See if the size argument is zero.
Ted Kremenek90af9092010-12-02 07:49:45 +0000819 SVal sizeVal = state->getSVal(Size);
820 QualType sizeTy = Size->getType();
Jordy Rose65136fb2010-07-07 08:15:01 +0000821
Ted Kremenek90af9092010-12-02 07:49:45 +0000822 const GRState *stateZeroSize, *stateNonZeroSize;
823 llvm::tie(stateZeroSize, stateNonZeroSize) =
824 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rose65136fb2010-07-07 08:15:01 +0000825
Jordy Rosed5d2e502010-07-08 23:57:29 +0000826 // If the size can be zero, the result will be 0 in that case, and we don't
827 // have to check either of the buffers.
Ted Kremenek90af9092010-12-02 07:49:45 +0000828 if (stateZeroSize) {
829 state = stateZeroSize;
830 state = state->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000831 C.addTransition(state);
Jordy Rose65136fb2010-07-07 08:15:01 +0000832 }
833
Jordy Rosed5d2e502010-07-08 23:57:29 +0000834 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +0000835 if (stateNonZeroSize) {
836 state = stateNonZeroSize;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000837 // If we know the two buffers are the same, we know the result is 0.
838 // First, get the two buffers' addresses. Another checker will have already
839 // made sure they're not undefined.
840 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(state->getSVal(Left));
841 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(state->getSVal(Right));
Jordy Rose65136fb2010-07-07 08:15:01 +0000842
Jordy Rosed5d2e502010-07-08 23:57:29 +0000843 // See if they are the same.
Ted Kremenek90af9092010-12-02 07:49:45 +0000844 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000845 const GRState *StSameBuf, *StNotSameBuf;
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000846 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000847
848 // If the two arguments might be the same buffer, we know the result is zero,
849 // and we only need to check one size.
850 if (StSameBuf) {
851 state = StSameBuf;
852 state = CheckBufferAccess(C, state, Size, Left);
853 if (state) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000854 state = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000855 C.addTransition(state);
856 }
857 }
858
859 // If the two arguments might be different buffers, we have to check the
860 // size of both of them.
861 if (StNotSameBuf) {
862 state = StNotSameBuf;
863 state = CheckBufferAccess(C, state, Size, Left, Right);
864 if (state) {
865 // The return value is the comparison result, which we don't know.
866 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000867 SVal CmpV = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000868 state = state->BindExpr(CE, CmpV);
869 C.addTransition(state);
870 }
871 }
872 }
Jordy Rose65136fb2010-07-07 08:15:01 +0000873}
874
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000875void CStringChecker::evalstrLength(CheckerContext &C,
876 const CallExpr *CE) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000877 // size_t strlen(const char *s);
Ted Kremenek280a01f2011-02-22 04:55:05 +0000878 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
879}
880
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000881void CStringChecker::evalstrnLength(CheckerContext &C,
882 const CallExpr *CE) const {
Ted Kremenek280a01f2011-02-22 04:55:05 +0000883 // size_t strnlen(const char *s, size_t maxlen);
884 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
885}
886
887void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000888 bool IsStrnlen) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000889 const GRState *state = C.getState();
890 const Expr *Arg = CE->getArg(0);
891 SVal ArgVal = state->getSVal(Arg);
892
893 // Check that the argument is non-null.
Ted Kremenek90af9092010-12-02 07:49:45 +0000894 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000895
896 if (state) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000897 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000898
899 // If the argument isn't a valid C string, there's no valid state to
900 // transition to.
Ted Kremenek90af9092010-12-02 07:49:45 +0000901 if (strLength.isUndef())
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000902 return;
903
Ted Kremenek280a01f2011-02-22 04:55:05 +0000904 // If the check is for strnlen() then bind the return value to no more than
905 // the maxlen value.
906 if (IsStrnlen) {
907 const Expr *maxlenExpr = CE->getArg(1);
908 SVal maxlenVal = state->getSVal(maxlenExpr);
909
910 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
911 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
912
913 QualType cmpTy = C.getSValBuilder().getContext().IntTy;
914 const GRState *stateTrue, *stateFalse;
915
916 // Check if the strLength is greater than or equal to the maxlen
917 llvm::tie(stateTrue, stateFalse) =
918 state->assume(cast<DefinedOrUnknownSVal>
919 (C.getSValBuilder().evalBinOpNN(state, BO_GE,
920 *strLengthNL, *maxlenValNL,
921 cmpTy)));
922
923 // If the strLength is greater than or equal to the maxlen, set strLength
924 // to maxlen
925 if (stateTrue && !stateFalse) {
926 strLength = maxlenVal;
927 }
928 }
929
Ted Kremenek90af9092010-12-02 07:49:45 +0000930 // If getCStringLength couldn't figure out the length, conjure a return
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000931 // value, so it can be used in constraints, at least.
Ted Kremenek90af9092010-12-02 07:49:45 +0000932 if (strLength.isUnknown()) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000933 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000934 strLength = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000935 }
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000936
937 // Bind the return value.
Ted Kremenek90af9092010-12-02 07:49:45 +0000938 state = state->BindExpr(CE, strLength);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000939 C.addTransition(state);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000940 }
941}
942
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000943void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose722f5582010-08-16 07:51:42 +0000944 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000945 evalStrcpyCommon(C, CE,
946 /* returnEnd = */ false,
947 /* isBounded = */ false,
948 /* isAppending = */ false);
Ted Kremenekfb1a79a2011-02-22 04:58:34 +0000949}
950
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000951void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenekfb1a79a2011-02-22 04:58:34 +0000952 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000953 evalStrcpyCommon(C, CE,
954 /* returnEnd = */ false,
955 /* isBounded = */ true,
956 /* isAppending = */ false);
Jordy Rose722f5582010-08-16 07:51:42 +0000957}
958
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000959void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose722f5582010-08-16 07:51:42 +0000960 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000961 evalStrcpyCommon(C, CE,
962 /* returnEnd = */ true,
963 /* isBounded = */ false,
964 /* isAppending = */ false);
965}
966
967void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
968 //char *strcat(char *restrict s1, const char *restrict s2);
969 evalStrcpyCommon(C, CE,
970 /* returnEnd = */ false,
971 /* isBounded = */ false,
972 /* isAppending = */ true);
973}
974
975void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
976 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
977 evalStrcpyCommon(C, CE,
978 /* returnEnd = */ false,
979 /* isBounded = */ true,
980 /* isAppending = */ true);
Jordy Rose722f5582010-08-16 07:51:42 +0000981}
982
Ted Kremenekdc891422010-12-01 21:57:22 +0000983void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000984 bool returnEnd, bool isBounded,
985 bool isAppending) const {
Jordy Rose722f5582010-08-16 07:51:42 +0000986 const GRState *state = C.getState();
987
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000988 // Check that the destination is non-null.
Jordy Rose722f5582010-08-16 07:51:42 +0000989 const Expr *Dst = CE->getArg(0);
990 SVal DstVal = state->getSVal(Dst);
991
Ted Kremenek90af9092010-12-02 07:49:45 +0000992 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +0000993 if (!state)
994 return;
995
996 // Check that the source is non-null.
Ted Kremenek90af9092010-12-02 07:49:45 +0000997 const Expr *srcExpr = CE->getArg(1);
998 SVal srcVal = state->getSVal(srcExpr);
999 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001000 if (!state)
1001 return;
1002
1003 // Get the string length of the source.
Ted Kremenek90af9092010-12-02 07:49:45 +00001004 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001005
1006 // If the source isn't a valid C string, give up.
Ted Kremenek90af9092010-12-02 07:49:45 +00001007 if (strLength.isUndef())
Jordy Rose722f5582010-08-16 07:51:42 +00001008 return;
1009
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001010 // If the function is strncpy, strncat, etc... it is bounded.
1011 if (isBounded) {
1012 // Get the max number of characters to copy.
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001013 const Expr *lenExpr = CE->getArg(2);
1014 SVal lenVal = state->getSVal(lenExpr);
1015
1016 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1017 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1018
1019 QualType cmpTy = C.getSValBuilder().getContext().IntTy;
1020 const GRState *stateTrue, *stateFalse;
1021
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001022 // Check if the max number to copy is less than the length of the src.
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001023 llvm::tie(stateTrue, stateFalse) =
1024 state->assume(cast<DefinedOrUnknownSVal>
1025 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1026 *strLengthNL, *lenValNL,
1027 cmpTy)));
1028
1029 if (stateTrue) {
1030 // Max number to copy is less than the length of the src, so the actual
1031 // strLength copied is the max number arg.
1032 strLength = lenVal;
1033 }
1034 }
1035
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001036 // If this is an appending function (strcat, strncat...) then set the
1037 // string length to strlen(src) + strlen(dst) since the buffer will
1038 // ultimately contain both.
1039 if (isAppending) {
1040 // Get the string length of the destination, or give up.
1041 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1042 if (dstStrLength.isUndef())
1043 return;
1044
1045 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&strLength);
1046 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1047
1048 // If src or dst cast to NonLoc is NULL, give up.
1049 if ((!srcStrLengthNL) || (!dstStrLengthNL))
1050 return;
1051
1052 QualType addTy = C.getSValBuilder().getContext().getSizeType();
1053
1054 strLength = C.getSValBuilder().evalBinOpNN(state, BO_Add,
1055 *srcStrLengthNL, *dstStrLengthNL,
1056 addTy);
1057 }
1058
Ted Kremenek90af9092010-12-02 07:49:45 +00001059 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001060
1061 // If the destination is a MemRegion, try to check for a buffer overflow and
1062 // record the new string length.
Ted Kremenek90af9092010-12-02 07:49:45 +00001063 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rose722f5582010-08-16 07:51:42 +00001064 // If the length is known, we can check for an overflow.
Ted Kremenek90af9092010-12-02 07:49:45 +00001065 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&strLength)) {
1066 SVal lastElement =
1067 C.getSValBuilder().evalBinOpLN(state, BO_Add, *dstRegVal,
1068 *knownStrLength, Dst->getType());
Jordy Rose722f5582010-08-16 07:51:42 +00001069
Ted Kremenek90af9092010-12-02 07:49:45 +00001070 state = CheckLocation(C, state, Dst, lastElement, /* IsDst = */ true);
Jordy Rose722f5582010-08-16 07:51:42 +00001071 if (!state)
1072 return;
1073
1074 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001075 if (returnEnd)
1076 Result = lastElement;
Jordy Rose722f5582010-08-16 07:51:42 +00001077 }
1078
1079 // Invalidate the destination. This must happen before we set the C string
1080 // length because invalidation will clear the length.
1081 // FIXME: Even if we can't perfectly model the copy, we should see if we
1082 // can use LazyCompoundVals to copy the source values into the destination.
1083 // This would probably remove any existing bindings past the end of the
1084 // string, but that's still an improvement over blank invalidation.
Ted Kremenek90af9092010-12-02 07:49:45 +00001085 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001086
1087 // Set the C string length of the destination.
Ted Kremenek90af9092010-12-02 07:49:45 +00001088 state = setCStringLength(state, dstRegVal->getRegion(), strLength);
Jordy Rose722f5582010-08-16 07:51:42 +00001089 }
1090
1091 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1092 // overflow, we still need a result. Conjure a return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001093 if (returnEnd && Result.isUnknown()) {
1094 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose722f5582010-08-16 07:51:42 +00001095 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +00001096 strLength = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rose722f5582010-08-16 07:51:42 +00001097 }
1098
1099 // Set the return value.
1100 state = state->BindExpr(CE, Result);
1101 C.addTransition(state);
1102}
1103
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001104void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1105 //int strcmp(const char *restrict s1, const char *restrict s2);
1106
1107 const GRState *state = C.getState();
1108
1109 // Check that the first string is non-null
1110 const Expr *s1 = CE->getArg(0);
1111 SVal s1Val = state->getSVal(s1);
1112 state = checkNonNull(C, state, s1, s1Val);
1113 if (!state)
1114 return;
1115
1116 // Check that the second string is non-null.
1117 const Expr *s2 = CE->getArg(1);
1118 SVal s2Val = state->getSVal(s2);
1119 state = checkNonNull(C, state, s2, s2Val);
1120 if (!state)
1121 return;
1122
1123 // Get the string length of the first string or give up.
1124 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1125 if (s1Length.isUndef())
1126 return;
1127
1128 // Get the string length of the second string or give up.
1129 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1130 if (s2Length.isUndef())
1131 return;
1132
1133 // Get the string literal of the first string.
1134 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1135 if (!s1StrLiteral)
1136 return;
1137 llvm::StringRef s1StrRef = s1StrLiteral->getString();
1138
1139 // Get the string literal of the second string.
1140 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1141 if (!s2StrLiteral)
1142 return;
1143 llvm::StringRef s2StrRef = s2StrLiteral->getString();
1144
1145 // Compare string 1 to string 2 the same way strcmp() does.
1146 int result = s1StrRef.compare(s2StrRef);
1147
1148 // Build the SVal of the comparison to bind the return value.
1149 SValBuilder &svalBuilder = C.getSValBuilder();
1150 QualType intTy = svalBuilder.getContext().IntTy;
1151 SVal resultVal = svalBuilder.makeIntVal(result, intTy);
1152
1153 // Bind the return value of the expression.
1154 // Set the return value.
1155 state = state->BindExpr(CE, resultVal);
1156 C.addTransition(state);
1157}
1158
Jordy Rosed5d2e502010-07-08 23:57:29 +00001159//===----------------------------------------------------------------------===//
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001160// The driver method, and other Checker callbacks.
Jordy Rosed5d2e502010-07-08 23:57:29 +00001161//===----------------------------------------------------------------------===//
Jordy Rose134a2362010-07-06 23:11:01 +00001162
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001163bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose134a2362010-07-06 23:11:01 +00001164 // Get the callee. All the functions we care about are C functions
1165 // with simple identifiers.
1166 const GRState *state = C.getState();
1167 const Expr *Callee = CE->getCallee();
1168 const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl();
1169
1170 if (!FD)
1171 return false;
1172
1173 // Get the name of the callee. If it's a builtin, strip off the prefix.
Douglas Gregor4b8eca82010-11-01 23:16:05 +00001174 IdentifierInfo *II = FD->getIdentifier();
1175 if (!II) // if no identifier, not a simple C function
1176 return false;
1177 llvm::StringRef Name = II->getName();
Jordy Rose134a2362010-07-06 23:11:01 +00001178 if (Name.startswith("__builtin_"))
1179 Name = Name.substr(10);
1180
Ted Kremenekdc891422010-12-01 21:57:22 +00001181 FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
1182 .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
Lenny Maiorani79d74142011-03-31 21:36:53 +00001183 .Case("mempcpy", &CStringChecker::evalMempcpy)
Ted Kremenekdc891422010-12-01 21:57:22 +00001184 .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
1185 .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
1186 .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001187 .Cases("strncpy", "__strncpy_chk", &CStringChecker::evalStrncpy)
Ted Kremenekdc891422010-12-01 21:57:22 +00001188 .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001189 .Cases("strcat", "__strcat_chk", &CStringChecker::evalStrcat)
1190 .Cases("strncat", "__strncat_chk", &CStringChecker::evalStrncat)
Ted Kremenek90af9092010-12-02 07:49:45 +00001191 .Case("strlen", &CStringChecker::evalstrLength)
Ted Kremenek280a01f2011-02-22 04:55:05 +00001192 .Case("strnlen", &CStringChecker::evalstrnLength)
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001193 .Case("strcmp", &CStringChecker::evalStrcmp)
Ted Kremenekdc891422010-12-01 21:57:22 +00001194 .Case("bcopy", &CStringChecker::evalBcopy)
Jordy Rose134a2362010-07-06 23:11:01 +00001195 .Default(NULL);
1196
Jordy Rosed5d2e502010-07-08 23:57:29 +00001197 // If the callee isn't a string function, let another checker handle it.
Ted Kremenekdc891422010-12-01 21:57:22 +00001198 if (!evalFunction)
Jordy Rose134a2362010-07-06 23:11:01 +00001199 return false;
1200
Jordy Rosed5d2e502010-07-08 23:57:29 +00001201 // Check and evaluate the call.
Ted Kremenekdc891422010-12-01 21:57:22 +00001202 (this->*evalFunction)(C, CE);
Jordy Rose134a2362010-07-06 23:11:01 +00001203 return true;
1204}
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001205
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001206void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001207 // Record string length for char a[] = "abc";
1208 const GRState *state = C.getState();
1209
1210 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1211 I != E; ++I) {
1212 const VarDecl *D = dyn_cast<VarDecl>(*I);
1213 if (!D)
1214 continue;
1215
1216 // FIXME: Handle array fields of structs.
1217 if (!D->getType()->isArrayType())
1218 continue;
1219
1220 const Expr *Init = D->getInit();
1221 if (!Init)
1222 continue;
1223 if (!isa<StringLiteral>(Init))
1224 continue;
1225
1226 Loc VarLoc = state->getLValue(D, C.getPredecessor()->getLocationContext());
1227 const MemRegion *MR = VarLoc.getAsRegion();
1228 if (!MR)
1229 continue;
1230
1231 SVal StrVal = state->getSVal(Init);
1232 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenek90af9092010-12-02 07:49:45 +00001233 DefinedOrUnknownSVal strLength
1234 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001235
Ted Kremenek90af9092010-12-02 07:49:45 +00001236 state = state->set<CStringLength>(MR, strLength);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001237 }
1238
1239 C.addTransition(state);
1240}
1241
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001242bool CStringChecker::wantsRegionChangeUpdate(const GRState *state) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001243 CStringLength::EntryMap Entries = state->get<CStringLength>();
1244 return !Entries.isEmpty();
1245}
1246
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001247const GRState *
1248CStringChecker::checkRegionChanges(const GRState *state,
1249 const MemRegion * const *Begin,
1250 const MemRegion * const *End) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001251 CStringLength::EntryMap Entries = state->get<CStringLength>();
1252 if (Entries.isEmpty())
1253 return state;
1254
1255 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1256 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1257
1258 // First build sets for the changed regions and their super-regions.
1259 for ( ; Begin != End; ++Begin) {
1260 const MemRegion *MR = *Begin;
1261 Invalidated.insert(MR);
1262
1263 SuperRegions.insert(MR);
1264 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1265 MR = SR->getSuperRegion();
1266 SuperRegions.insert(MR);
1267 }
1268 }
1269
1270 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1271
1272 // Then loop over the entries in the current state.
1273 for (CStringLength::EntryMap::iterator I = Entries.begin(),
1274 E = Entries.end(); I != E; ++I) {
1275 const MemRegion *MR = I.getKey();
1276
1277 // Is this entry for a super-region of a changed region?
1278 if (SuperRegions.count(MR)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001279 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001280 continue;
1281 }
1282
1283 // Is this entry for a sub-region of a changed region?
1284 const MemRegion *Super = MR;
1285 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1286 Super = SR->getSuperRegion();
1287 if (Invalidated.count(Super)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001288 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001289 break;
1290 }
1291 }
1292 }
1293
1294 return state->set<CStringLength>(Entries);
1295}
1296
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001297void CStringChecker::checkLiveSymbols(const GRState *state,
1298 SymbolReaper &SR) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001299 // Mark all symbols in our string length map as valid.
1300 CStringLength::EntryMap Entries = state->get<CStringLength>();
1301
1302 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1303 I != E; ++I) {
1304 SVal Len = I.getData();
1305 if (SymbolRef Sym = Len.getAsSymbol())
1306 SR.markInUse(Sym);
1307 }
1308}
1309
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001310void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1311 CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001312 if (!SR.hasDeadSymbols())
1313 return;
1314
1315 const GRState *state = C.getState();
1316 CStringLength::EntryMap Entries = state->get<CStringLength>();
1317 if (Entries.isEmpty())
1318 return;
1319
1320 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1321 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1322 I != E; ++I) {
1323 SVal Len = I.getData();
1324 if (SymbolRef Sym = Len.getAsSymbol()) {
1325 if (SR.isDead(Sym))
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001326 Entries = F.remove(Entries, I.getKey());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001327 }
1328 }
1329
1330 state = state->set<CStringLength>(Entries);
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001331 C.generateNode(state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001332}
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001333
1334void ento::registerCStringChecker(CheckerManager &mgr) {
1335 mgr.registerChecker<CStringChecker>();
1336}