blob: d9e49e4c4778df543ec20db08564ae4f6dc76fa7 [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,
Ted Kremenekaa181172011-05-02 19:42:42 +000045 const StoreManager::InvalidatedSymbols *,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000046 const MemRegion * const *Begin,
47 const MemRegion * const *End) const;
Jordy Rose134a2362010-07-06 23:11:01 +000048
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000049 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
50 const CallExpr *) const;
Jordy Rose134a2362010-07-06 23:11:01 +000051
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000052 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani79d74142011-03-31 21:36:53 +000053 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000054 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
55 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani79d74142011-03-31 21:36:53 +000056 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
57 const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +000058 const Expr *Size, const Expr *Source, const Expr *Dest,
Lenny Maiorani79d74142011-03-31 21:36:53 +000059 bool Restricted = false,
60 bool IsMempcpy = false) const;
Jordy Rosed5d2e502010-07-08 23:57:29 +000061
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000062 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose134a2362010-07-06 23:11:01 +000063
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000064 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
65 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek280a01f2011-02-22 04:55:05 +000066 void evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000067 bool IsStrnlen = false) const;
Jordy Roseb052e8f2010-07-27 01:37:31 +000068
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000069 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
70 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
71 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenekfb1a79a2011-02-22 04:58:34 +000072 void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool returnEnd,
Lenny Maiorani467dbd52011-04-09 15:12:58 +000073 bool isBounded, bool isAppending) const;
74
75 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
76 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose722f5582010-08-16 07:51:42 +000077
Lenny Maioranif3539ad2011-04-12 17:08:43 +000078 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranie553e402011-04-25 22:21:00 +000079 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani4af23c82011-04-28 15:09:11 +000080 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani0b510272011-05-02 19:05:49 +000081 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranie553e402011-04-25 22:21:00 +000082 void evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani4af23c82011-04-28 15:09:11 +000083 bool isBounded = false, bool ignoreCase = false) const;
Lenny Maioranif3539ad2011-04-12 17:08:43 +000084
Jordy Rose134a2362010-07-06 23:11:01 +000085 // Utility methods
Jordy Rosed5d2e502010-07-08 23:57:29 +000086 std::pair<const GRState*, const GRState*>
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000087 static assumeZero(CheckerContext &C,
88 const GRState *state, SVal V, QualType Ty);
Jordy Rosed5d2e502010-07-08 23:57:29 +000089
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000090 static const GRState *setCStringLength(const GRState *state,
91 const MemRegion *MR, SVal strLength);
92 static SVal getCStringLengthForRegion(CheckerContext &C,
93 const GRState *&state,
94 const Expr *Ex, const MemRegion *MR);
Ted Kremenek90af9092010-12-02 07:49:45 +000095 SVal getCStringLength(CheckerContext &C, const GRState *&state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +000096 const Expr *Ex, SVal Buf) const;
Jordy Roseb052e8f2010-07-27 01:37:31 +000097
Lenny Maioranif3539ad2011-04-12 17:08:43 +000098 const StringLiteral *getCStringLiteral(CheckerContext &C,
99 const GRState *&state,
100 const Expr *expr,
101 SVal val) const;
102
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000103 static const GRState *InvalidateBuffer(CheckerContext &C,
104 const GRState *state,
105 const Expr *Ex, SVal V);
Jordy Rose722f5582010-08-16 07:51:42 +0000106
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000107 static bool SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
108 const MemRegion *MR);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000109
110 // Re-usable checks
Ted Kremenek90af9092010-12-02 07:49:45 +0000111 const GRState *checkNonNull(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000112 const Expr *S, SVal l) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000113 const GRState *CheckLocation(CheckerContext &C, const GRState *state,
Jordy Rose722f5582010-08-16 07:51:42 +0000114 const Expr *S, SVal l,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000115 bool IsDestination = false) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000116 const GRState *CheckBufferAccess(CheckerContext &C, const GRState *state,
117 const Expr *Size,
118 const Expr *FirstBuf,
Jordy Rose722f5582010-08-16 07:51:42 +0000119 const Expr *SecondBuf = NULL,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000120 bool FirstIsDestination = false) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000121 const GRState *CheckOverlap(CheckerContext &C, const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000122 const Expr *Size, const Expr *First,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000123 const Expr *Second) const;
Ted Kremenek90af9092010-12-02 07:49:45 +0000124 void emitOverlapBug(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000125 const Stmt *First, const Stmt *Second) const;
Jordy Rose134a2362010-07-06 23:11:01 +0000126};
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000127
128class CStringLength {
129public:
130 typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
131};
Jordy Rose134a2362010-07-06 23:11:01 +0000132} //end anonymous namespace
133
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000134namespace clang {
Ted Kremenek98857c92010-12-23 07:20:52 +0000135namespace ento {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000136 template <>
137 struct GRStateTrait<CStringLength>
138 : public GRStatePartialTrait<CStringLength::EntryMap> {
139 static void *GDMIndex() { return CStringChecker::getTag(); }
140 };
141}
Argyrios Kyrtzidisca08fba2010-12-22 18:53:20 +0000142}
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000143
Jordy Rosed5d2e502010-07-08 23:57:29 +0000144//===----------------------------------------------------------------------===//
145// Individual checks and utility methods.
146//===----------------------------------------------------------------------===//
147
148std::pair<const GRState*, const GRState*>
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000149CStringChecker::assumeZero(CheckerContext &C, const GRState *state, SVal V,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000150 QualType Ty) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000151 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
152 if (!val)
Jordy Rosed5d2e502010-07-08 23:57:29 +0000153 return std::pair<const GRState*, const GRState *>(state, state);
Jordy Rose33c829a2010-07-07 07:48:06 +0000154
Ted Kremenek90af9092010-12-02 07:49:45 +0000155 SValBuilder &svalBuilder = C.getSValBuilder();
156 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
157 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000158}
Jordy Rose33c829a2010-07-07 07:48:06 +0000159
Ted Kremenek90af9092010-12-02 07:49:45 +0000160const GRState *CStringChecker::checkNonNull(CheckerContext &C,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000161 const GRState *state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000162 const Expr *S, SVal l) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000163 // If a previous check has failed, propagate the failure.
164 if (!state)
165 return NULL;
166
167 const GRState *stateNull, *stateNonNull;
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000168 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed5d2e502010-07-08 23:57:29 +0000169
170 if (stateNull && !stateNonNull) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000171 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rose33c829a2010-07-07 07:48:06 +0000172 if (!N)
173 return NULL;
174
Jordy Rosed5d2e502010-07-08 23:57:29 +0000175 if (!BT_Null)
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000176 BT_Null.reset(new BuiltinBug("API",
177 "Null pointer argument in call to byte string function"));
Jordy Rose33c829a2010-07-07 07:48:06 +0000178
179 // Generate a report for this bug.
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000180 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Jordy Rose33c829a2010-07-07 07:48:06 +0000181 EnhancedBugReport *report = new EnhancedBugReport(*BT,
182 BT->getDescription(), N);
183
184 report->addRange(S->getSourceRange());
185 report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, S);
186 C.EmitReport(report);
187 return NULL;
188 }
189
190 // From here on, assume that the value is non-null.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000191 assert(stateNonNull);
192 return stateNonNull;
Jordy Rose33c829a2010-07-07 07:48:06 +0000193}
194
Jordy Rose134a2362010-07-06 23:11:01 +0000195// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
196const GRState *CStringChecker::CheckLocation(CheckerContext &C,
197 const GRState *state,
Jordy Rose722f5582010-08-16 07:51:42 +0000198 const Expr *S, SVal l,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000199 bool IsDestination) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000200 // If a previous check has failed, propagate the failure.
201 if (!state)
202 return NULL;
203
Jordy Rose134a2362010-07-06 23:11:01 +0000204 // Check for out of bound array element access.
205 const MemRegion *R = l.getAsRegion();
206 if (!R)
207 return state;
208
Jordy Rose134a2362010-07-06 23:11:01 +0000209 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
210 if (!ER)
211 return state;
212
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000213 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Rose134a2362010-07-06 23:11:01 +0000214 "CheckLocation should only be called with char* ElementRegions");
215
216 // Get the size of the array.
Ted Kremenek90af9092010-12-02 07:49:45 +0000217 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
218 SValBuilder &svalBuilder = C.getSValBuilder();
219 SVal Extent = svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
Jordy Rose134a2362010-07-06 23:11:01 +0000220 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
221
222 // Get the index of the accessed element.
Gabor Greif230ddf32010-09-09 10:51:37 +0000223 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
Jordy Rose134a2362010-07-06 23:11:01 +0000224
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000225 const GRState *StInBound = state->assumeInBound(Idx, Size, true);
226 const GRState *StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Rose134a2362010-07-06 23:11:01 +0000227 if (StOutBound && !StInBound) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000228 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Rose134a2362010-07-06 23:11:01 +0000229 if (!N)
230 return NULL;
231
Jordy Rose722f5582010-08-16 07:51:42 +0000232 BuiltinBug *BT;
233 if (IsDestination) {
234 if (!BT_BoundsWrite) {
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000235 BT_BoundsWrite.reset(new BuiltinBug("Out-of-bound array access",
236 "Byte string function overflows destination buffer"));
Jordy Rose722f5582010-08-16 07:51:42 +0000237 }
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000238 BT = static_cast<BuiltinBug*>(BT_BoundsWrite.get());
Jordy Rose722f5582010-08-16 07:51:42 +0000239 } else {
240 if (!BT_Bounds) {
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000241 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
242 "Byte string function accesses out-of-bound array element"));
Jordy Rose722f5582010-08-16 07:51:42 +0000243 }
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000244 BT = static_cast<BuiltinBug*>(BT_Bounds.get());
Jordy Rose722f5582010-08-16 07:51:42 +0000245 }
Jordy Rose134a2362010-07-06 23:11:01 +0000246
247 // FIXME: It would be nice to eventually make this diagnostic more clear,
248 // e.g., by referencing the original declaration or by saying *why* this
249 // reference is outside the range.
250
251 // Generate a report for this bug.
Jordy Rose134a2362010-07-06 23:11:01 +0000252 RangedBugReport *report = new RangedBugReport(*BT, BT->getDescription(), N);
253
254 report->addRange(S->getSourceRange());
255 C.EmitReport(report);
256 return NULL;
257 }
258
259 // Array bound check succeeded. From this point forward the array bound
260 // should always succeed.
261 return StInBound;
262}
263
264const GRState *CStringChecker::CheckBufferAccess(CheckerContext &C,
265 const GRState *state,
266 const Expr *Size,
267 const Expr *FirstBuf,
Jordy Rose722f5582010-08-16 07:51:42 +0000268 const Expr *SecondBuf,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000269 bool FirstIsDestination) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000270 // If a previous check has failed, propagate the failure.
271 if (!state)
272 return NULL;
273
Ted Kremenek90af9092010-12-02 07:49:45 +0000274 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose134a2362010-07-06 23:11:01 +0000275 ASTContext &Ctx = C.getASTContext();
276
Ted Kremenek90af9092010-12-02 07:49:45 +0000277 QualType sizeTy = Size->getType();
Jordy Rose134a2362010-07-06 23:11:01 +0000278 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
279
Jordy Rose33c829a2010-07-07 07:48:06 +0000280 // Check that the first buffer is non-null.
281 SVal BufVal = state->getSVal(FirstBuf);
Ted Kremenek90af9092010-12-02 07:49:45 +0000282 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000283 if (!state)
284 return NULL;
285
Jordy Rosed5d2e502010-07-08 23:57:29 +0000286 // Get the access length and make sure it is known.
287 SVal LengthVal = state->getSVal(Size);
288 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
289 if (!Length)
290 return state;
291
Jordy Rose134a2362010-07-06 23:11:01 +0000292 // Compute the offset of the last element to be accessed: size-1.
Ted Kremenek90af9092010-12-02 07:49:45 +0000293 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
294 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
295 *Length, One, sizeTy));
Jordy Rose134a2362010-07-06 23:11:01 +0000296
Chris Lattner57540c52011-04-15 05:22:18 +0000297 // Check that the first buffer is sufficiently long.
Ted Kremenek90af9092010-12-02 07:49:45 +0000298 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
Jordy Roseafdb0532010-08-05 23:11:30 +0000299 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000300 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
301 LastOffset, PtrTy);
Jordy Rose722f5582010-08-16 07:51:42 +0000302 state = CheckLocation(C, state, FirstBuf, BufEnd, FirstIsDestination);
Jordy Rose134a2362010-07-06 23:11:01 +0000303
Jordy Roseafdb0532010-08-05 23:11:30 +0000304 // If the buffer isn't large enough, abort.
305 if (!state)
306 return NULL;
307 }
Jordy Rose134a2362010-07-06 23:11:01 +0000308
309 // If there's a second buffer, check it as well.
310 if (SecondBuf) {
311 BufVal = state->getSVal(SecondBuf);
Ted Kremenek90af9092010-12-02 07:49:45 +0000312 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000313 if (!state)
314 return NULL;
315
Ted Kremenek90af9092010-12-02 07:49:45 +0000316 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
Jordy Roseafdb0532010-08-05 23:11:30 +0000317 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000318 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
319 LastOffset, PtrTy);
Jordy Roseafdb0532010-08-05 23:11:30 +0000320 state = CheckLocation(C, state, SecondBuf, BufEnd);
321 }
Jordy Rose134a2362010-07-06 23:11:01 +0000322 }
323
324 // Large enough or not, return this state!
325 return state;
326}
327
328const GRState *CStringChecker::CheckOverlap(CheckerContext &C,
329 const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000330 const Expr *Size,
Jordy Rose134a2362010-07-06 23:11:01 +0000331 const Expr *First,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000332 const Expr *Second) const {
Jordy Rose134a2362010-07-06 23:11:01 +0000333 // Do a simple check for overlap: if the two arguments are from the same
334 // buffer, see if the end of the first is greater than the start of the second
335 // or vice versa.
336
Jordy Rosed5d2e502010-07-08 23:57:29 +0000337 // If a previous check has failed, propagate the failure.
338 if (!state)
339 return NULL;
340
Jordy Rose134a2362010-07-06 23:11:01 +0000341 const GRState *stateTrue, *stateFalse;
342
343 // Get the buffer values and make sure they're known locations.
Ted Kremenek90af9092010-12-02 07:49:45 +0000344 SVal firstVal = state->getSVal(First);
345 SVal secondVal = state->getSVal(Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000346
Ted Kremenek90af9092010-12-02 07:49:45 +0000347 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
348 if (!firstLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000349 return state;
350
Ted Kremenek90af9092010-12-02 07:49:45 +0000351 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
352 if (!secondLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000353 return state;
354
355 // Are the two values the same?
Ted Kremenek90af9092010-12-02 07:49:45 +0000356 SValBuilder &svalBuilder = C.getSValBuilder();
357 llvm::tie(stateTrue, stateFalse) =
358 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Rose134a2362010-07-06 23:11:01 +0000359
360 if (stateTrue && !stateFalse) {
361 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenek90af9092010-12-02 07:49:45 +0000362 emitOverlapBug(C, stateTrue, First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000363 return NULL;
364 }
365
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000366 // assume the two expressions are not equal.
Jordy Rose134a2362010-07-06 23:11:01 +0000367 assert(stateFalse);
368 state = stateFalse;
369
370 // Which value comes first?
Ted Kremenek90af9092010-12-02 07:49:45 +0000371 ASTContext &Ctx = svalBuilder.getContext();
372 QualType cmpTy = Ctx.IntTy;
373 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
374 *firstLoc, *secondLoc, cmpTy);
375 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
376 if (!reverseTest)
Jordy Rose134a2362010-07-06 23:11:01 +0000377 return state;
378
Ted Kremenek90af9092010-12-02 07:49:45 +0000379 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000380 if (stateTrue) {
381 if (stateFalse) {
382 // If we don't know which one comes first, we can't perform this test.
383 return state;
384 } else {
Ted Kremenek90af9092010-12-02 07:49:45 +0000385 // Switch the values so that firstVal is before secondVal.
386 Loc *tmpLoc = firstLoc;
387 firstLoc = secondLoc;
388 secondLoc = tmpLoc;
Jordy Rose134a2362010-07-06 23:11:01 +0000389
390 // Switch the Exprs as well, so that they still correspond.
391 const Expr *tmpExpr = First;
392 First = Second;
393 Second = tmpExpr;
394 }
395 }
396
397 // Get the length, and make sure it too is known.
398 SVal LengthVal = state->getSVal(Size);
399 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
400 if (!Length)
401 return state;
402
403 // Convert the first buffer's start address to char*.
404 // Bail out if the cast fails.
405 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Ted Kremenek90af9092010-12-02 07:49:45 +0000406 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy, First->getType());
Jordy Rose134a2362010-07-06 23:11:01 +0000407 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
408 if (!FirstStartLoc)
409 return state;
410
411 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenek90af9092010-12-02 07:49:45 +0000412 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Rose134a2362010-07-06 23:11:01 +0000413 *FirstStartLoc, *Length, CharPtrTy);
414 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
415 if (!FirstEndLoc)
416 return state;
417
418 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenek90af9092010-12-02 07:49:45 +0000419 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
420 *FirstEndLoc, *secondLoc, cmpTy);
Jordy Rose134a2362010-07-06 23:11:01 +0000421 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
422 if (!OverlapTest)
423 return state;
424
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000425 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000426
427 if (stateTrue && !stateFalse) {
428 // Overlap!
Ted Kremenek90af9092010-12-02 07:49:45 +0000429 emitOverlapBug(C, stateTrue, First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000430 return NULL;
431 }
432
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000433 // assume the two expressions don't overlap.
Jordy Rose134a2362010-07-06 23:11:01 +0000434 assert(stateFalse);
435 return stateFalse;
436}
437
Ted Kremenek90af9092010-12-02 07:49:45 +0000438void CStringChecker::emitOverlapBug(CheckerContext &C, const GRState *state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000439 const Stmt *First, const Stmt *Second) const {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000440 ExplodedNode *N = C.generateSink(state);
Jordy Rose134a2362010-07-06 23:11:01 +0000441 if (!N)
442 return;
443
444 if (!BT_Overlap)
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000445 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
Jordy Rose134a2362010-07-06 23:11:01 +0000446
447 // Generate a report for this bug.
448 RangedBugReport *report =
449 new RangedBugReport(*BT_Overlap,
450 "Arguments must not be overlapping buffers", N);
451 report->addRange(First->getSourceRange());
452 report->addRange(Second->getSourceRange());
453
454 C.EmitReport(report);
455}
456
Ted Kremenek90af9092010-12-02 07:49:45 +0000457const GRState *CStringChecker::setCStringLength(const GRState *state,
Jordy Rose722f5582010-08-16 07:51:42 +0000458 const MemRegion *MR,
Ted Kremenek90af9092010-12-02 07:49:45 +0000459 SVal strLength) {
460 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
461 if (strLength.isUnknown())
Jordy Rose722f5582010-08-16 07:51:42 +0000462 return state;
463
464 MR = MR->StripCasts();
465
466 switch (MR->getKind()) {
467 case MemRegion::StringRegionKind:
468 // FIXME: This can happen if we strcpy() into a string region. This is
469 // undefined [C99 6.4.5p6], but we should still warn about it.
470 return state;
471
472 case MemRegion::SymbolicRegionKind:
473 case MemRegion::AllocaRegionKind:
474 case MemRegion::VarRegionKind:
475 case MemRegion::FieldRegionKind:
476 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek90af9092010-12-02 07:49:45 +0000477 return state->set<CStringLength>(MR, strLength);
Jordy Rose722f5582010-08-16 07:51:42 +0000478
479 case MemRegion::ElementRegionKind:
480 // FIXME: Handle element regions by upper-bounding the parent region's
481 // string length.
482 return state;
483
484 default:
485 // Other regions (mostly non-data) can't have a reliable C string length.
486 // For now, just ignore the change.
487 // FIXME: These are rare but not impossible. We should output some kind of
488 // warning for things like strcpy((char[]){'a', 0}, "b");
489 return state;
490 }
491}
492
Ted Kremenek90af9092010-12-02 07:49:45 +0000493SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000494 const GRState *&state,
495 const Expr *Ex,
496 const MemRegion *MR) {
497 // If there's a recorded length, go ahead and return it.
498 const SVal *Recorded = state->get<CStringLength>(MR);
499 if (Recorded)
500 return *Recorded;
501
502 // Otherwise, get a new symbol and update the state.
503 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000504 SValBuilder &svalBuilder = C.getSValBuilder();
505 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000506 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
507 MR, Ex, sizeTy, Count);
Ted Kremenek90af9092010-12-02 07:49:45 +0000508 state = state->set<CStringLength>(MR, strLength);
509 return strLength;
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000510}
511
Ted Kremenek90af9092010-12-02 07:49:45 +0000512SVal CStringChecker::getCStringLength(CheckerContext &C, const GRState *&state,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000513 const Expr *Ex, SVal Buf) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000514 const MemRegion *MR = Buf.getAsRegion();
515 if (!MR) {
516 // If we can't get a region, see if it's something we /know/ isn't a
517 // C string. In the context of locations, the only time we can issue such
518 // a warning is for labels.
519 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000520 if (ExplodedNode *N = C.generateNode(state)) {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000521 if (!BT_NotCString)
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000522 BT_NotCString.reset(new BuiltinBug("API",
523 "Argument is not a null-terminated string."));
Jordy Roseb052e8f2010-07-27 01:37:31 +0000524
525 llvm::SmallString<120> buf;
526 llvm::raw_svector_ostream os(buf);
527 os << "Argument to byte string function is the address of the label '"
Chris Lattner5a9b1ec2011-02-17 05:38:27 +0000528 << Label->getLabel()->getName()
Jordy Roseb052e8f2010-07-27 01:37:31 +0000529 << "', which is not a null-terminated string";
530
531 // Generate a report for this bug.
532 EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
533 os.str(), N);
534
535 report->addRange(Ex->getSourceRange());
536 C.EmitReport(report);
537 }
538
539 return UndefinedVal();
540 }
541
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000542 // If it's not a region and not a label, give up.
543 return UnknownVal();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000544 }
545
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000546 // If we have a region, strip casts from it and see if we can figure out
547 // its length. For anything we can't figure out, just return UnknownVal.
548 MR = MR->StripCasts();
549
550 switch (MR->getKind()) {
551 case MemRegion::StringRegionKind: {
552 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
553 // so we can assume that the byte length is the correct C string length.
Ted Kremenek90af9092010-12-02 07:49:45 +0000554 SValBuilder &svalBuilder = C.getSValBuilder();
555 QualType sizeTy = svalBuilder.getContext().getSizeType();
556 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
557 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000558 }
559 case MemRegion::SymbolicRegionKind:
560 case MemRegion::AllocaRegionKind:
561 case MemRegion::VarRegionKind:
562 case MemRegion::FieldRegionKind:
563 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek90af9092010-12-02 07:49:45 +0000564 return getCStringLengthForRegion(C, state, Ex, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000565 case MemRegion::CompoundLiteralRegionKind:
566 // FIXME: Can we track this? Is it necessary?
567 return UnknownVal();
568 case MemRegion::ElementRegionKind:
569 // FIXME: How can we handle this? It's not good enough to subtract the
570 // offset from the base string length; consider "123\x00567" and &a[5].
571 return UnknownVal();
572 default:
573 // Other regions (mostly non-data) can't have a reliable C string length.
574 // In this case, an error is emitted and UndefinedVal is returned.
575 // The caller should always be prepared to handle this case.
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000576 if (ExplodedNode *N = C.generateNode(state)) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000577 if (!BT_NotCString)
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000578 BT_NotCString.reset(new BuiltinBug("API",
579 "Argument is not a null-terminated string."));
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000580
581 llvm::SmallString<120> buf;
582 llvm::raw_svector_ostream os(buf);
583
584 os << "Argument to byte string function is ";
585
586 if (SummarizeRegion(os, C.getASTContext(), MR))
587 os << ", which is not a null-terminated string";
588 else
589 os << "not a null-terminated string";
590
591 // Generate a report for this bug.
592 EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
593 os.str(), N);
594
595 report->addRange(Ex->getSourceRange());
596 C.EmitReport(report);
597 }
598
599 return UndefinedVal();
600 }
Jordy Roseb052e8f2010-07-27 01:37:31 +0000601}
602
Lenny Maioranif3539ad2011-04-12 17:08:43 +0000603const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
604 const GRState *&state, const Expr *expr, SVal val) const {
605
606 // Get the memory region pointed to by the val.
607 const MemRegion *bufRegion = val.getAsRegion();
608 if (!bufRegion)
609 return NULL;
610
611 // Strip casts off the memory region.
612 bufRegion = bufRegion->StripCasts();
613
614 // Cast the memory region to a string region.
615 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
616 if (!strRegion)
617 return NULL;
618
619 // Return the actual string in the string region.
620 return strRegion->getStringLiteral();
621}
622
Jordy Rose722f5582010-08-16 07:51:42 +0000623const GRState *CStringChecker::InvalidateBuffer(CheckerContext &C,
624 const GRState *state,
625 const Expr *E, SVal V) {
626 Loc *L = dyn_cast<Loc>(&V);
627 if (!L)
628 return state;
629
630 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
631 // some assumptions about the value that CFRefCount can't. Even so, it should
632 // probably be refactored.
633 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
634 const MemRegion *R = MR->getRegion()->StripCasts();
635
636 // Are we dealing with an ElementRegion? If so, we should be invalidating
637 // the super-region.
638 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
639 R = ER->getSuperRegion();
640 // FIXME: What about layers of ElementRegions?
641 }
642
643 // Invalidate this region.
644 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenekeddeba02011-02-11 19:48:15 +0000645 return state->invalidateRegion(R, E, Count, NULL);
Jordy Rose722f5582010-08-16 07:51:42 +0000646 }
647
648 // If we have a non-region value by chance, just remove the binding.
649 // FIXME: is this necessary or correct? This handles the non-Region
650 // cases. Is it ever valid to store to these?
651 return state->unbindLoc(*L);
652}
653
Jordy Roseb052e8f2010-07-27 01:37:31 +0000654bool CStringChecker::SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
655 const MemRegion *MR) {
656 const TypedRegion *TR = dyn_cast<TypedRegion>(MR);
657 if (!TR)
658 return false;
659
660 switch (TR->getKind()) {
661 case MemRegion::FunctionTextRegionKind: {
662 const FunctionDecl *FD = cast<FunctionTextRegion>(TR)->getDecl();
663 if (FD)
664 os << "the address of the function '" << FD << "'";
665 else
666 os << "the address of a function";
667 return true;
668 }
669 case MemRegion::BlockTextRegionKind:
670 os << "block text";
671 return true;
672 case MemRegion::BlockDataRegionKind:
673 os << "a block";
674 return true;
675 case MemRegion::CXXThisRegionKind:
Zhongxing Xu03207162010-11-26 08:52:48 +0000676 case MemRegion::CXXTempObjectRegionKind:
677 os << "a C++ temp object of type " << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000678 return true;
679 case MemRegion::VarRegionKind:
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000680 os << "a variable of type" << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000681 return true;
682 case MemRegion::FieldRegionKind:
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000683 os << "a field of type " << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000684 return true;
685 case MemRegion::ObjCIvarRegionKind:
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000686 os << "an instance variable of type " << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000687 return true;
688 default:
689 return false;
690 }
691}
692
Jordy Rosed5d2e502010-07-08 23:57:29 +0000693//===----------------------------------------------------------------------===//
Ted Kremenekdc891422010-12-01 21:57:22 +0000694// evaluation of individual function calls.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000695//===----------------------------------------------------------------------===//
696
Lenny Maiorani79d74142011-03-31 21:36:53 +0000697void CStringChecker::evalCopyCommon(CheckerContext &C,
698 const CallExpr *CE,
699 const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000700 const Expr *Size, const Expr *Dest,
Lenny Maiorani79d74142011-03-31 21:36:53 +0000701 const Expr *Source, bool Restricted,
702 bool IsMempcpy) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000703 // See if the size argument is zero.
Ted Kremenek90af9092010-12-02 07:49:45 +0000704 SVal sizeVal = state->getSVal(Size);
705 QualType sizeTy = Size->getType();
Jordy Rosed5d2e502010-07-08 23:57:29 +0000706
Ted Kremenek90af9092010-12-02 07:49:45 +0000707 const GRState *stateZeroSize, *stateNonZeroSize;
708 llvm::tie(stateZeroSize, stateNonZeroSize) = assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000709
Lenny Maiorani79d74142011-03-31 21:36:53 +0000710 // Get the value of the Dest.
711 SVal destVal = state->getSVal(Dest);
712
713 // If the size is zero, there won't be any actual memory access, so
714 // just bind the return value to the destination buffer and return.
715 if (stateZeroSize) {
Jordy Rose63b84be2011-06-04 00:04:22 +0000716 stateZeroSize = stateZeroSize->BindExpr(CE, destVal);
Ted Kremenek90af9092010-12-02 07:49:45 +0000717 C.addTransition(stateZeroSize);
Lenny Maiorani79d74142011-03-31 21:36:53 +0000718 }
Jordy Rosed5d2e502010-07-08 23:57:29 +0000719
720 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +0000721 if (stateNonZeroSize) {
Jordy Rose63b84be2011-06-04 00:04:22 +0000722 state = stateNonZeroSize;
Lenny Maiorani79d74142011-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.
Jordy Rose722f5582010-08-16 07:51:42 +0000740 state = CheckBufferAccess(C, state, Size, Dest, Source,
741 /* FirstIsDst = */ true);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000742 if (Restricted)
743 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rose722f5582010-08-16 07:51:42 +0000744
745 if (state) {
Lenny Maiorani79d74142011-03-31 21:36:53 +0000746
747 // If this is mempcpy, get the byte after the last byte copied and
748 // bind the expr.
749 if (IsMempcpy) {
750 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
751
752 // Get the length to copy.
753 SVal lenVal = state->getSVal(Size);
754 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&lenVal);
755
756 // Get the byte after the last byte copied.
757 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
758 *destRegVal,
759 *lenValNonLoc,
760 Dest->getType());
761
762 // The byte after the last byte copied is the return value.
763 state = state->BindExpr(CE, lastElement);
764 }
765
Jordy Rose722f5582010-08-16 07:51:42 +0000766 // Invalidate the destination.
767 // FIXME: Even if we can't perfectly model the copy, we should see if we
768 // can use LazyCompoundVals to copy the source values into the destination.
769 // This would probably remove any existing bindings past the end of the
770 // copied region, but that's still an improvement over blank invalidation.
771 state = InvalidateBuffer(C, state, Dest, state->getSVal(Dest));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000772 C.addTransition(state);
Jordy Rose722f5582010-08-16 07:51:42 +0000773 }
Jordy Rosed5d2e502010-07-08 23:57:29 +0000774 }
775}
776
777
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000778void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose134a2362010-07-06 23:11:01 +0000779 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Rose134a2362010-07-06 23:11:01 +0000780 // The return value is the address of the destination buffer.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000781 const Expr *Dest = CE->getArg(0);
782 const GRState *state = C.getState();
783 state = state->BindExpr(CE, state->getSVal(Dest));
Lenny Maiorani79d74142011-03-31 21:36:53 +0000784 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
785}
786
787void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
788 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
789 // The return value is a pointer to the byte following the last written byte.
790 const Expr *Dest = CE->getArg(0);
791 const GRState *state = C.getState();
792
793 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Rose134a2362010-07-06 23:11:01 +0000794}
795
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000796void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000797 // void *memmove(void *dst, const void *src, size_t n);
798 // The return value is the address of the destination buffer.
799 const Expr *Dest = CE->getArg(0);
800 const GRState *state = C.getState();
801 state = state->BindExpr(CE, state->getSVal(Dest));
Lenny Maiorani79d74142011-03-31 21:36:53 +0000802 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000803}
804
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000805void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000806 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maiorani79d74142011-03-31 21:36:53 +0000807 evalCopyCommon(C, CE, C.getState(),
808 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000809}
810
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000811void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose65136fb2010-07-07 08:15:01 +0000812 // int memcmp(const void *s1, const void *s2, size_t n);
813 const Expr *Left = CE->getArg(0);
814 const Expr *Right = CE->getArg(1);
815 const Expr *Size = CE->getArg(2);
816
817 const GRState *state = C.getState();
Ted Kremenek90af9092010-12-02 07:49:45 +0000818 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose65136fb2010-07-07 08:15:01 +0000819
Jordy Rosed5d2e502010-07-08 23:57:29 +0000820 // See if the size argument is zero.
Ted Kremenek90af9092010-12-02 07:49:45 +0000821 SVal sizeVal = state->getSVal(Size);
822 QualType sizeTy = Size->getType();
Jordy Rose65136fb2010-07-07 08:15:01 +0000823
Ted Kremenek90af9092010-12-02 07:49:45 +0000824 const GRState *stateZeroSize, *stateNonZeroSize;
825 llvm::tie(stateZeroSize, stateNonZeroSize) =
826 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rose65136fb2010-07-07 08:15:01 +0000827
Jordy Rosed5d2e502010-07-08 23:57:29 +0000828 // If the size can be zero, the result will be 0 in that case, and we don't
829 // have to check either of the buffers.
Ted Kremenek90af9092010-12-02 07:49:45 +0000830 if (stateZeroSize) {
831 state = stateZeroSize;
832 state = state->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000833 C.addTransition(state);
Jordy Rose65136fb2010-07-07 08:15:01 +0000834 }
835
Jordy Rosed5d2e502010-07-08 23:57:29 +0000836 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +0000837 if (stateNonZeroSize) {
838 state = stateNonZeroSize;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000839 // If we know the two buffers are the same, we know the result is 0.
840 // First, get the two buffers' addresses. Another checker will have already
841 // made sure they're not undefined.
842 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(state->getSVal(Left));
843 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(state->getSVal(Right));
Jordy Rose65136fb2010-07-07 08:15:01 +0000844
Jordy Rosed5d2e502010-07-08 23:57:29 +0000845 // See if they are the same.
Ted Kremenek90af9092010-12-02 07:49:45 +0000846 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000847 const GRState *StSameBuf, *StNotSameBuf;
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000848 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000849
850 // If the two arguments might be the same buffer, we know the result is zero,
851 // and we only need to check one size.
852 if (StSameBuf) {
853 state = StSameBuf;
854 state = CheckBufferAccess(C, state, Size, Left);
855 if (state) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000856 state = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000857 C.addTransition(state);
858 }
859 }
860
861 // If the two arguments might be different buffers, we have to check the
862 // size of both of them.
863 if (StNotSameBuf) {
864 state = StNotSameBuf;
865 state = CheckBufferAccess(C, state, Size, Left, Right);
866 if (state) {
867 // The return value is the comparison result, which we don't know.
868 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000869 SVal CmpV = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000870 state = state->BindExpr(CE, CmpV);
871 C.addTransition(state);
872 }
873 }
874 }
Jordy Rose65136fb2010-07-07 08:15:01 +0000875}
876
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000877void CStringChecker::evalstrLength(CheckerContext &C,
878 const CallExpr *CE) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000879 // size_t strlen(const char *s);
Ted Kremenek280a01f2011-02-22 04:55:05 +0000880 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
881}
882
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000883void CStringChecker::evalstrnLength(CheckerContext &C,
884 const CallExpr *CE) const {
Ted Kremenek280a01f2011-02-22 04:55:05 +0000885 // size_t strnlen(const char *s, size_t maxlen);
886 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
887}
888
889void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000890 bool IsStrnlen) const {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000891 const GRState *state = C.getState();
892 const Expr *Arg = CE->getArg(0);
893 SVal ArgVal = state->getSVal(Arg);
894
895 // Check that the argument is non-null.
Ted Kremenek90af9092010-12-02 07:49:45 +0000896 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000897
898 if (state) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000899 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000900
901 // If the argument isn't a valid C string, there's no valid state to
902 // transition to.
Ted Kremenek90af9092010-12-02 07:49:45 +0000903 if (strLength.isUndef())
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000904 return;
905
Ted Kremenek280a01f2011-02-22 04:55:05 +0000906 // If the check is for strnlen() then bind the return value to no more than
907 // the maxlen value.
908 if (IsStrnlen) {
909 const Expr *maxlenExpr = CE->getArg(1);
910 SVal maxlenVal = state->getSVal(maxlenExpr);
911
912 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
913 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
914
915 QualType cmpTy = C.getSValBuilder().getContext().IntTy;
916 const GRState *stateTrue, *stateFalse;
917
918 // Check if the strLength is greater than or equal to the maxlen
919 llvm::tie(stateTrue, stateFalse) =
920 state->assume(cast<DefinedOrUnknownSVal>
921 (C.getSValBuilder().evalBinOpNN(state, BO_GE,
922 *strLengthNL, *maxlenValNL,
923 cmpTy)));
924
925 // If the strLength is greater than or equal to the maxlen, set strLength
926 // to maxlen
927 if (stateTrue && !stateFalse) {
928 strLength = maxlenVal;
929 }
930 }
931
Ted Kremenek90af9092010-12-02 07:49:45 +0000932 // If getCStringLength couldn't figure out the length, conjure a return
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000933 // value, so it can be used in constraints, at least.
Ted Kremenek90af9092010-12-02 07:49:45 +0000934 if (strLength.isUnknown()) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000935 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000936 strLength = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000937 }
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000938
939 // Bind the return value.
Ted Kremenek90af9092010-12-02 07:49:45 +0000940 state = state->BindExpr(CE, strLength);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000941 C.addTransition(state);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000942 }
943}
944
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000945void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose722f5582010-08-16 07:51:42 +0000946 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000947 evalStrcpyCommon(C, CE,
948 /* returnEnd = */ false,
949 /* isBounded = */ false,
950 /* isAppending = */ false);
Ted Kremenekfb1a79a2011-02-22 04:58:34 +0000951}
952
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000953void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose4451cd42011-06-04 00:05:23 +0000954 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000955 evalStrcpyCommon(C, CE,
956 /* returnEnd = */ false,
957 /* isBounded = */ true,
958 /* isAppending = */ false);
Jordy Rose722f5582010-08-16 07:51:42 +0000959}
960
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +0000961void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rose722f5582010-08-16 07:51:42 +0000962 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000963 evalStrcpyCommon(C, CE,
964 /* returnEnd = */ true,
965 /* isBounded = */ false,
966 /* isAppending = */ false);
967}
968
969void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
970 //char *strcat(char *restrict s1, const char *restrict s2);
971 evalStrcpyCommon(C, CE,
972 /* returnEnd = */ false,
973 /* isBounded = */ false,
974 /* isAppending = */ true);
975}
976
977void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
978 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
979 evalStrcpyCommon(C, CE,
980 /* returnEnd = */ false,
981 /* isBounded = */ true,
982 /* isAppending = */ true);
Jordy Rose722f5582010-08-16 07:51:42 +0000983}
984
Ted Kremenekdc891422010-12-01 21:57:22 +0000985void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000986 bool returnEnd, bool isBounded,
987 bool isAppending) const {
Jordy Rose722f5582010-08-16 07:51:42 +0000988 const GRState *state = C.getState();
989
Lenny Maiorani467dbd52011-04-09 15:12:58 +0000990 // Check that the destination is non-null.
Jordy Rose722f5582010-08-16 07:51:42 +0000991 const Expr *Dst = CE->getArg(0);
992 SVal DstVal = state->getSVal(Dst);
993
Ted Kremenek90af9092010-12-02 07:49:45 +0000994 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +0000995 if (!state)
996 return;
997
998 // Check that the source is non-null.
Ted Kremenek90af9092010-12-02 07:49:45 +0000999 const Expr *srcExpr = CE->getArg(1);
1000 SVal srcVal = state->getSVal(srcExpr);
1001 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001002 if (!state)
1003 return;
1004
1005 // Get the string length of the source.
Ted Kremenek90af9092010-12-02 07:49:45 +00001006 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001007
1008 // If the source isn't a valid C string, give up.
Ted Kremenek90af9092010-12-02 07:49:45 +00001009 if (strLength.isUndef())
Jordy Rose722f5582010-08-16 07:51:42 +00001010 return;
1011
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001012 // If the function is strncpy, strncat, etc... it is bounded.
1013 if (isBounded) {
1014 // Get the max number of characters to copy.
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001015 const Expr *lenExpr = CE->getArg(2);
1016 SVal lenVal = state->getSVal(lenExpr);
1017
Lenny Maioranied2cc6c2011-04-28 18:59:43 +00001018 // Cast the length to a NonLoc SVal. If it is not a NonLoc then give up.
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001019 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
Lenny Maioranied2cc6c2011-04-28 18:59:43 +00001020 if (!strLengthNL)
1021 return;
1022
1023 // Cast the max length to a NonLoc SVal. If it is not a NonLoc then give up.
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001024 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
Lenny Maioranied2cc6c2011-04-28 18:59:43 +00001025 if (!lenValNL)
1026 return;
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001027
1028 QualType cmpTy = C.getSValBuilder().getContext().IntTy;
1029 const GRState *stateTrue, *stateFalse;
1030
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001031 // Check if the max number to copy is less than the length of the src.
Ted Kremenekfb1a79a2011-02-22 04:58:34 +00001032 llvm::tie(stateTrue, stateFalse) =
1033 state->assume(cast<DefinedOrUnknownSVal>
1034 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1035 *strLengthNL, *lenValNL,
1036 cmpTy)));
1037
1038 if (stateTrue) {
1039 // Max number to copy is less than the length of the src, so the actual
1040 // strLength copied is the max number arg.
1041 strLength = lenVal;
1042 }
1043 }
1044
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001045 // If this is an appending function (strcat, strncat...) then set the
1046 // string length to strlen(src) + strlen(dst) since the buffer will
1047 // ultimately contain both.
1048 if (isAppending) {
1049 // Get the string length of the destination, or give up.
1050 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1051 if (dstStrLength.isUndef())
1052 return;
1053
1054 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&strLength);
1055 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1056
1057 // If src or dst cast to NonLoc is NULL, give up.
1058 if ((!srcStrLengthNL) || (!dstStrLengthNL))
1059 return;
1060
1061 QualType addTy = C.getSValBuilder().getContext().getSizeType();
1062
1063 strLength = C.getSValBuilder().evalBinOpNN(state, BO_Add,
1064 *srcStrLengthNL, *dstStrLengthNL,
1065 addTy);
1066 }
1067
Ted Kremenek90af9092010-12-02 07:49:45 +00001068 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001069
1070 // If the destination is a MemRegion, try to check for a buffer overflow and
1071 // record the new string length.
Ted Kremenek90af9092010-12-02 07:49:45 +00001072 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rose722f5582010-08-16 07:51:42 +00001073 // If the length is known, we can check for an overflow.
Ted Kremenek90af9092010-12-02 07:49:45 +00001074 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&strLength)) {
1075 SVal lastElement =
1076 C.getSValBuilder().evalBinOpLN(state, BO_Add, *dstRegVal,
1077 *knownStrLength, Dst->getType());
Jordy Rose722f5582010-08-16 07:51:42 +00001078
Ted Kremenek90af9092010-12-02 07:49:45 +00001079 state = CheckLocation(C, state, Dst, lastElement, /* IsDst = */ true);
Jordy Rose722f5582010-08-16 07:51:42 +00001080 if (!state)
1081 return;
1082
1083 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001084 if (returnEnd)
1085 Result = lastElement;
Jordy Rose722f5582010-08-16 07:51:42 +00001086 }
1087
1088 // Invalidate the destination. This must happen before we set the C string
1089 // length because invalidation will clear the length.
1090 // FIXME: Even if we can't perfectly model the copy, we should see if we
1091 // can use LazyCompoundVals to copy the source values into the destination.
1092 // This would probably remove any existing bindings past the end of the
1093 // string, but that's still an improvement over blank invalidation.
Ted Kremenek90af9092010-12-02 07:49:45 +00001094 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rose722f5582010-08-16 07:51:42 +00001095
1096 // Set the C string length of the destination.
Ted Kremenek90af9092010-12-02 07:49:45 +00001097 state = setCStringLength(state, dstRegVal->getRegion(), strLength);
Jordy Rose722f5582010-08-16 07:51:42 +00001098 }
1099
1100 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1101 // overflow, we still need a result. Conjure a return value.
Ted Kremenek90af9092010-12-02 07:49:45 +00001102 if (returnEnd && Result.isUnknown()) {
1103 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose722f5582010-08-16 07:51:42 +00001104 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +00001105 strLength = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rose722f5582010-08-16 07:51:42 +00001106 }
1107
1108 // Set the return value.
1109 state = state->BindExpr(CE, Result);
1110 C.addTransition(state);
1111}
1112
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001113void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
1114 //int strcmp(const char *restrict s1, const char *restrict s2);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001115 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maioranie553e402011-04-25 22:21:00 +00001116}
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001117
Lenny Maioranie553e402011-04-25 22:21:00 +00001118void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
1119 //int strncmp(const char *restrict s1, const char *restrict s2, size_t n);
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001120 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1121}
1122
1123void CStringChecker::evalStrcasecmp(CheckerContext &C,
1124 const CallExpr *CE) const {
1125 //int strcasecmp(const char *restrict s1, const char *restrict s2);
1126 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maioranie553e402011-04-25 22:21:00 +00001127}
1128
Lenny Maiorani0b510272011-05-02 19:05:49 +00001129void CStringChecker::evalStrncasecmp(CheckerContext &C,
1130 const CallExpr *CE) const {
1131 //int strncasecmp(const char *restrict s1, const char *restrict s2, size_t n);
1132 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1133}
1134
Lenny Maioranie553e402011-04-25 22:21:00 +00001135void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001136 bool isBounded, bool ignoreCase) const {
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001137 const GRState *state = C.getState();
1138
1139 // Check that the first string is non-null
1140 const Expr *s1 = CE->getArg(0);
1141 SVal s1Val = state->getSVal(s1);
1142 state = checkNonNull(C, state, s1, s1Val);
1143 if (!state)
1144 return;
1145
1146 // Check that the second string is non-null.
1147 const Expr *s2 = CE->getArg(1);
1148 SVal s2Val = state->getSVal(s2);
1149 state = checkNonNull(C, state, s2, s2Val);
1150 if (!state)
1151 return;
1152
1153 // Get the string length of the first string or give up.
1154 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1155 if (s1Length.isUndef())
1156 return;
1157
1158 // Get the string length of the second string or give up.
1159 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1160 if (s2Length.isUndef())
1161 return;
1162
1163 // Get the string literal of the first string.
1164 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1165 if (!s1StrLiteral)
1166 return;
1167 llvm::StringRef s1StrRef = s1StrLiteral->getString();
1168
1169 // Get the string literal of the second string.
1170 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1171 if (!s2StrLiteral)
1172 return;
1173 llvm::StringRef s2StrRef = s2StrLiteral->getString();
1174
Lenny Maioranie553e402011-04-25 22:21:00 +00001175 int result;
1176 if (isBounded) {
1177 // Get the max number of characters to compare.
1178 const Expr *lenExpr = CE->getArg(2);
1179 SVal lenVal = state->getSVal(lenExpr);
1180
1181 // Dynamically cast the length to a ConcreteInt. If it is not a ConcreteInt
1182 // then give up, otherwise get the value and use it as the bounds.
1183 nonloc::ConcreteInt *CI = dyn_cast<nonloc::ConcreteInt>(&lenVal);
1184 if (!CI)
1185 return;
1186 llvm::APSInt lenInt(CI->getValue());
1187
Lenny Maiorani0b510272011-05-02 19:05:49 +00001188 // Create substrings of each to compare the prefix.
1189 s1StrRef = s1StrRef.substr(0, (size_t)lenInt.getLimitedValue());
1190 s2StrRef = s2StrRef.substr(0, (size_t)lenInt.getLimitedValue());
1191 }
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001192
Lenny Maiorani0b510272011-05-02 19:05:49 +00001193 if (ignoreCase) {
1194 // Compare string 1 to string 2 the same way strcasecmp() does.
1195 result = s1StrRef.compare_lower(s2StrRef);
Lenny Maioranie553e402011-04-25 22:21:00 +00001196 } else {
1197 // Compare string 1 to string 2 the same way strcmp() does.
Lenny Maiorani0b510272011-05-02 19:05:49 +00001198 result = s1StrRef.compare(s2StrRef);
Lenny Maioranie553e402011-04-25 22:21:00 +00001199 }
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001200
1201 // Build the SVal of the comparison to bind the return value.
1202 SValBuilder &svalBuilder = C.getSValBuilder();
1203 QualType intTy = svalBuilder.getContext().IntTy;
1204 SVal resultVal = svalBuilder.makeIntVal(result, intTy);
1205
1206 // Bind the return value of the expression.
1207 // Set the return value.
1208 state = state->BindExpr(CE, resultVal);
1209 C.addTransition(state);
1210}
1211
Jordy Rosed5d2e502010-07-08 23:57:29 +00001212//===----------------------------------------------------------------------===//
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001213// The driver method, and other Checker callbacks.
Jordy Rosed5d2e502010-07-08 23:57:29 +00001214//===----------------------------------------------------------------------===//
Jordy Rose134a2362010-07-06 23:11:01 +00001215
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001216bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Jordy Rose134a2362010-07-06 23:11:01 +00001217 // Get the callee. All the functions we care about are C functions
1218 // with simple identifiers.
1219 const GRState *state = C.getState();
1220 const Expr *Callee = CE->getCallee();
1221 const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl();
1222
1223 if (!FD)
1224 return false;
1225
1226 // Get the name of the callee. If it's a builtin, strip off the prefix.
Douglas Gregor4b8eca82010-11-01 23:16:05 +00001227 IdentifierInfo *II = FD->getIdentifier();
1228 if (!II) // if no identifier, not a simple C function
1229 return false;
1230 llvm::StringRef Name = II->getName();
Jordy Rose134a2362010-07-06 23:11:01 +00001231 if (Name.startswith("__builtin_"))
1232 Name = Name.substr(10);
1233
Ted Kremenekdc891422010-12-01 21:57:22 +00001234 FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
1235 .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
Jordy Roseaee7fb92011-06-03 23:42:56 +00001236 .Cases("mempcpy", "__mempcpy_chk", &CStringChecker::evalMempcpy)
Ted Kremenekdc891422010-12-01 21:57:22 +00001237 .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
1238 .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
1239 .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
Lenny Maiorani50668582011-05-03 16:34:26 +00001240 //.Cases("strncpy", "__strncpy_chk", &CStringChecker::evalStrncpy)
Ted Kremenekdc891422010-12-01 21:57:22 +00001241 .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
Lenny Maiorani467dbd52011-04-09 15:12:58 +00001242 .Cases("strcat", "__strcat_chk", &CStringChecker::evalStrcat)
1243 .Cases("strncat", "__strncat_chk", &CStringChecker::evalStrncat)
Ted Kremenek90af9092010-12-02 07:49:45 +00001244 .Case("strlen", &CStringChecker::evalstrLength)
Ted Kremenek280a01f2011-02-22 04:55:05 +00001245 .Case("strnlen", &CStringChecker::evalstrnLength)
Lenny Maioranif3539ad2011-04-12 17:08:43 +00001246 .Case("strcmp", &CStringChecker::evalStrcmp)
Lenny Maioranie553e402011-04-25 22:21:00 +00001247 .Case("strncmp", &CStringChecker::evalStrncmp)
Lenny Maiorani4af23c82011-04-28 15:09:11 +00001248 .Case("strcasecmp", &CStringChecker::evalStrcasecmp)
Lenny Maiorani0b510272011-05-02 19:05:49 +00001249 .Case("strncasecmp", &CStringChecker::evalStrncasecmp)
Ted Kremenekdc891422010-12-01 21:57:22 +00001250 .Case("bcopy", &CStringChecker::evalBcopy)
Jordy Rose134a2362010-07-06 23:11:01 +00001251 .Default(NULL);
1252
Jordy Rosed5d2e502010-07-08 23:57:29 +00001253 // If the callee isn't a string function, let another checker handle it.
Ted Kremenekdc891422010-12-01 21:57:22 +00001254 if (!evalFunction)
Jordy Rose134a2362010-07-06 23:11:01 +00001255 return false;
1256
Jordy Rosed5d2e502010-07-08 23:57:29 +00001257 // Check and evaluate the call.
Ted Kremenekdc891422010-12-01 21:57:22 +00001258 (this->*evalFunction)(C, CE);
Jordy Rose134a2362010-07-06 23:11:01 +00001259 return true;
1260}
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001261
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001262void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001263 // Record string length for char a[] = "abc";
1264 const GRState *state = C.getState();
1265
1266 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1267 I != E; ++I) {
1268 const VarDecl *D = dyn_cast<VarDecl>(*I);
1269 if (!D)
1270 continue;
1271
1272 // FIXME: Handle array fields of structs.
1273 if (!D->getType()->isArrayType())
1274 continue;
1275
1276 const Expr *Init = D->getInit();
1277 if (!Init)
1278 continue;
1279 if (!isa<StringLiteral>(Init))
1280 continue;
1281
1282 Loc VarLoc = state->getLValue(D, C.getPredecessor()->getLocationContext());
1283 const MemRegion *MR = VarLoc.getAsRegion();
1284 if (!MR)
1285 continue;
1286
1287 SVal StrVal = state->getSVal(Init);
1288 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenek90af9092010-12-02 07:49:45 +00001289 DefinedOrUnknownSVal strLength
1290 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001291
Ted Kremenek90af9092010-12-02 07:49:45 +00001292 state = state->set<CStringLength>(MR, strLength);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001293 }
1294
1295 C.addTransition(state);
1296}
1297
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001298bool CStringChecker::wantsRegionChangeUpdate(const GRState *state) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001299 CStringLength::EntryMap Entries = state->get<CStringLength>();
1300 return !Entries.isEmpty();
1301}
1302
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001303const GRState *
1304CStringChecker::checkRegionChanges(const GRState *state,
Ted Kremenekaa181172011-05-02 19:42:42 +00001305 const StoreManager::InvalidatedSymbols *,
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001306 const MemRegion * const *Begin,
1307 const MemRegion * const *End) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001308 CStringLength::EntryMap Entries = state->get<CStringLength>();
1309 if (Entries.isEmpty())
1310 return state;
1311
1312 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1313 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1314
1315 // First build sets for the changed regions and their super-regions.
1316 for ( ; Begin != End; ++Begin) {
1317 const MemRegion *MR = *Begin;
1318 Invalidated.insert(MR);
1319
1320 SuperRegions.insert(MR);
1321 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1322 MR = SR->getSuperRegion();
1323 SuperRegions.insert(MR);
1324 }
1325 }
1326
1327 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1328
1329 // Then loop over the entries in the current state.
1330 for (CStringLength::EntryMap::iterator I = Entries.begin(),
1331 E = Entries.end(); I != E; ++I) {
1332 const MemRegion *MR = I.getKey();
1333
1334 // Is this entry for a super-region of a changed region?
1335 if (SuperRegions.count(MR)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001336 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001337 continue;
1338 }
1339
1340 // Is this entry for a sub-region of a changed region?
1341 const MemRegion *Super = MR;
1342 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1343 Super = SR->getSuperRegion();
1344 if (Invalidated.count(Super)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001345 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001346 break;
1347 }
1348 }
1349 }
1350
1351 return state->set<CStringLength>(Entries);
1352}
1353
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001354void CStringChecker::checkLiveSymbols(const GRState *state,
1355 SymbolReaper &SR) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001356 // Mark all symbols in our string length map as valid.
1357 CStringLength::EntryMap Entries = state->get<CStringLength>();
1358
1359 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1360 I != E; ++I) {
1361 SVal Len = I.getData();
1362 if (SymbolRef Sym = Len.getAsSymbol())
1363 SR.markInUse(Sym);
1364 }
1365}
1366
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001367void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1368 CheckerContext &C) const {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001369 if (!SR.hasDeadSymbols())
1370 return;
1371
1372 const GRState *state = C.getState();
1373 CStringLength::EntryMap Entries = state->get<CStringLength>();
1374 if (Entries.isEmpty())
1375 return;
1376
1377 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1378 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1379 I != E; ++I) {
1380 SVal Len = I.getData();
1381 if (SymbolRef Sym = Len.getAsSymbol()) {
1382 if (SR.isDead(Sym))
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001383 Entries = F.remove(Entries, I.getKey());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001384 }
1385 }
1386
1387 state = state->set<CStringLength>(Entries);
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001388 C.generateNode(state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001389}
Argyrios Kyrtzidisc26f15d2011-02-24 01:05:30 +00001390
1391void ento::registerCStringChecker(CheckerManager &mgr) {
1392 mgr.registerChecker<CStringChecker>();
1393}