blob: 1d25680f0723a9f32ad141342a4e69d30695e7a4 [file] [log] [blame]
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001//= CStringChecker.h - Checks calls to C string functions ----------*- C++ -*-//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This defines CStringChecker, which is an assortment of checks on calls
11// to functions in <string.h>.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidisa0decc92011-02-15 21:25:03 +000015#include "ClangSACheckers.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000016#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000017#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000018#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000019#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"
Jordy Roseccbf7ee2010-07-06 23:11:01 +000021#include "llvm/ADT/StringSwitch.h"
22
23using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000024using namespace ento;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000025
26namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000027class CStringChecker : public Checker< eval::Call,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000028 check::PreStmt<DeclStmt>,
29 check::LiveSymbols,
30 check::DeadSymbols,
31 check::RegionChanges
32 > {
33 mutable llvm::OwningPtr<BugType> BT_Null, BT_Bounds, BT_BoundsWrite,
34 BT_Overlap, BT_NotCString;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000035public:
Jordy Roseccbf7ee2010-07-06 23:11:01 +000036 static void *getTag() { static int tag; return &tag; }
37
Argyrios Kyrtzidis183ff982011-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 Rosea5261542010-08-14 21:02:52 +000043
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000044 const GRState *checkRegionChanges(const GRState *state,
45 const MemRegion * const *Begin,
46 const MemRegion * const *End) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000047
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000048 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
49 const CallExpr *) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000050
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000051 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000052 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000053 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
54 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000055 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
56 const GRState *state,
Jordy Rosed325ffb2010-07-08 23:57:29 +000057 const Expr *Size, const Expr *Source, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +000058 bool Restricted = false,
59 bool IsMempcpy = false) const;
Jordy Rosed325ffb2010-07-08 23:57:29 +000060
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000061 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000062
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000063 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
64 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenekbe4242c2011-02-22 04:55:05 +000065 void evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000066 bool IsStrnlen = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +000067
Argyrios Kyrtzidis183ff982011-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 Kremenek0ef473f2011-02-22 04:58:34 +000071 void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool returnEnd,
Lenny Maiorani067bbd02011-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 Rosee64f3112010-08-16 07:51:42 +000076
Lenny Maiorani318dd922011-04-12 17:08:43 +000077 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani357f6ee2011-04-25 22:21:00 +000078 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
79 void evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
80 bool isBounded = false) const;
Lenny Maiorani318dd922011-04-12 17:08:43 +000081
Jordy Roseccbf7ee2010-07-06 23:11:01 +000082 // Utility methods
Jordy Rosed325ffb2010-07-08 23:57:29 +000083 std::pair<const GRState*, const GRState*>
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000084 static assumeZero(CheckerContext &C,
85 const GRState *state, SVal V, QualType Ty);
Jordy Rosed325ffb2010-07-08 23:57:29 +000086
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000087 static const GRState *setCStringLength(const GRState *state,
88 const MemRegion *MR, SVal strLength);
89 static SVal getCStringLengthForRegion(CheckerContext &C,
90 const GRState *&state,
91 const Expr *Ex, const MemRegion *MR);
Ted Kremenekc8413fd2010-12-02 07:49:45 +000092 SVal getCStringLength(CheckerContext &C, const GRState *&state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000093 const Expr *Ex, SVal Buf) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +000094
Lenny Maiorani318dd922011-04-12 17:08:43 +000095 const StringLiteral *getCStringLiteral(CheckerContext &C,
96 const GRState *&state,
97 const Expr *expr,
98 SVal val) const;
99
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000100 static const GRState *InvalidateBuffer(CheckerContext &C,
101 const GRState *state,
102 const Expr *Ex, SVal V);
Jordy Rosee64f3112010-08-16 07:51:42 +0000103
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000104 static bool SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
105 const MemRegion *MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000106
107 // Re-usable checks
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000108 const GRState *checkNonNull(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000109 const Expr *S, SVal l) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000110 const GRState *CheckLocation(CheckerContext &C, const GRState *state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000111 const Expr *S, SVal l,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000112 bool IsDestination = false) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000113 const GRState *CheckBufferAccess(CheckerContext &C, const GRState *state,
114 const Expr *Size,
115 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000116 const Expr *SecondBuf = NULL,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000117 bool FirstIsDestination = false) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000118 const GRState *CheckOverlap(CheckerContext &C, const GRState *state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000119 const Expr *Size, const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000120 const Expr *Second) const;
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000121 void emitOverlapBug(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000122 const Stmt *First, const Stmt *Second) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000123};
Jordy Rosea5261542010-08-14 21:02:52 +0000124
125class CStringLength {
126public:
127 typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
128};
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000129} //end anonymous namespace
130
Jordy Rosea5261542010-08-14 21:02:52 +0000131namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000132namespace ento {
Jordy Rosea5261542010-08-14 21:02:52 +0000133 template <>
134 struct GRStateTrait<CStringLength>
135 : public GRStatePartialTrait<CStringLength::EntryMap> {
136 static void *GDMIndex() { return CStringChecker::getTag(); }
137 };
138}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000139}
Jordy Rosea5261542010-08-14 21:02:52 +0000140
Jordy Rosed325ffb2010-07-08 23:57:29 +0000141//===----------------------------------------------------------------------===//
142// Individual checks and utility methods.
143//===----------------------------------------------------------------------===//
144
145std::pair<const GRState*, const GRState*>
Ted Kremenek28f47b92010-12-01 22:16:56 +0000146CStringChecker::assumeZero(CheckerContext &C, const GRState *state, SVal V,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000147 QualType Ty) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000148 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
149 if (!val)
Jordy Rosed325ffb2010-07-08 23:57:29 +0000150 return std::pair<const GRState*, const GRState *>(state, state);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000151
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000152 SValBuilder &svalBuilder = C.getSValBuilder();
153 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
154 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000155}
Jordy Rosea6b808c2010-07-07 07:48:06 +0000156
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000157const GRState *CStringChecker::checkNonNull(CheckerContext &C,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000158 const GRState *state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000159 const Expr *S, SVal l) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000160 // If a previous check has failed, propagate the failure.
161 if (!state)
162 return NULL;
163
164 const GRState *stateNull, *stateNonNull;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000165 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed325ffb2010-07-08 23:57:29 +0000166
167 if (stateNull && !stateNonNull) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000168 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000169 if (!N)
170 return NULL;
171
Jordy Rosed325ffb2010-07-08 23:57:29 +0000172 if (!BT_Null)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000173 BT_Null.reset(new BuiltinBug("API",
174 "Null pointer argument in call to byte string function"));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000175
176 // Generate a report for this bug.
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000177 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Jordy Rosea6b808c2010-07-07 07:48:06 +0000178 EnhancedBugReport *report = new EnhancedBugReport(*BT,
179 BT->getDescription(), N);
180
181 report->addRange(S->getSourceRange());
182 report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, S);
183 C.EmitReport(report);
184 return NULL;
185 }
186
187 // From here on, assume that the value is non-null.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000188 assert(stateNonNull);
189 return stateNonNull;
Jordy Rosea6b808c2010-07-07 07:48:06 +0000190}
191
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000192// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
193const GRState *CStringChecker::CheckLocation(CheckerContext &C,
194 const GRState *state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000195 const Expr *S, SVal l,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000196 bool IsDestination) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000197 // If a previous check has failed, propagate the failure.
198 if (!state)
199 return NULL;
200
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000201 // Check for out of bound array element access.
202 const MemRegion *R = l.getAsRegion();
203 if (!R)
204 return state;
205
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000206 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
207 if (!ER)
208 return state;
209
Zhongxing Xu018220c2010-08-11 06:10:55 +0000210 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000211 "CheckLocation should only be called with char* ElementRegions");
212
213 // Get the size of the array.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000214 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
215 SValBuilder &svalBuilder = C.getSValBuilder();
216 SVal Extent = svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000217 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
218
219 // Get the index of the accessed element.
Gabor Greif89b06582010-09-09 10:51:37 +0000220 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000221
Ted Kremenek28f47b92010-12-01 22:16:56 +0000222 const GRState *StInBound = state->assumeInBound(Idx, Size, true);
223 const GRState *StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000224 if (StOutBound && !StInBound) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000225 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000226 if (!N)
227 return NULL;
228
Jordy Rosee64f3112010-08-16 07:51:42 +0000229 BuiltinBug *BT;
230 if (IsDestination) {
231 if (!BT_BoundsWrite) {
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000232 BT_BoundsWrite.reset(new BuiltinBug("Out-of-bound array access",
233 "Byte string function overflows destination buffer"));
Jordy Rosee64f3112010-08-16 07:51:42 +0000234 }
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000235 BT = static_cast<BuiltinBug*>(BT_BoundsWrite.get());
Jordy Rosee64f3112010-08-16 07:51:42 +0000236 } else {
237 if (!BT_Bounds) {
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000238 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
239 "Byte string function accesses out-of-bound array element"));
Jordy Rosee64f3112010-08-16 07:51:42 +0000240 }
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000241 BT = static_cast<BuiltinBug*>(BT_Bounds.get());
Jordy Rosee64f3112010-08-16 07:51:42 +0000242 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000243
244 // FIXME: It would be nice to eventually make this diagnostic more clear,
245 // e.g., by referencing the original declaration or by saying *why* this
246 // reference is outside the range.
247
248 // Generate a report for this bug.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000249 RangedBugReport *report = new RangedBugReport(*BT, BT->getDescription(), N);
250
251 report->addRange(S->getSourceRange());
252 C.EmitReport(report);
253 return NULL;
254 }
255
256 // Array bound check succeeded. From this point forward the array bound
257 // should always succeed.
258 return StInBound;
259}
260
261const GRState *CStringChecker::CheckBufferAccess(CheckerContext &C,
262 const GRState *state,
263 const Expr *Size,
264 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000265 const Expr *SecondBuf,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000266 bool FirstIsDestination) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000267 // If a previous check has failed, propagate the failure.
268 if (!state)
269 return NULL;
270
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000271 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000272 ASTContext &Ctx = C.getASTContext();
273
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000274 QualType sizeTy = Size->getType();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000275 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
276
Jordy Rosea6b808c2010-07-07 07:48:06 +0000277 // Check that the first buffer is non-null.
278 SVal BufVal = state->getSVal(FirstBuf);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000279 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000280 if (!state)
281 return NULL;
282
Jordy Rosed325ffb2010-07-08 23:57:29 +0000283 // Get the access length and make sure it is known.
284 SVal LengthVal = state->getSVal(Size);
285 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
286 if (!Length)
287 return state;
288
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000289 // Compute the offset of the last element to be accessed: size-1.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000290 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
291 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
292 *Length, One, sizeTy));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000293
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000294 // Check that the first buffer is sufficiently long.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000295 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000296 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000297 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
298 LastOffset, PtrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +0000299 state = CheckLocation(C, state, FirstBuf, BufEnd, FirstIsDestination);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000300
Jordy Roseb6a40262010-08-05 23:11:30 +0000301 // If the buffer isn't large enough, abort.
302 if (!state)
303 return NULL;
304 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000305
306 // If there's a second buffer, check it as well.
307 if (SecondBuf) {
308 BufVal = state->getSVal(SecondBuf);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000309 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000310 if (!state)
311 return NULL;
312
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000313 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000314 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000315 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
316 LastOffset, PtrTy);
Jordy Roseb6a40262010-08-05 23:11:30 +0000317 state = CheckLocation(C, state, SecondBuf, BufEnd);
318 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000319 }
320
321 // Large enough or not, return this state!
322 return state;
323}
324
325const GRState *CStringChecker::CheckOverlap(CheckerContext &C,
326 const GRState *state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000327 const Expr *Size,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000328 const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000329 const Expr *Second) const {
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000330 // Do a simple check for overlap: if the two arguments are from the same
331 // buffer, see if the end of the first is greater than the start of the second
332 // or vice versa.
333
Jordy Rosed325ffb2010-07-08 23:57:29 +0000334 // If a previous check has failed, propagate the failure.
335 if (!state)
336 return NULL;
337
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000338 const GRState *stateTrue, *stateFalse;
339
340 // Get the buffer values and make sure they're known locations.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000341 SVal firstVal = state->getSVal(First);
342 SVal secondVal = state->getSVal(Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000343
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000344 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
345 if (!firstLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000346 return state;
347
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000348 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
349 if (!secondLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000350 return state;
351
352 // Are the two values the same?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000353 SValBuilder &svalBuilder = C.getSValBuilder();
354 llvm::tie(stateTrue, stateFalse) =
355 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000356
357 if (stateTrue && !stateFalse) {
358 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000359 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000360 return NULL;
361 }
362
Ted Kremenek28f47b92010-12-01 22:16:56 +0000363 // assume the two expressions are not equal.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000364 assert(stateFalse);
365 state = stateFalse;
366
367 // Which value comes first?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000368 ASTContext &Ctx = svalBuilder.getContext();
369 QualType cmpTy = Ctx.IntTy;
370 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
371 *firstLoc, *secondLoc, cmpTy);
372 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
373 if (!reverseTest)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000374 return state;
375
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000376 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000377 if (stateTrue) {
378 if (stateFalse) {
379 // If we don't know which one comes first, we can't perform this test.
380 return state;
381 } else {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000382 // Switch the values so that firstVal is before secondVal.
383 Loc *tmpLoc = firstLoc;
384 firstLoc = secondLoc;
385 secondLoc = tmpLoc;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000386
387 // Switch the Exprs as well, so that they still correspond.
388 const Expr *tmpExpr = First;
389 First = Second;
390 Second = tmpExpr;
391 }
392 }
393
394 // Get the length, and make sure it too is known.
395 SVal LengthVal = state->getSVal(Size);
396 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
397 if (!Length)
398 return state;
399
400 // Convert the first buffer's start address to char*.
401 // Bail out if the cast fails.
402 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000403 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy, First->getType());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000404 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
405 if (!FirstStartLoc)
406 return state;
407
408 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000409 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000410 *FirstStartLoc, *Length, CharPtrTy);
411 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
412 if (!FirstEndLoc)
413 return state;
414
415 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000416 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
417 *FirstEndLoc, *secondLoc, cmpTy);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000418 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
419 if (!OverlapTest)
420 return state;
421
Ted Kremenek28f47b92010-12-01 22:16:56 +0000422 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000423
424 if (stateTrue && !stateFalse) {
425 // Overlap!
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000426 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000427 return NULL;
428 }
429
Ted Kremenek28f47b92010-12-01 22:16:56 +0000430 // assume the two expressions don't overlap.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000431 assert(stateFalse);
432 return stateFalse;
433}
434
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000435void CStringChecker::emitOverlapBug(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000436 const Stmt *First, const Stmt *Second) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000437 ExplodedNode *N = C.generateSink(state);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000438 if (!N)
439 return;
440
441 if (!BT_Overlap)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000442 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000443
444 // Generate a report for this bug.
445 RangedBugReport *report =
446 new RangedBugReport(*BT_Overlap,
447 "Arguments must not be overlapping buffers", N);
448 report->addRange(First->getSourceRange());
449 report->addRange(Second->getSourceRange());
450
451 C.EmitReport(report);
452}
453
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000454const GRState *CStringChecker::setCStringLength(const GRState *state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000455 const MemRegion *MR,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000456 SVal strLength) {
457 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
458 if (strLength.isUnknown())
Jordy Rosee64f3112010-08-16 07:51:42 +0000459 return state;
460
461 MR = MR->StripCasts();
462
463 switch (MR->getKind()) {
464 case MemRegion::StringRegionKind:
465 // FIXME: This can happen if we strcpy() into a string region. This is
466 // undefined [C99 6.4.5p6], but we should still warn about it.
467 return state;
468
469 case MemRegion::SymbolicRegionKind:
470 case MemRegion::AllocaRegionKind:
471 case MemRegion::VarRegionKind:
472 case MemRegion::FieldRegionKind:
473 case MemRegion::ObjCIvarRegionKind:
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000474 return state->set<CStringLength>(MR, strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +0000475
476 case MemRegion::ElementRegionKind:
477 // FIXME: Handle element regions by upper-bounding the parent region's
478 // string length.
479 return state;
480
481 default:
482 // Other regions (mostly non-data) can't have a reliable C string length.
483 // For now, just ignore the change.
484 // FIXME: These are rare but not impossible. We should output some kind of
485 // warning for things like strcpy((char[]){'a', 0}, "b");
486 return state;
487 }
488}
489
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000490SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Jordy Rosea5261542010-08-14 21:02:52 +0000491 const GRState *&state,
492 const Expr *Ex,
493 const MemRegion *MR) {
494 // If there's a recorded length, go ahead and return it.
495 const SVal *Recorded = state->get<CStringLength>(MR);
496 if (Recorded)
497 return *Recorded;
498
499 // Otherwise, get a new symbol and update the state.
500 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000501 SValBuilder &svalBuilder = C.getSValBuilder();
502 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000503 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
504 MR, Ex, sizeTy, Count);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000505 state = state->set<CStringLength>(MR, strLength);
506 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000507}
508
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000509SVal CStringChecker::getCStringLength(CheckerContext &C, const GRState *&state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000510 const Expr *Ex, SVal Buf) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000511 const MemRegion *MR = Buf.getAsRegion();
512 if (!MR) {
513 // If we can't get a region, see if it's something we /know/ isn't a
514 // C string. In the context of locations, the only time we can issue such
515 // a warning is for labels.
516 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000517 if (ExplodedNode *N = C.generateNode(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000518 if (!BT_NotCString)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000519 BT_NotCString.reset(new BuiltinBug("API",
520 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000521
522 llvm::SmallString<120> buf;
523 llvm::raw_svector_ostream os(buf);
524 os << "Argument to byte string function is the address of the label '"
Chris Lattner68106302011-02-17 05:38:27 +0000525 << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000526 << "', which is not a null-terminated string";
527
528 // Generate a report for this bug.
529 EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
530 os.str(), N);
531
532 report->addRange(Ex->getSourceRange());
533 C.EmitReport(report);
534 }
535
536 return UndefinedVal();
537 }
538
Jordy Rosea5261542010-08-14 21:02:52 +0000539 // If it's not a region and not a label, give up.
540 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000541 }
542
Jordy Rosea5261542010-08-14 21:02:52 +0000543 // If we have a region, strip casts from it and see if we can figure out
544 // its length. For anything we can't figure out, just return UnknownVal.
545 MR = MR->StripCasts();
546
547 switch (MR->getKind()) {
548 case MemRegion::StringRegionKind: {
549 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
550 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000551 SValBuilder &svalBuilder = C.getSValBuilder();
552 QualType sizeTy = svalBuilder.getContext().getSizeType();
553 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
554 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000555 }
556 case MemRegion::SymbolicRegionKind:
557 case MemRegion::AllocaRegionKind:
558 case MemRegion::VarRegionKind:
559 case MemRegion::FieldRegionKind:
560 case MemRegion::ObjCIvarRegionKind:
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000561 return getCStringLengthForRegion(C, state, Ex, MR);
Jordy Rosea5261542010-08-14 21:02:52 +0000562 case MemRegion::CompoundLiteralRegionKind:
563 // FIXME: Can we track this? Is it necessary?
564 return UnknownVal();
565 case MemRegion::ElementRegionKind:
566 // FIXME: How can we handle this? It's not good enough to subtract the
567 // offset from the base string length; consider "123\x00567" and &a[5].
568 return UnknownVal();
569 default:
570 // Other regions (mostly non-data) can't have a reliable C string length.
571 // In this case, an error is emitted and UndefinedVal is returned.
572 // The caller should always be prepared to handle this case.
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000573 if (ExplodedNode *N = C.generateNode(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000574 if (!BT_NotCString)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000575 BT_NotCString.reset(new BuiltinBug("API",
576 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000577
578 llvm::SmallString<120> buf;
579 llvm::raw_svector_ostream os(buf);
580
581 os << "Argument to byte string function is ";
582
583 if (SummarizeRegion(os, C.getASTContext(), MR))
584 os << ", which is not a null-terminated string";
585 else
586 os << "not a null-terminated string";
587
588 // Generate a report for this bug.
589 EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
590 os.str(), N);
591
592 report->addRange(Ex->getSourceRange());
593 C.EmitReport(report);
594 }
595
596 return UndefinedVal();
597 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000598}
599
Lenny Maiorani318dd922011-04-12 17:08:43 +0000600const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
601 const GRState *&state, const Expr *expr, SVal val) const {
602
603 // Get the memory region pointed to by the val.
604 const MemRegion *bufRegion = val.getAsRegion();
605 if (!bufRegion)
606 return NULL;
607
608 // Strip casts off the memory region.
609 bufRegion = bufRegion->StripCasts();
610
611 // Cast the memory region to a string region.
612 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
613 if (!strRegion)
614 return NULL;
615
616 // Return the actual string in the string region.
617 return strRegion->getStringLiteral();
618}
619
Jordy Rosee64f3112010-08-16 07:51:42 +0000620const GRState *CStringChecker::InvalidateBuffer(CheckerContext &C,
621 const GRState *state,
622 const Expr *E, SVal V) {
623 Loc *L = dyn_cast<Loc>(&V);
624 if (!L)
625 return state;
626
627 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
628 // some assumptions about the value that CFRefCount can't. Even so, it should
629 // probably be refactored.
630 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
631 const MemRegion *R = MR->getRegion()->StripCasts();
632
633 // Are we dealing with an ElementRegion? If so, we should be invalidating
634 // the super-region.
635 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
636 R = ER->getSuperRegion();
637 // FIXME: What about layers of ElementRegions?
638 }
639
640 // Invalidate this region.
641 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek25345282011-02-11 19:48:15 +0000642 return state->invalidateRegion(R, E, Count, NULL);
Jordy Rosee64f3112010-08-16 07:51:42 +0000643 }
644
645 // If we have a non-region value by chance, just remove the binding.
646 // FIXME: is this necessary or correct? This handles the non-Region
647 // cases. Is it ever valid to store to these?
648 return state->unbindLoc(*L);
649}
650
Jordy Rose19c5dd12010-07-27 01:37:31 +0000651bool CStringChecker::SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
652 const MemRegion *MR) {
653 const TypedRegion *TR = dyn_cast<TypedRegion>(MR);
654 if (!TR)
655 return false;
656
657 switch (TR->getKind()) {
658 case MemRegion::FunctionTextRegionKind: {
659 const FunctionDecl *FD = cast<FunctionTextRegion>(TR)->getDecl();
660 if (FD)
661 os << "the address of the function '" << FD << "'";
662 else
663 os << "the address of a function";
664 return true;
665 }
666 case MemRegion::BlockTextRegionKind:
667 os << "block text";
668 return true;
669 case MemRegion::BlockDataRegionKind:
670 os << "a block";
671 return true;
672 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000673 case MemRegion::CXXTempObjectRegionKind:
674 os << "a C++ temp object of type " << TR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000675 return true;
676 case MemRegion::VarRegionKind:
Zhongxing Xu018220c2010-08-11 06:10:55 +0000677 os << "a variable of type" << TR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000678 return true;
679 case MemRegion::FieldRegionKind:
Zhongxing Xu018220c2010-08-11 06:10:55 +0000680 os << "a field of type " << TR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000681 return true;
682 case MemRegion::ObjCIvarRegionKind:
Zhongxing Xu018220c2010-08-11 06:10:55 +0000683 os << "an instance variable of type " << TR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000684 return true;
685 default:
686 return false;
687 }
688}
689
Jordy Rosed325ffb2010-07-08 23:57:29 +0000690//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000691// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000692//===----------------------------------------------------------------------===//
693
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000694void CStringChecker::evalCopyCommon(CheckerContext &C,
695 const CallExpr *CE,
696 const GRState *state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000697 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000698 const Expr *Source, bool Restricted,
699 bool IsMempcpy) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000700 // See if the size argument is zero.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000701 SVal sizeVal = state->getSVal(Size);
702 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000703
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000704 const GRState *stateZeroSize, *stateNonZeroSize;
705 llvm::tie(stateZeroSize, stateNonZeroSize) = assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000706
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000707 // Get the value of the Dest.
708 SVal destVal = state->getSVal(Dest);
709
710 // If the size is zero, there won't be any actual memory access, so
711 // just bind the return value to the destination buffer and return.
712 if (stateZeroSize) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000713 C.addTransition(stateZeroSize);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000714 if (IsMempcpy)
715 state->BindExpr(CE, destVal);
716 else
717 state->BindExpr(CE, sizeVal);
718 return;
719 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000720
721 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000722 if (stateNonZeroSize) {
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000723
724 // Ensure the destination is not null. If it is NULL there will be a
725 // NULL pointer dereference.
726 state = checkNonNull(C, state, Dest, destVal);
727 if (!state)
728 return;
729
730 // Get the value of the Src.
731 SVal srcVal = state->getSVal(Source);
732
733 // Ensure the source is not null. If it is NULL there will be a
734 // NULL pointer dereference.
735 state = checkNonNull(C, state, Source, srcVal);
736 if (!state)
737 return;
738
739 // Ensure the buffers do not overlap.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000740 state = stateNonZeroSize;
Jordy Rosee64f3112010-08-16 07:51:42 +0000741 state = CheckBufferAccess(C, state, Size, Dest, Source,
742 /* FirstIsDst = */ true);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000743 if (Restricted)
744 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000745
746 if (state) {
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000747
748 // If this is mempcpy, get the byte after the last byte copied and
749 // bind the expr.
750 if (IsMempcpy) {
751 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
752
753 // Get the length to copy.
754 SVal lenVal = state->getSVal(Size);
755 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&lenVal);
756
757 // Get the byte after the last byte copied.
758 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
759 *destRegVal,
760 *lenValNonLoc,
761 Dest->getType());
762
763 // The byte after the last byte copied is the return value.
764 state = state->BindExpr(CE, lastElement);
765 }
766
Jordy Rosee64f3112010-08-16 07:51:42 +0000767 // Invalidate the destination.
768 // FIXME: Even if we can't perfectly model the copy, we should see if we
769 // can use LazyCompoundVals to copy the source values into the destination.
770 // This would probably remove any existing bindings past the end of the
771 // copied region, but that's still an improvement over blank invalidation.
772 state = InvalidateBuffer(C, state, Dest, state->getSVal(Dest));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000773 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +0000774 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000775 }
776}
777
778
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000779void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000780 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000781 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000782 const Expr *Dest = CE->getArg(0);
783 const GRState *state = C.getState();
784 state = state->BindExpr(CE, state->getSVal(Dest));
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000785 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
786}
787
788void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
789 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
790 // The return value is a pointer to the byte following the last written byte.
791 const Expr *Dest = CE->getArg(0);
792 const GRState *state = C.getState();
793
794 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000795}
796
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000797void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000798 // void *memmove(void *dst, const void *src, size_t n);
799 // The return value is the address of the destination buffer.
800 const Expr *Dest = CE->getArg(0);
801 const GRState *state = C.getState();
802 state = state->BindExpr(CE, state->getSVal(Dest));
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000803 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000804}
805
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000806void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000807 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000808 evalCopyCommon(C, CE, C.getState(),
809 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000810}
811
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000812void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000813 // int memcmp(const void *s1, const void *s2, size_t n);
814 const Expr *Left = CE->getArg(0);
815 const Expr *Right = CE->getArg(1);
816 const Expr *Size = CE->getArg(2);
817
818 const GRState *state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000819 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000820
Jordy Rosed325ffb2010-07-08 23:57:29 +0000821 // See if the size argument is zero.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000822 SVal sizeVal = state->getSVal(Size);
823 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000824
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000825 const GRState *stateZeroSize, *stateNonZeroSize;
826 llvm::tie(stateZeroSize, stateNonZeroSize) =
827 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000828
Jordy Rosed325ffb2010-07-08 23:57:29 +0000829 // If the size can be zero, the result will be 0 in that case, and we don't
830 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000831 if (stateZeroSize) {
832 state = stateZeroSize;
833 state = state->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000834 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000835 }
836
Jordy Rosed325ffb2010-07-08 23:57:29 +0000837 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000838 if (stateNonZeroSize) {
839 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +0000840 // If we know the two buffers are the same, we know the result is 0.
841 // First, get the two buffers' addresses. Another checker will have already
842 // made sure they're not undefined.
843 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(state->getSVal(Left));
844 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(state->getSVal(Right));
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000845
Jordy Rosed325ffb2010-07-08 23:57:29 +0000846 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000847 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000848 const GRState *StSameBuf, *StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000849 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000850
851 // If the two arguments might be the same buffer, we know the result is zero,
852 // and we only need to check one size.
853 if (StSameBuf) {
854 state = StSameBuf;
855 state = CheckBufferAccess(C, state, Size, Left);
856 if (state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000857 state = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000858 C.addTransition(state);
859 }
860 }
861
862 // If the two arguments might be different buffers, we have to check the
863 // size of both of them.
864 if (StNotSameBuf) {
865 state = StNotSameBuf;
866 state = CheckBufferAccess(C, state, Size, Left, Right);
867 if (state) {
868 // The return value is the comparison result, which we don't know.
869 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000870 SVal CmpV = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000871 state = state->BindExpr(CE, CmpV);
872 C.addTransition(state);
873 }
874 }
875 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000876}
877
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000878void CStringChecker::evalstrLength(CheckerContext &C,
879 const CallExpr *CE) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000880 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +0000881 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
882}
883
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000884void CStringChecker::evalstrnLength(CheckerContext &C,
885 const CallExpr *CE) const {
Ted Kremenekbe4242c2011-02-22 04:55:05 +0000886 // size_t strnlen(const char *s, size_t maxlen);
887 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
888}
889
890void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000891 bool IsStrnlen) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000892 const GRState *state = C.getState();
893 const Expr *Arg = CE->getArg(0);
894 SVal ArgVal = state->getSVal(Arg);
895
896 // Check that the argument is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000897 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000898
899 if (state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000900 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +0000901
902 // If the argument isn't a valid C string, there's no valid state to
903 // transition to.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000904 if (strLength.isUndef())
Jordy Rosea5261542010-08-14 21:02:52 +0000905 return;
906
Ted Kremenekbe4242c2011-02-22 04:55:05 +0000907 // If the check is for strnlen() then bind the return value to no more than
908 // the maxlen value.
909 if (IsStrnlen) {
910 const Expr *maxlenExpr = CE->getArg(1);
911 SVal maxlenVal = state->getSVal(maxlenExpr);
912
913 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
914 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
915
916 QualType cmpTy = C.getSValBuilder().getContext().IntTy;
917 const GRState *stateTrue, *stateFalse;
918
919 // Check if the strLength is greater than or equal to the maxlen
920 llvm::tie(stateTrue, stateFalse) =
921 state->assume(cast<DefinedOrUnknownSVal>
922 (C.getSValBuilder().evalBinOpNN(state, BO_GE,
923 *strLengthNL, *maxlenValNL,
924 cmpTy)));
925
926 // If the strLength is greater than or equal to the maxlen, set strLength
927 // to maxlen
928 if (stateTrue && !stateFalse) {
929 strLength = maxlenVal;
930 }
931 }
932
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000933 // If getCStringLength couldn't figure out the length, conjure a return
Jordy Rosea5261542010-08-14 21:02:52 +0000934 // value, so it can be used in constraints, at least.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000935 if (strLength.isUnknown()) {
Jordy Rosea5261542010-08-14 21:02:52 +0000936 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000937 strLength = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000938 }
Jordy Rosea5261542010-08-14 21:02:52 +0000939
940 // Bind the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000941 state = state->BindExpr(CE, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +0000942 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000943 }
944}
945
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000946void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosee64f3112010-08-16 07:51:42 +0000947 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +0000948 evalStrcpyCommon(C, CE,
949 /* returnEnd = */ false,
950 /* isBounded = */ false,
951 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +0000952}
953
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000954void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek0ef473f2011-02-22 04:58:34 +0000955 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +0000956 evalStrcpyCommon(C, CE,
957 /* returnEnd = */ false,
958 /* isBounded = */ true,
959 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +0000960}
961
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000962void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosee64f3112010-08-16 07:51:42 +0000963 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +0000964 evalStrcpyCommon(C, CE,
965 /* returnEnd = */ true,
966 /* isBounded = */ false,
967 /* isAppending = */ false);
968}
969
970void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
971 //char *strcat(char *restrict s1, const char *restrict s2);
972 evalStrcpyCommon(C, CE,
973 /* returnEnd = */ false,
974 /* isBounded = */ false,
975 /* isAppending = */ true);
976}
977
978void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
979 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
980 evalStrcpyCommon(C, CE,
981 /* returnEnd = */ false,
982 /* isBounded = */ true,
983 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +0000984}
985
Ted Kremenek9c149532010-12-01 21:57:22 +0000986void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +0000987 bool returnEnd, bool isBounded,
988 bool isAppending) const {
Jordy Rosee64f3112010-08-16 07:51:42 +0000989 const GRState *state = C.getState();
990
Lenny Maiorani067bbd02011-04-09 15:12:58 +0000991 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +0000992 const Expr *Dst = CE->getArg(0);
993 SVal DstVal = state->getSVal(Dst);
994
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000995 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000996 if (!state)
997 return;
998
999 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001000 const Expr *srcExpr = CE->getArg(1);
1001 SVal srcVal = state->getSVal(srcExpr);
1002 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001003 if (!state)
1004 return;
1005
1006 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001007 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001008
1009 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001010 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001011 return;
1012
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001013 // If the function is strncpy, strncat, etc... it is bounded.
1014 if (isBounded) {
1015 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001016 const Expr *lenExpr = CE->getArg(2);
1017 SVal lenVal = state->getSVal(lenExpr);
1018
1019 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1020 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1021
1022 QualType cmpTy = C.getSValBuilder().getContext().IntTy;
1023 const GRState *stateTrue, *stateFalse;
1024
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001025 // Check if the max number to copy is less than the length of the src.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001026 llvm::tie(stateTrue, stateFalse) =
1027 state->assume(cast<DefinedOrUnknownSVal>
1028 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1029 *strLengthNL, *lenValNL,
1030 cmpTy)));
1031
1032 if (stateTrue) {
1033 // Max number to copy is less than the length of the src, so the actual
1034 // strLength copied is the max number arg.
1035 strLength = lenVal;
1036 }
1037 }
1038
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001039 // If this is an appending function (strcat, strncat...) then set the
1040 // string length to strlen(src) + strlen(dst) since the buffer will
1041 // ultimately contain both.
1042 if (isAppending) {
1043 // Get the string length of the destination, or give up.
1044 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1045 if (dstStrLength.isUndef())
1046 return;
1047
1048 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&strLength);
1049 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1050
1051 // If src or dst cast to NonLoc is NULL, give up.
1052 if ((!srcStrLengthNL) || (!dstStrLengthNL))
1053 return;
1054
1055 QualType addTy = C.getSValBuilder().getContext().getSizeType();
1056
1057 strLength = C.getSValBuilder().evalBinOpNN(state, BO_Add,
1058 *srcStrLengthNL, *dstStrLengthNL,
1059 addTy);
1060 }
1061
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001062 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001063
1064 // If the destination is a MemRegion, try to check for a buffer overflow and
1065 // record the new string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001066 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rosee64f3112010-08-16 07:51:42 +00001067 // If the length is known, we can check for an overflow.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001068 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&strLength)) {
1069 SVal lastElement =
1070 C.getSValBuilder().evalBinOpLN(state, BO_Add, *dstRegVal,
1071 *knownStrLength, Dst->getType());
Jordy Rosee64f3112010-08-16 07:51:42 +00001072
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001073 state = CheckLocation(C, state, Dst, lastElement, /* IsDst = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001074 if (!state)
1075 return;
1076
1077 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001078 if (returnEnd)
1079 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001080 }
1081
1082 // Invalidate the destination. This must happen before we set the C string
1083 // length because invalidation will clear the length.
1084 // FIXME: Even if we can't perfectly model the copy, we should see if we
1085 // can use LazyCompoundVals to copy the source values into the destination.
1086 // This would probably remove any existing bindings past the end of the
1087 // string, but that's still an improvement over blank invalidation.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001088 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001089
1090 // Set the C string length of the destination.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001091 state = setCStringLength(state, dstRegVal->getRegion(), strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001092 }
1093
1094 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1095 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001096 if (returnEnd && Result.isUnknown()) {
1097 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosee64f3112010-08-16 07:51:42 +00001098 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001099 strLength = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rosee64f3112010-08-16 07:51:42 +00001100 }
1101
1102 // Set the return value.
1103 state = state->BindExpr(CE, Result);
1104 C.addTransition(state);
1105}
1106
Lenny Maiorani318dd922011-04-12 17:08:43 +00001107void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1108 //int strcmp(const char *restrict s1, const char *restrict s2);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001109 evalStrcmpCommon(C, CE, /* isBounded = */ false);
1110}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001111
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001112void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1113 //int strncmp(const char *restrict s1, const char *restrict s2, size_t n);
1114 evalStrcmpCommon(C, CE, /* isBounded = */ true);
1115}
1116
1117void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
1118 bool isBounded) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +00001119 const GRState *state = C.getState();
1120
1121 // Check that the first string is non-null
1122 const Expr *s1 = CE->getArg(0);
1123 SVal s1Val = state->getSVal(s1);
1124 state = checkNonNull(C, state, s1, s1Val);
1125 if (!state)
1126 return;
1127
1128 // Check that the second string is non-null.
1129 const Expr *s2 = CE->getArg(1);
1130 SVal s2Val = state->getSVal(s2);
1131 state = checkNonNull(C, state, s2, s2Val);
1132 if (!state)
1133 return;
1134
1135 // Get the string length of the first string or give up.
1136 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1137 if (s1Length.isUndef())
1138 return;
1139
1140 // Get the string length of the second string or give up.
1141 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1142 if (s2Length.isUndef())
1143 return;
1144
1145 // Get the string literal of the first string.
1146 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1147 if (!s1StrLiteral)
1148 return;
1149 llvm::StringRef s1StrRef = s1StrLiteral->getString();
1150
1151 // Get the string literal of the second string.
1152 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1153 if (!s2StrLiteral)
1154 return;
1155 llvm::StringRef s2StrRef = s2StrLiteral->getString();
1156
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001157 int result;
1158 if (isBounded) {
1159 // Get the max number of characters to compare.
1160 const Expr *lenExpr = CE->getArg(2);
1161 SVal lenVal = state->getSVal(lenExpr);
1162
1163 // Dynamically cast the length to a ConcreteInt. If it is not a ConcreteInt
1164 // then give up, otherwise get the value and use it as the bounds.
1165 nonloc::ConcreteInt *CI = dyn_cast<nonloc::ConcreteInt>(&lenVal);
1166 if (!CI)
1167 return;
1168 llvm::APSInt lenInt(CI->getValue());
1169
1170 // Compare using the bounds provided like strncmp() does.
1171 result = s1StrRef.compare(s2StrRef, (size_t)lenInt.getLimitedValue());
1172 } else {
1173 // Compare string 1 to string 2 the same way strcmp() does.
1174 result = s1StrRef.compare(s2StrRef);
1175 }
Lenny Maiorani318dd922011-04-12 17:08:43 +00001176
1177 // Build the SVal of the comparison to bind the return value.
1178 SValBuilder &svalBuilder = C.getSValBuilder();
1179 QualType intTy = svalBuilder.getContext().IntTy;
1180 SVal resultVal = svalBuilder.makeIntVal(result, intTy);
1181
1182 // Bind the return value of the expression.
1183 // Set the return value.
1184 state = state->BindExpr(CE, resultVal);
1185 C.addTransition(state);
1186}
1187
Jordy Rosed325ffb2010-07-08 23:57:29 +00001188//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001189// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001190//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001191
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001192bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001193 // Get the callee. All the functions we care about are C functions
1194 // with simple identifiers.
1195 const GRState *state = C.getState();
1196 const Expr *Callee = CE->getCallee();
1197 const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl();
1198
1199 if (!FD)
1200 return false;
1201
1202 // Get the name of the callee. If it's a builtin, strip off the prefix.
Douglas Gregor90d26a42010-11-01 23:16:05 +00001203 IdentifierInfo *II = FD->getIdentifier();
1204 if (!II) // if no identifier, not a simple C function
1205 return false;
1206 llvm::StringRef Name = II->getName();
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001207 if (Name.startswith("__builtin_"))
1208 Name = Name.substr(10);
1209
Ted Kremenek9c149532010-12-01 21:57:22 +00001210 FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
1211 .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001212 .Case("mempcpy", &CStringChecker::evalMempcpy)
Ted Kremenek9c149532010-12-01 21:57:22 +00001213 .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
1214 .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
1215 .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001216 .Cases("strncpy", "__strncpy_chk", &CStringChecker::evalStrncpy)
Ted Kremenek9c149532010-12-01 21:57:22 +00001217 .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001218 .Cases("strcat", "__strcat_chk", &CStringChecker::evalStrcat)
1219 .Cases("strncat", "__strncat_chk", &CStringChecker::evalStrncat)
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001220 .Case("strlen", &CStringChecker::evalstrLength)
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001221 .Case("strnlen", &CStringChecker::evalstrnLength)
Lenny Maiorani318dd922011-04-12 17:08:43 +00001222 .Case("strcmp", &CStringChecker::evalStrcmp)
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001223 .Case("strncmp", &CStringChecker::evalStrncmp)
Ted Kremenek9c149532010-12-01 21:57:22 +00001224 .Case("bcopy", &CStringChecker::evalBcopy)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001225 .Default(NULL);
1226
Jordy Rosed325ffb2010-07-08 23:57:29 +00001227 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001228 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001229 return false;
1230
Jordy Rosed325ffb2010-07-08 23:57:29 +00001231 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001232 (this->*evalFunction)(C, CE);
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001233 return true;
1234}
Jordy Rosea5261542010-08-14 21:02:52 +00001235
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001236void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001237 // Record string length for char a[] = "abc";
1238 const GRState *state = C.getState();
1239
1240 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1241 I != E; ++I) {
1242 const VarDecl *D = dyn_cast<VarDecl>(*I);
1243 if (!D)
1244 continue;
1245
1246 // FIXME: Handle array fields of structs.
1247 if (!D->getType()->isArrayType())
1248 continue;
1249
1250 const Expr *Init = D->getInit();
1251 if (!Init)
1252 continue;
1253 if (!isa<StringLiteral>(Init))
1254 continue;
1255
1256 Loc VarLoc = state->getLValue(D, C.getPredecessor()->getLocationContext());
1257 const MemRegion *MR = VarLoc.getAsRegion();
1258 if (!MR)
1259 continue;
1260
1261 SVal StrVal = state->getSVal(Init);
1262 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001263 DefinedOrUnknownSVal strLength
1264 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rosea5261542010-08-14 21:02:52 +00001265
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001266 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001267 }
1268
1269 C.addTransition(state);
1270}
1271
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001272bool CStringChecker::wantsRegionChangeUpdate(const GRState *state) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001273 CStringLength::EntryMap Entries = state->get<CStringLength>();
1274 return !Entries.isEmpty();
1275}
1276
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001277const GRState *
1278CStringChecker::checkRegionChanges(const GRState *state,
1279 const MemRegion * const *Begin,
1280 const MemRegion * const *End) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001281 CStringLength::EntryMap Entries = state->get<CStringLength>();
1282 if (Entries.isEmpty())
1283 return state;
1284
1285 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1286 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1287
1288 // First build sets for the changed regions and their super-regions.
1289 for ( ; Begin != End; ++Begin) {
1290 const MemRegion *MR = *Begin;
1291 Invalidated.insert(MR);
1292
1293 SuperRegions.insert(MR);
1294 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1295 MR = SR->getSuperRegion();
1296 SuperRegions.insert(MR);
1297 }
1298 }
1299
1300 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1301
1302 // Then loop over the entries in the current state.
1303 for (CStringLength::EntryMap::iterator I = Entries.begin(),
1304 E = Entries.end(); I != E; ++I) {
1305 const MemRegion *MR = I.getKey();
1306
1307 // Is this entry for a super-region of a changed region?
1308 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001309 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001310 continue;
1311 }
1312
1313 // Is this entry for a sub-region of a changed region?
1314 const MemRegion *Super = MR;
1315 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1316 Super = SR->getSuperRegion();
1317 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001318 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001319 break;
1320 }
1321 }
1322 }
1323
1324 return state->set<CStringLength>(Entries);
1325}
1326
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001327void CStringChecker::checkLiveSymbols(const GRState *state,
1328 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001329 // Mark all symbols in our string length map as valid.
1330 CStringLength::EntryMap Entries = state->get<CStringLength>();
1331
1332 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1333 I != E; ++I) {
1334 SVal Len = I.getData();
1335 if (SymbolRef Sym = Len.getAsSymbol())
1336 SR.markInUse(Sym);
1337 }
1338}
1339
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001340void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1341 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001342 if (!SR.hasDeadSymbols())
1343 return;
1344
1345 const GRState *state = C.getState();
1346 CStringLength::EntryMap Entries = state->get<CStringLength>();
1347 if (Entries.isEmpty())
1348 return;
1349
1350 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1351 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1352 I != E; ++I) {
1353 SVal Len = I.getData();
1354 if (SymbolRef Sym = Len.getAsSymbol()) {
1355 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00001356 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00001357 }
1358 }
1359
1360 state = state->set<CStringLength>(Entries);
Ted Kremenekd048c6e2010-12-20 21:19:09 +00001361 C.generateNode(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001362}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001363
1364void ento::registerCStringChecker(CheckerManager &mgr) {
1365 mgr.registerChecker<CStringChecker>();
1366}