blob: e9722a6de6b81d053a738901fa958d10dcd34e13 [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 Kyrtzidis507ff532011-02-17 21:39:17 +000016#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000017#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerVisitor.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"
Jordy Rose134a2362010-07-06 23:11:01 +000020#include "llvm/ADT/StringSwitch.h"
21
22using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000023using namespace ento;
Jordy Rose134a2362010-07-06 23:11:01 +000024
25namespace {
26class CStringChecker : public CheckerVisitor<CStringChecker> {
Jordy Rose722f5582010-08-16 07:51:42 +000027 BugType *BT_Null, *BT_Bounds, *BT_BoundsWrite, *BT_Overlap, *BT_NotCString;
Jordy Rose134a2362010-07-06 23:11:01 +000028public:
29 CStringChecker()
Jordy Rose722f5582010-08-16 07:51:42 +000030 : BT_Null(0), BT_Bounds(0), BT_BoundsWrite(0), BT_Overlap(0), BT_NotCString(0)
31 {}
Jordy Rose134a2362010-07-06 23:11:01 +000032 static void *getTag() { static int tag; return &tag; }
33
Ted Kremenekdc891422010-12-01 21:57:22 +000034 bool evalCallExpr(CheckerContext &C, const CallExpr *CE);
Jordy Rose2a2e21c2010-08-14 21:02:52 +000035 void PreVisitDeclStmt(CheckerContext &C, const DeclStmt *DS);
36 void MarkLiveSymbols(const GRState *state, SymbolReaper &SR);
Ted Kremenekdc891422010-12-01 21:57:22 +000037 void evalDeadSymbols(CheckerContext &C, SymbolReaper &SR);
Ted Kremenek926c9622011-01-11 02:34:45 +000038 bool wantsRegionChangeUpdate(const GRState *state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +000039
40 const GRState *EvalRegionChanges(const GRState *state,
41 const MemRegion * const *Begin,
42 const MemRegion * const *End,
43 bool*);
Jordy Rose134a2362010-07-06 23:11:01 +000044
Jordy Rosed5d2e502010-07-08 23:57:29 +000045 typedef void (CStringChecker::*FnCheck)(CheckerContext &, const CallExpr *);
Jordy Rose134a2362010-07-06 23:11:01 +000046
Ted Kremenekdc891422010-12-01 21:57:22 +000047 void evalMemcpy(CheckerContext &C, const CallExpr *CE);
48 void evalMemmove(CheckerContext &C, const CallExpr *CE);
49 void evalBcopy(CheckerContext &C, const CallExpr *CE);
50 void evalCopyCommon(CheckerContext &C, const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +000051 const Expr *Size, const Expr *Source, const Expr *Dest,
52 bool Restricted = false);
53
Ted Kremenekdc891422010-12-01 21:57:22 +000054 void evalMemcmp(CheckerContext &C, const CallExpr *CE);
Jordy Rose134a2362010-07-06 23:11:01 +000055
Ted Kremenek90af9092010-12-02 07:49:45 +000056 void evalstrLength(CheckerContext &C, const CallExpr *CE);
Ted Kremenek280a01f2011-02-22 04:55:05 +000057 void evalstrnLength(CheckerContext &C, const CallExpr *CE);
58 void evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
59 bool IsStrnlen = false);
Jordy Roseb052e8f2010-07-27 01:37:31 +000060
Ted Kremenekdc891422010-12-01 21:57:22 +000061 void evalStrcpy(CheckerContext &C, const CallExpr *CE);
62 void evalStpcpy(CheckerContext &C, const CallExpr *CE);
Ted Kremenek90af9092010-12-02 07:49:45 +000063 void evalStrcpyCommon(CheckerContext &C, const CallExpr *CE, bool returnEnd);
Jordy Rose722f5582010-08-16 07:51:42 +000064
Jordy Rose134a2362010-07-06 23:11:01 +000065 // Utility methods
Jordy Rosed5d2e502010-07-08 23:57:29 +000066 std::pair<const GRState*, const GRState*>
Ted Kremenekc5bea1e2010-12-01 22:16:56 +000067 assumeZero(CheckerContext &C, const GRState *state, SVal V, QualType Ty);
Jordy Rosed5d2e502010-07-08 23:57:29 +000068
Ted Kremenek90af9092010-12-02 07:49:45 +000069 const GRState *setCStringLength(const GRState *state, const MemRegion *MR,
70 SVal strLength);
71 SVal getCStringLengthForRegion(CheckerContext &C, const GRState *&state,
Jordy Rose2a2e21c2010-08-14 21:02:52 +000072 const Expr *Ex, const MemRegion *MR);
Ted Kremenek90af9092010-12-02 07:49:45 +000073 SVal getCStringLength(CheckerContext &C, const GRState *&state,
Jordy Roseb052e8f2010-07-27 01:37:31 +000074 const Expr *Ex, SVal Buf);
75
Jordy Rose722f5582010-08-16 07:51:42 +000076 const GRState *InvalidateBuffer(CheckerContext &C, const GRState *state,
77 const Expr *Ex, SVal V);
78
Jordy Roseb052e8f2010-07-27 01:37:31 +000079 bool SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
80 const MemRegion *MR);
81
82 // Re-usable checks
Ted Kremenek90af9092010-12-02 07:49:45 +000083 const GRState *checkNonNull(CheckerContext &C, const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +000084 const Expr *S, SVal l);
Jordy Rose134a2362010-07-06 23:11:01 +000085 const GRState *CheckLocation(CheckerContext &C, const GRState *state,
Jordy Rose722f5582010-08-16 07:51:42 +000086 const Expr *S, SVal l,
87 bool IsDestination = false);
Jordy Rose134a2362010-07-06 23:11:01 +000088 const GRState *CheckBufferAccess(CheckerContext &C, const GRState *state,
89 const Expr *Size,
90 const Expr *FirstBuf,
Jordy Rose722f5582010-08-16 07:51:42 +000091 const Expr *SecondBuf = NULL,
92 bool FirstIsDestination = false);
Jordy Rose134a2362010-07-06 23:11:01 +000093 const GRState *CheckOverlap(CheckerContext &C, const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +000094 const Expr *Size, const Expr *First,
95 const Expr *Second);
Ted Kremenek90af9092010-12-02 07:49:45 +000096 void emitOverlapBug(CheckerContext &C, const GRState *state,
Jordy Rose134a2362010-07-06 23:11:01 +000097 const Stmt *First, const Stmt *Second);
98};
Jordy Rose2a2e21c2010-08-14 21:02:52 +000099
100class CStringLength {
101public:
102 typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
103};
Jordy Rose134a2362010-07-06 23:11:01 +0000104} //end anonymous namespace
105
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000106namespace clang {
Ted Kremenek98857c92010-12-23 07:20:52 +0000107namespace ento {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000108 template <>
109 struct GRStateTrait<CStringLength>
110 : public GRStatePartialTrait<CStringLength::EntryMap> {
111 static void *GDMIndex() { return CStringChecker::getTag(); }
112 };
113}
Argyrios Kyrtzidisca08fba2010-12-22 18:53:20 +0000114}
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000115
Argyrios Kyrtzidis507ff532011-02-17 21:39:17 +0000116static void RegisterCStringChecker(ExprEngine &Eng) {
Jordy Rose134a2362010-07-06 23:11:01 +0000117 Eng.registerCheck(new CStringChecker());
118}
119
Argyrios Kyrtzidis507ff532011-02-17 21:39:17 +0000120void ento::registerCStringChecker(CheckerManager &mgr) {
121 mgr.addCheckerRegisterFunction(RegisterCStringChecker);
122}
123
Jordy Rosed5d2e502010-07-08 23:57:29 +0000124//===----------------------------------------------------------------------===//
125// Individual checks and utility methods.
126//===----------------------------------------------------------------------===//
127
128std::pair<const GRState*, const GRState*>
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000129CStringChecker::assumeZero(CheckerContext &C, const GRState *state, SVal V,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000130 QualType Ty) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000131 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
132 if (!val)
Jordy Rosed5d2e502010-07-08 23:57:29 +0000133 return std::pair<const GRState*, const GRState *>(state, state);
Jordy Rose33c829a2010-07-07 07:48:06 +0000134
Ted Kremenek90af9092010-12-02 07:49:45 +0000135 SValBuilder &svalBuilder = C.getSValBuilder();
136 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
137 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000138}
Jordy Rose33c829a2010-07-07 07:48:06 +0000139
Ted Kremenek90af9092010-12-02 07:49:45 +0000140const GRState *CStringChecker::checkNonNull(CheckerContext &C,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000141 const GRState *state,
142 const Expr *S, SVal l) {
143 // If a previous check has failed, propagate the failure.
144 if (!state)
145 return NULL;
146
147 const GRState *stateNull, *stateNonNull;
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000148 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed5d2e502010-07-08 23:57:29 +0000149
150 if (stateNull && !stateNonNull) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000151 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rose33c829a2010-07-07 07:48:06 +0000152 if (!N)
153 return NULL;
154
Jordy Rosed5d2e502010-07-08 23:57:29 +0000155 if (!BT_Null)
156 BT_Null = new BuiltinBug("API",
Jordy Rose33c829a2010-07-07 07:48:06 +0000157 "Null pointer argument in call to byte string function");
158
159 // Generate a report for this bug.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000160 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null);
Jordy Rose33c829a2010-07-07 07:48:06 +0000161 EnhancedBugReport *report = new EnhancedBugReport(*BT,
162 BT->getDescription(), N);
163
164 report->addRange(S->getSourceRange());
165 report->addVisitorCreator(bugreporter::registerTrackNullOrUndefValue, S);
166 C.EmitReport(report);
167 return NULL;
168 }
169
170 // From here on, assume that the value is non-null.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000171 assert(stateNonNull);
172 return stateNonNull;
Jordy Rose33c829a2010-07-07 07:48:06 +0000173}
174
Jordy Rose134a2362010-07-06 23:11:01 +0000175// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
176const GRState *CStringChecker::CheckLocation(CheckerContext &C,
177 const GRState *state,
Jordy Rose722f5582010-08-16 07:51:42 +0000178 const Expr *S, SVal l,
179 bool IsDestination) {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000180 // If a previous check has failed, propagate the failure.
181 if (!state)
182 return NULL;
183
Jordy Rose134a2362010-07-06 23:11:01 +0000184 // Check for out of bound array element access.
185 const MemRegion *R = l.getAsRegion();
186 if (!R)
187 return state;
188
Jordy Rose134a2362010-07-06 23:11:01 +0000189 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
190 if (!ER)
191 return state;
192
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000193 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Rose134a2362010-07-06 23:11:01 +0000194 "CheckLocation should only be called with char* ElementRegions");
195
196 // Get the size of the array.
Ted Kremenek90af9092010-12-02 07:49:45 +0000197 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
198 SValBuilder &svalBuilder = C.getSValBuilder();
199 SVal Extent = svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
Jordy Rose134a2362010-07-06 23:11:01 +0000200 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
201
202 // Get the index of the accessed element.
Gabor Greif230ddf32010-09-09 10:51:37 +0000203 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
Jordy Rose134a2362010-07-06 23:11:01 +0000204
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000205 const GRState *StInBound = state->assumeInBound(Idx, Size, true);
206 const GRState *StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Rose134a2362010-07-06 23:11:01 +0000207 if (StOutBound && !StInBound) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000208 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Rose134a2362010-07-06 23:11:01 +0000209 if (!N)
210 return NULL;
211
Jordy Rose722f5582010-08-16 07:51:42 +0000212 BuiltinBug *BT;
213 if (IsDestination) {
214 if (!BT_BoundsWrite) {
215 BT_BoundsWrite = new BuiltinBug("Out-of-bound array access",
216 "Byte string function overflows destination buffer");
217 }
218 BT = static_cast<BuiltinBug*>(BT_BoundsWrite);
219 } else {
220 if (!BT_Bounds) {
221 BT_Bounds = new BuiltinBug("Out-of-bound array access",
222 "Byte string function accesses out-of-bound array element");
223 }
224 BT = static_cast<BuiltinBug*>(BT_Bounds);
225 }
Jordy Rose134a2362010-07-06 23:11:01 +0000226
227 // FIXME: It would be nice to eventually make this diagnostic more clear,
228 // e.g., by referencing the original declaration or by saying *why* this
229 // reference is outside the range.
230
231 // Generate a report for this bug.
Jordy Rose134a2362010-07-06 23:11:01 +0000232 RangedBugReport *report = new RangedBugReport(*BT, BT->getDescription(), N);
233
234 report->addRange(S->getSourceRange());
235 C.EmitReport(report);
236 return NULL;
237 }
238
239 // Array bound check succeeded. From this point forward the array bound
240 // should always succeed.
241 return StInBound;
242}
243
244const GRState *CStringChecker::CheckBufferAccess(CheckerContext &C,
245 const GRState *state,
246 const Expr *Size,
247 const Expr *FirstBuf,
Jordy Rose722f5582010-08-16 07:51:42 +0000248 const Expr *SecondBuf,
249 bool FirstIsDestination) {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000250 // If a previous check has failed, propagate the failure.
251 if (!state)
252 return NULL;
253
Ted Kremenek90af9092010-12-02 07:49:45 +0000254 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose134a2362010-07-06 23:11:01 +0000255 ASTContext &Ctx = C.getASTContext();
256
Ted Kremenek90af9092010-12-02 07:49:45 +0000257 QualType sizeTy = Size->getType();
Jordy Rose134a2362010-07-06 23:11:01 +0000258 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
259
Jordy Rose33c829a2010-07-07 07:48:06 +0000260 // Check that the first buffer is non-null.
261 SVal BufVal = state->getSVal(FirstBuf);
Ted Kremenek90af9092010-12-02 07:49:45 +0000262 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000263 if (!state)
264 return NULL;
265
Jordy Rosed5d2e502010-07-08 23:57:29 +0000266 // Get the access length and make sure it is known.
267 SVal LengthVal = state->getSVal(Size);
268 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
269 if (!Length)
270 return state;
271
Jordy Rose134a2362010-07-06 23:11:01 +0000272 // Compute the offset of the last element to be accessed: size-1.
Ted Kremenek90af9092010-12-02 07:49:45 +0000273 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
274 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
275 *Length, One, sizeTy));
Jordy Rose134a2362010-07-06 23:11:01 +0000276
Jordy Rose33c829a2010-07-07 07:48:06 +0000277 // Check that the first buffer is sufficently long.
Ted Kremenek90af9092010-12-02 07:49:45 +0000278 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
Jordy Roseafdb0532010-08-05 23:11:30 +0000279 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000280 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
281 LastOffset, PtrTy);
Jordy Rose722f5582010-08-16 07:51:42 +0000282 state = CheckLocation(C, state, FirstBuf, BufEnd, FirstIsDestination);
Jordy Rose134a2362010-07-06 23:11:01 +0000283
Jordy Roseafdb0532010-08-05 23:11:30 +0000284 // If the buffer isn't large enough, abort.
285 if (!state)
286 return NULL;
287 }
Jordy Rose134a2362010-07-06 23:11:01 +0000288
289 // If there's a second buffer, check it as well.
290 if (SecondBuf) {
291 BufVal = state->getSVal(SecondBuf);
Ted Kremenek90af9092010-12-02 07:49:45 +0000292 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rose33c829a2010-07-07 07:48:06 +0000293 if (!state)
294 return NULL;
295
Ted Kremenek90af9092010-12-02 07:49:45 +0000296 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
Jordy Roseafdb0532010-08-05 23:11:30 +0000297 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000298 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
299 LastOffset, PtrTy);
Jordy Roseafdb0532010-08-05 23:11:30 +0000300 state = CheckLocation(C, state, SecondBuf, BufEnd);
301 }
Jordy Rose134a2362010-07-06 23:11:01 +0000302 }
303
304 // Large enough or not, return this state!
305 return state;
306}
307
308const GRState *CStringChecker::CheckOverlap(CheckerContext &C,
309 const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000310 const Expr *Size,
Jordy Rose134a2362010-07-06 23:11:01 +0000311 const Expr *First,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000312 const Expr *Second) {
Jordy Rose134a2362010-07-06 23:11:01 +0000313 // Do a simple check for overlap: if the two arguments are from the same
314 // buffer, see if the end of the first is greater than the start of the second
315 // or vice versa.
316
Jordy Rosed5d2e502010-07-08 23:57:29 +0000317 // If a previous check has failed, propagate the failure.
318 if (!state)
319 return NULL;
320
Jordy Rose134a2362010-07-06 23:11:01 +0000321 const GRState *stateTrue, *stateFalse;
322
323 // Get the buffer values and make sure they're known locations.
Ted Kremenek90af9092010-12-02 07:49:45 +0000324 SVal firstVal = state->getSVal(First);
325 SVal secondVal = state->getSVal(Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000326
Ted Kremenek90af9092010-12-02 07:49:45 +0000327 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
328 if (!firstLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000329 return state;
330
Ted Kremenek90af9092010-12-02 07:49:45 +0000331 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
332 if (!secondLoc)
Jordy Rose134a2362010-07-06 23:11:01 +0000333 return state;
334
335 // Are the two values the same?
Ted Kremenek90af9092010-12-02 07:49:45 +0000336 SValBuilder &svalBuilder = C.getSValBuilder();
337 llvm::tie(stateTrue, stateFalse) =
338 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Rose134a2362010-07-06 23:11:01 +0000339
340 if (stateTrue && !stateFalse) {
341 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenek90af9092010-12-02 07:49:45 +0000342 emitOverlapBug(C, stateTrue, First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000343 return NULL;
344 }
345
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000346 // assume the two expressions are not equal.
Jordy Rose134a2362010-07-06 23:11:01 +0000347 assert(stateFalse);
348 state = stateFalse;
349
350 // Which value comes first?
Ted Kremenek90af9092010-12-02 07:49:45 +0000351 ASTContext &Ctx = svalBuilder.getContext();
352 QualType cmpTy = Ctx.IntTy;
353 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
354 *firstLoc, *secondLoc, cmpTy);
355 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
356 if (!reverseTest)
Jordy Rose134a2362010-07-06 23:11:01 +0000357 return state;
358
Ted Kremenek90af9092010-12-02 07:49:45 +0000359 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000360 if (stateTrue) {
361 if (stateFalse) {
362 // If we don't know which one comes first, we can't perform this test.
363 return state;
364 } else {
Ted Kremenek90af9092010-12-02 07:49:45 +0000365 // Switch the values so that firstVal is before secondVal.
366 Loc *tmpLoc = firstLoc;
367 firstLoc = secondLoc;
368 secondLoc = tmpLoc;
Jordy Rose134a2362010-07-06 23:11:01 +0000369
370 // Switch the Exprs as well, so that they still correspond.
371 const Expr *tmpExpr = First;
372 First = Second;
373 Second = tmpExpr;
374 }
375 }
376
377 // Get the length, and make sure it too is known.
378 SVal LengthVal = state->getSVal(Size);
379 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
380 if (!Length)
381 return state;
382
383 // Convert the first buffer's start address to char*.
384 // Bail out if the cast fails.
385 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Ted Kremenek90af9092010-12-02 07:49:45 +0000386 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy, First->getType());
Jordy Rose134a2362010-07-06 23:11:01 +0000387 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
388 if (!FirstStartLoc)
389 return state;
390
391 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenek90af9092010-12-02 07:49:45 +0000392 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Rose134a2362010-07-06 23:11:01 +0000393 *FirstStartLoc, *Length, CharPtrTy);
394 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
395 if (!FirstEndLoc)
396 return state;
397
398 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenek90af9092010-12-02 07:49:45 +0000399 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
400 *FirstEndLoc, *secondLoc, cmpTy);
Jordy Rose134a2362010-07-06 23:11:01 +0000401 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
402 if (!OverlapTest)
403 return state;
404
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000405 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Rose134a2362010-07-06 23:11:01 +0000406
407 if (stateTrue && !stateFalse) {
408 // Overlap!
Ted Kremenek90af9092010-12-02 07:49:45 +0000409 emitOverlapBug(C, stateTrue, First, Second);
Jordy Rose134a2362010-07-06 23:11:01 +0000410 return NULL;
411 }
412
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000413 // assume the two expressions don't overlap.
Jordy Rose134a2362010-07-06 23:11:01 +0000414 assert(stateFalse);
415 return stateFalse;
416}
417
Ted Kremenek90af9092010-12-02 07:49:45 +0000418void CStringChecker::emitOverlapBug(CheckerContext &C, const GRState *state,
Jordy Rose134a2362010-07-06 23:11:01 +0000419 const Stmt *First, const Stmt *Second) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000420 ExplodedNode *N = C.generateSink(state);
Jordy Rose134a2362010-07-06 23:11:01 +0000421 if (!N)
422 return;
423
424 if (!BT_Overlap)
425 BT_Overlap = new BugType("Unix API", "Improper arguments");
426
427 // Generate a report for this bug.
428 RangedBugReport *report =
429 new RangedBugReport(*BT_Overlap,
430 "Arguments must not be overlapping buffers", N);
431 report->addRange(First->getSourceRange());
432 report->addRange(Second->getSourceRange());
433
434 C.EmitReport(report);
435}
436
Ted Kremenek90af9092010-12-02 07:49:45 +0000437const GRState *CStringChecker::setCStringLength(const GRState *state,
Jordy Rose722f5582010-08-16 07:51:42 +0000438 const MemRegion *MR,
Ted Kremenek90af9092010-12-02 07:49:45 +0000439 SVal strLength) {
440 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
441 if (strLength.isUnknown())
Jordy Rose722f5582010-08-16 07:51:42 +0000442 return state;
443
444 MR = MR->StripCasts();
445
446 switch (MR->getKind()) {
447 case MemRegion::StringRegionKind:
448 // FIXME: This can happen if we strcpy() into a string region. This is
449 // undefined [C99 6.4.5p6], but we should still warn about it.
450 return state;
451
452 case MemRegion::SymbolicRegionKind:
453 case MemRegion::AllocaRegionKind:
454 case MemRegion::VarRegionKind:
455 case MemRegion::FieldRegionKind:
456 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek90af9092010-12-02 07:49:45 +0000457 return state->set<CStringLength>(MR, strLength);
Jordy Rose722f5582010-08-16 07:51:42 +0000458
459 case MemRegion::ElementRegionKind:
460 // FIXME: Handle element regions by upper-bounding the parent region's
461 // string length.
462 return state;
463
464 default:
465 // Other regions (mostly non-data) can't have a reliable C string length.
466 // For now, just ignore the change.
467 // FIXME: These are rare but not impossible. We should output some kind of
468 // warning for things like strcpy((char[]){'a', 0}, "b");
469 return state;
470 }
471}
472
Ted Kremenek90af9092010-12-02 07:49:45 +0000473SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000474 const GRState *&state,
475 const Expr *Ex,
476 const MemRegion *MR) {
477 // If there's a recorded length, go ahead and return it.
478 const SVal *Recorded = state->get<CStringLength>(MR);
479 if (Recorded)
480 return *Recorded;
481
482 // Otherwise, get a new symbol and update the state.
483 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000484 SValBuilder &svalBuilder = C.getSValBuilder();
485 QualType sizeTy = svalBuilder.getContext().getSizeType();
486 SVal strLength = svalBuilder.getMetadataSymbolVal(getTag(), MR, Ex, sizeTy, Count);
487 state = state->set<CStringLength>(MR, strLength);
488 return strLength;
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000489}
490
Ted Kremenek90af9092010-12-02 07:49:45 +0000491SVal CStringChecker::getCStringLength(CheckerContext &C, const GRState *&state,
Jordy Roseb052e8f2010-07-27 01:37:31 +0000492 const Expr *Ex, SVal Buf) {
493 const MemRegion *MR = Buf.getAsRegion();
494 if (!MR) {
495 // If we can't get a region, see if it's something we /know/ isn't a
496 // C string. In the context of locations, the only time we can issue such
497 // a warning is for labels.
498 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000499 if (ExplodedNode *N = C.generateNode(state)) {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000500 if (!BT_NotCString)
501 BT_NotCString = new BuiltinBug("API",
502 "Argument is not a null-terminated string.");
503
504 llvm::SmallString<120> buf;
505 llvm::raw_svector_ostream os(buf);
506 os << "Argument to byte string function is the address of the label '"
Chris Lattner5a9b1ec2011-02-17 05:38:27 +0000507 << Label->getLabel()->getName()
Jordy Roseb052e8f2010-07-27 01:37:31 +0000508 << "', which is not a null-terminated string";
509
510 // Generate a report for this bug.
511 EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
512 os.str(), N);
513
514 report->addRange(Ex->getSourceRange());
515 C.EmitReport(report);
516 }
517
518 return UndefinedVal();
519 }
520
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000521 // If it's not a region and not a label, give up.
522 return UnknownVal();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000523 }
524
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000525 // If we have a region, strip casts from it and see if we can figure out
526 // its length. For anything we can't figure out, just return UnknownVal.
527 MR = MR->StripCasts();
528
529 switch (MR->getKind()) {
530 case MemRegion::StringRegionKind: {
531 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
532 // so we can assume that the byte length is the correct C string length.
Ted Kremenek90af9092010-12-02 07:49:45 +0000533 SValBuilder &svalBuilder = C.getSValBuilder();
534 QualType sizeTy = svalBuilder.getContext().getSizeType();
535 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
536 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000537 }
538 case MemRegion::SymbolicRegionKind:
539 case MemRegion::AllocaRegionKind:
540 case MemRegion::VarRegionKind:
541 case MemRegion::FieldRegionKind:
542 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek90af9092010-12-02 07:49:45 +0000543 return getCStringLengthForRegion(C, state, Ex, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000544 case MemRegion::CompoundLiteralRegionKind:
545 // FIXME: Can we track this? Is it necessary?
546 return UnknownVal();
547 case MemRegion::ElementRegionKind:
548 // FIXME: How can we handle this? It's not good enough to subtract the
549 // offset from the base string length; consider "123\x00567" and &a[5].
550 return UnknownVal();
551 default:
552 // Other regions (mostly non-data) can't have a reliable C string length.
553 // In this case, an error is emitted and UndefinedVal is returned.
554 // The caller should always be prepared to handle this case.
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000555 if (ExplodedNode *N = C.generateNode(state)) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000556 if (!BT_NotCString)
557 BT_NotCString = new BuiltinBug("API",
558 "Argument is not a null-terminated string.");
559
560 llvm::SmallString<120> buf;
561 llvm::raw_svector_ostream os(buf);
562
563 os << "Argument to byte string function is ";
564
565 if (SummarizeRegion(os, C.getASTContext(), MR))
566 os << ", which is not a null-terminated string";
567 else
568 os << "not a null-terminated string";
569
570 // Generate a report for this bug.
571 EnhancedBugReport *report = new EnhancedBugReport(*BT_NotCString,
572 os.str(), N);
573
574 report->addRange(Ex->getSourceRange());
575 C.EmitReport(report);
576 }
577
578 return UndefinedVal();
579 }
Jordy Roseb052e8f2010-07-27 01:37:31 +0000580}
581
Jordy Rose722f5582010-08-16 07:51:42 +0000582const GRState *CStringChecker::InvalidateBuffer(CheckerContext &C,
583 const GRState *state,
584 const Expr *E, SVal V) {
585 Loc *L = dyn_cast<Loc>(&V);
586 if (!L)
587 return state;
588
589 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
590 // some assumptions about the value that CFRefCount can't. Even so, it should
591 // probably be refactored.
592 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
593 const MemRegion *R = MR->getRegion()->StripCasts();
594
595 // Are we dealing with an ElementRegion? If so, we should be invalidating
596 // the super-region.
597 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
598 R = ER->getSuperRegion();
599 // FIXME: What about layers of ElementRegions?
600 }
601
602 // Invalidate this region.
603 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenekeddeba02011-02-11 19:48:15 +0000604 return state->invalidateRegion(R, E, Count, NULL);
Jordy Rose722f5582010-08-16 07:51:42 +0000605 }
606
607 // If we have a non-region value by chance, just remove the binding.
608 // FIXME: is this necessary or correct? This handles the non-Region
609 // cases. Is it ever valid to store to these?
610 return state->unbindLoc(*L);
611}
612
Jordy Roseb052e8f2010-07-27 01:37:31 +0000613bool CStringChecker::SummarizeRegion(llvm::raw_ostream& os, ASTContext& Ctx,
614 const MemRegion *MR) {
615 const TypedRegion *TR = dyn_cast<TypedRegion>(MR);
616 if (!TR)
617 return false;
618
619 switch (TR->getKind()) {
620 case MemRegion::FunctionTextRegionKind: {
621 const FunctionDecl *FD = cast<FunctionTextRegion>(TR)->getDecl();
622 if (FD)
623 os << "the address of the function '" << FD << "'";
624 else
625 os << "the address of a function";
626 return true;
627 }
628 case MemRegion::BlockTextRegionKind:
629 os << "block text";
630 return true;
631 case MemRegion::BlockDataRegionKind:
632 os << "a block";
633 return true;
634 case MemRegion::CXXThisRegionKind:
Zhongxing Xu03207162010-11-26 08:52:48 +0000635 case MemRegion::CXXTempObjectRegionKind:
636 os << "a C++ temp object of type " << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000637 return true;
638 case MemRegion::VarRegionKind:
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000639 os << "a variable of type" << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000640 return true;
641 case MemRegion::FieldRegionKind:
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000642 os << "a field of type " << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000643 return true;
644 case MemRegion::ObjCIvarRegionKind:
Zhongxing Xu8de0a3d2010-08-11 06:10:55 +0000645 os << "an instance variable of type " << TR->getValueType().getAsString();
Jordy Roseb052e8f2010-07-27 01:37:31 +0000646 return true;
647 default:
648 return false;
649 }
650}
651
Jordy Rosed5d2e502010-07-08 23:57:29 +0000652//===----------------------------------------------------------------------===//
Ted Kremenekdc891422010-12-01 21:57:22 +0000653// evaluation of individual function calls.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000654//===----------------------------------------------------------------------===//
655
Ted Kremenekdc891422010-12-01 21:57:22 +0000656void CStringChecker::evalCopyCommon(CheckerContext &C, const GRState *state,
Jordy Rosed5d2e502010-07-08 23:57:29 +0000657 const Expr *Size, const Expr *Dest,
658 const Expr *Source, bool Restricted) {
659 // See if the size argument is zero.
Ted Kremenek90af9092010-12-02 07:49:45 +0000660 SVal sizeVal = state->getSVal(Size);
661 QualType sizeTy = Size->getType();
Jordy Rosed5d2e502010-07-08 23:57:29 +0000662
Ted Kremenek90af9092010-12-02 07:49:45 +0000663 const GRState *stateZeroSize, *stateNonZeroSize;
664 llvm::tie(stateZeroSize, stateNonZeroSize) = assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000665
666 // If the size is zero, there won't be any actual memory access.
Ted Kremenek90af9092010-12-02 07:49:45 +0000667 if (stateZeroSize)
668 C.addTransition(stateZeroSize);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000669
670 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +0000671 if (stateNonZeroSize) {
672 state = stateNonZeroSize;
Jordy Rose722f5582010-08-16 07:51:42 +0000673 state = CheckBufferAccess(C, state, Size, Dest, Source,
674 /* FirstIsDst = */ true);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000675 if (Restricted)
676 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rose722f5582010-08-16 07:51:42 +0000677
678 if (state) {
679 // Invalidate the destination.
680 // FIXME: Even if we can't perfectly model the copy, we should see if we
681 // can use LazyCompoundVals to copy the source values into the destination.
682 // This would probably remove any existing bindings past the end of the
683 // copied region, but that's still an improvement over blank invalidation.
684 state = InvalidateBuffer(C, state, Dest, state->getSVal(Dest));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000685 C.addTransition(state);
Jordy Rose722f5582010-08-16 07:51:42 +0000686 }
Jordy Rosed5d2e502010-07-08 23:57:29 +0000687 }
688}
689
690
Ted Kremenekdc891422010-12-01 21:57:22 +0000691void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) {
Jordy Rose134a2362010-07-06 23:11:01 +0000692 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Rose134a2362010-07-06 23:11:01 +0000693 // The return value is the address of the destination buffer.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000694 const Expr *Dest = CE->getArg(0);
695 const GRState *state = C.getState();
696 state = state->BindExpr(CE, state->getSVal(Dest));
Ted Kremenekdc891422010-12-01 21:57:22 +0000697 evalCopyCommon(C, state, CE->getArg(2), Dest, CE->getArg(1), true);
Jordy Rose134a2362010-07-06 23:11:01 +0000698}
699
Ted Kremenekdc891422010-12-01 21:57:22 +0000700void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000701 // void *memmove(void *dst, const void *src, size_t n);
702 // The return value is the address of the destination buffer.
703 const Expr *Dest = CE->getArg(0);
704 const GRState *state = C.getState();
705 state = state->BindExpr(CE, state->getSVal(Dest));
Ted Kremenekdc891422010-12-01 21:57:22 +0000706 evalCopyCommon(C, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000707}
708
Ted Kremenekdc891422010-12-01 21:57:22 +0000709void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) {
Jordy Rosed5d2e502010-07-08 23:57:29 +0000710 // void bcopy(const void *src, void *dst, size_t n);
Ted Kremenekdc891422010-12-01 21:57:22 +0000711 evalCopyCommon(C, C.getState(), CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000712}
713
Ted Kremenekdc891422010-12-01 21:57:22 +0000714void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) {
Jordy Rose65136fb2010-07-07 08:15:01 +0000715 // int memcmp(const void *s1, const void *s2, size_t n);
716 const Expr *Left = CE->getArg(0);
717 const Expr *Right = CE->getArg(1);
718 const Expr *Size = CE->getArg(2);
719
720 const GRState *state = C.getState();
Ted Kremenek90af9092010-12-02 07:49:45 +0000721 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose65136fb2010-07-07 08:15:01 +0000722
Jordy Rosed5d2e502010-07-08 23:57:29 +0000723 // See if the size argument is zero.
Ted Kremenek90af9092010-12-02 07:49:45 +0000724 SVal sizeVal = state->getSVal(Size);
725 QualType sizeTy = Size->getType();
Jordy Rose65136fb2010-07-07 08:15:01 +0000726
Ted Kremenek90af9092010-12-02 07:49:45 +0000727 const GRState *stateZeroSize, *stateNonZeroSize;
728 llvm::tie(stateZeroSize, stateNonZeroSize) =
729 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rose65136fb2010-07-07 08:15:01 +0000730
Jordy Rosed5d2e502010-07-08 23:57:29 +0000731 // If the size can be zero, the result will be 0 in that case, and we don't
732 // have to check either of the buffers.
Ted Kremenek90af9092010-12-02 07:49:45 +0000733 if (stateZeroSize) {
734 state = stateZeroSize;
735 state = state->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000736 C.addTransition(state);
Jordy Rose65136fb2010-07-07 08:15:01 +0000737 }
738
Jordy Rosed5d2e502010-07-08 23:57:29 +0000739 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenek90af9092010-12-02 07:49:45 +0000740 if (stateNonZeroSize) {
741 state = stateNonZeroSize;
Jordy Rosed5d2e502010-07-08 23:57:29 +0000742 // If we know the two buffers are the same, we know the result is 0.
743 // First, get the two buffers' addresses. Another checker will have already
744 // made sure they're not undefined.
745 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(state->getSVal(Left));
746 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(state->getSVal(Right));
Jordy Rose65136fb2010-07-07 08:15:01 +0000747
Jordy Rosed5d2e502010-07-08 23:57:29 +0000748 // See if they are the same.
Ted Kremenek90af9092010-12-02 07:49:45 +0000749 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000750 const GRState *StSameBuf, *StNotSameBuf;
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000751 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000752
753 // If the two arguments might be the same buffer, we know the result is zero,
754 // and we only need to check one size.
755 if (StSameBuf) {
756 state = StSameBuf;
757 state = CheckBufferAccess(C, state, Size, Left);
758 if (state) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000759 state = StSameBuf->BindExpr(CE, svalBuilder.makeZeroVal(CE->getType()));
Jordy Rosed5d2e502010-07-08 23:57:29 +0000760 C.addTransition(state);
761 }
762 }
763
764 // If the two arguments might be different buffers, we have to check the
765 // size of both of them.
766 if (StNotSameBuf) {
767 state = StNotSameBuf;
768 state = CheckBufferAccess(C, state, Size, Left, Right);
769 if (state) {
770 // The return value is the comparison result, which we don't know.
771 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000772 SVal CmpV = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rosed5d2e502010-07-08 23:57:29 +0000773 state = state->BindExpr(CE, CmpV);
774 C.addTransition(state);
775 }
776 }
777 }
Jordy Rose65136fb2010-07-07 08:15:01 +0000778}
779
Ted Kremenek90af9092010-12-02 07:49:45 +0000780void CStringChecker::evalstrLength(CheckerContext &C, const CallExpr *CE) {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000781 // size_t strlen(const char *s);
Ted Kremenek280a01f2011-02-22 04:55:05 +0000782 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
783}
784
785void CStringChecker::evalstrnLength(CheckerContext &C, const CallExpr *CE) {
786 // size_t strnlen(const char *s, size_t maxlen);
787 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
788}
789
790void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
791 bool IsStrnlen) {
Jordy Roseb052e8f2010-07-27 01:37:31 +0000792 const GRState *state = C.getState();
793 const Expr *Arg = CE->getArg(0);
794 SVal ArgVal = state->getSVal(Arg);
795
796 // Check that the argument is non-null.
Ted Kremenek90af9092010-12-02 07:49:45 +0000797 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000798
799 if (state) {
Ted Kremenek90af9092010-12-02 07:49:45 +0000800 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000801
802 // If the argument isn't a valid C string, there's no valid state to
803 // transition to.
Ted Kremenek90af9092010-12-02 07:49:45 +0000804 if (strLength.isUndef())
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000805 return;
806
Ted Kremenek280a01f2011-02-22 04:55:05 +0000807 // If the check is for strnlen() then bind the return value to no more than
808 // the maxlen value.
809 if (IsStrnlen) {
810 const Expr *maxlenExpr = CE->getArg(1);
811 SVal maxlenVal = state->getSVal(maxlenExpr);
812
813 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
814 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
815
816 QualType cmpTy = C.getSValBuilder().getContext().IntTy;
817 const GRState *stateTrue, *stateFalse;
818
819 // Check if the strLength is greater than or equal to the maxlen
820 llvm::tie(stateTrue, stateFalse) =
821 state->assume(cast<DefinedOrUnknownSVal>
822 (C.getSValBuilder().evalBinOpNN(state, BO_GE,
823 *strLengthNL, *maxlenValNL,
824 cmpTy)));
825
826 // If the strLength is greater than or equal to the maxlen, set strLength
827 // to maxlen
828 if (stateTrue && !stateFalse) {
829 strLength = maxlenVal;
830 }
831 }
832
Ted Kremenek90af9092010-12-02 07:49:45 +0000833 // If getCStringLength couldn't figure out the length, conjure a return
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000834 // value, so it can be used in constraints, at least.
Ted Kremenek90af9092010-12-02 07:49:45 +0000835 if (strLength.isUnknown()) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000836 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000837 strLength = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000838 }
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000839
840 // Bind the return value.
Ted Kremenek90af9092010-12-02 07:49:45 +0000841 state = state->BindExpr(CE, strLength);
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000842 C.addTransition(state);
Jordy Roseb052e8f2010-07-27 01:37:31 +0000843 }
844}
845
Ted Kremenekdc891422010-12-01 21:57:22 +0000846void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) {
Jordy Rose722f5582010-08-16 07:51:42 +0000847 // char *strcpy(char *restrict dst, const char *restrict src);
Ted Kremenek90af9092010-12-02 07:49:45 +0000848 evalStrcpyCommon(C, CE, /* returnEnd = */ false);
Jordy Rose722f5582010-08-16 07:51:42 +0000849}
850
Ted Kremenekdc891422010-12-01 21:57:22 +0000851void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) {
Jordy Rose722f5582010-08-16 07:51:42 +0000852 // char *stpcpy(char *restrict dst, const char *restrict src);
Ted Kremenek90af9092010-12-02 07:49:45 +0000853 evalStrcpyCommon(C, CE, /* returnEnd = */ true);
Jordy Rose722f5582010-08-16 07:51:42 +0000854}
855
Ted Kremenekdc891422010-12-01 21:57:22 +0000856void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Ted Kremenek90af9092010-12-02 07:49:45 +0000857 bool returnEnd) {
Jordy Rose722f5582010-08-16 07:51:42 +0000858 const GRState *state = C.getState();
859
860 // Check that the destination is non-null
861 const Expr *Dst = CE->getArg(0);
862 SVal DstVal = state->getSVal(Dst);
863
Ted Kremenek90af9092010-12-02 07:49:45 +0000864 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +0000865 if (!state)
866 return;
867
868 // Check that the source is non-null.
Ted Kremenek90af9092010-12-02 07:49:45 +0000869 const Expr *srcExpr = CE->getArg(1);
870 SVal srcVal = state->getSVal(srcExpr);
871 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +0000872 if (!state)
873 return;
874
875 // Get the string length of the source.
Ted Kremenek90af9092010-12-02 07:49:45 +0000876 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rose722f5582010-08-16 07:51:42 +0000877
878 // If the source isn't a valid C string, give up.
Ted Kremenek90af9092010-12-02 07:49:45 +0000879 if (strLength.isUndef())
Jordy Rose722f5582010-08-16 07:51:42 +0000880 return;
881
Ted Kremenek90af9092010-12-02 07:49:45 +0000882 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rose722f5582010-08-16 07:51:42 +0000883
884 // If the destination is a MemRegion, try to check for a buffer overflow and
885 // record the new string length.
Ted Kremenek90af9092010-12-02 07:49:45 +0000886 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rose722f5582010-08-16 07:51:42 +0000887 // If the length is known, we can check for an overflow.
Ted Kremenek90af9092010-12-02 07:49:45 +0000888 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&strLength)) {
889 SVal lastElement =
890 C.getSValBuilder().evalBinOpLN(state, BO_Add, *dstRegVal,
891 *knownStrLength, Dst->getType());
Jordy Rose722f5582010-08-16 07:51:42 +0000892
Ted Kremenek90af9092010-12-02 07:49:45 +0000893 state = CheckLocation(C, state, Dst, lastElement, /* IsDst = */ true);
Jordy Rose722f5582010-08-16 07:51:42 +0000894 if (!state)
895 return;
896
897 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenek90af9092010-12-02 07:49:45 +0000898 if (returnEnd)
899 Result = lastElement;
Jordy Rose722f5582010-08-16 07:51:42 +0000900 }
901
902 // Invalidate the destination. This must happen before we set the C string
903 // length because invalidation will clear the length.
904 // FIXME: Even if we can't perfectly model the copy, we should see if we
905 // can use LazyCompoundVals to copy the source values into the destination.
906 // This would probably remove any existing bindings past the end of the
907 // string, but that's still an improvement over blank invalidation.
Ted Kremenek90af9092010-12-02 07:49:45 +0000908 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rose722f5582010-08-16 07:51:42 +0000909
910 // Set the C string length of the destination.
Ted Kremenek90af9092010-12-02 07:49:45 +0000911 state = setCStringLength(state, dstRegVal->getRegion(), strLength);
Jordy Rose722f5582010-08-16 07:51:42 +0000912 }
913
914 // If this is a stpcpy-style copy, but we were unable to check for a buffer
915 // overflow, we still need a result. Conjure a return value.
Ted Kremenek90af9092010-12-02 07:49:45 +0000916 if (returnEnd && Result.isUnknown()) {
917 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose722f5582010-08-16 07:51:42 +0000918 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenek90af9092010-12-02 07:49:45 +0000919 strLength = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rose722f5582010-08-16 07:51:42 +0000920 }
921
922 // Set the return value.
923 state = state->BindExpr(CE, Result);
924 C.addTransition(state);
925}
926
Jordy Rosed5d2e502010-07-08 23:57:29 +0000927//===----------------------------------------------------------------------===//
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000928// The driver method, and other Checker callbacks.
Jordy Rosed5d2e502010-07-08 23:57:29 +0000929//===----------------------------------------------------------------------===//
Jordy Rose134a2362010-07-06 23:11:01 +0000930
Ted Kremenekdc891422010-12-01 21:57:22 +0000931bool CStringChecker::evalCallExpr(CheckerContext &C, const CallExpr *CE) {
Jordy Rose134a2362010-07-06 23:11:01 +0000932 // Get the callee. All the functions we care about are C functions
933 // with simple identifiers.
934 const GRState *state = C.getState();
935 const Expr *Callee = CE->getCallee();
936 const FunctionDecl *FD = state->getSVal(Callee).getAsFunctionDecl();
937
938 if (!FD)
939 return false;
940
941 // Get the name of the callee. If it's a builtin, strip off the prefix.
Douglas Gregor4b8eca82010-11-01 23:16:05 +0000942 IdentifierInfo *II = FD->getIdentifier();
943 if (!II) // if no identifier, not a simple C function
944 return false;
945 llvm::StringRef Name = II->getName();
Jordy Rose134a2362010-07-06 23:11:01 +0000946 if (Name.startswith("__builtin_"))
947 Name = Name.substr(10);
948
Ted Kremenekdc891422010-12-01 21:57:22 +0000949 FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
950 .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
951 .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
952 .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
953 .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
954 .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
Ted Kremenek90af9092010-12-02 07:49:45 +0000955 .Case("strlen", &CStringChecker::evalstrLength)
Ted Kremenek280a01f2011-02-22 04:55:05 +0000956 .Case("strnlen", &CStringChecker::evalstrnLength)
Ted Kremenekdc891422010-12-01 21:57:22 +0000957 .Case("bcopy", &CStringChecker::evalBcopy)
Jordy Rose134a2362010-07-06 23:11:01 +0000958 .Default(NULL);
959
Jordy Rosed5d2e502010-07-08 23:57:29 +0000960 // If the callee isn't a string function, let another checker handle it.
Ted Kremenekdc891422010-12-01 21:57:22 +0000961 if (!evalFunction)
Jordy Rose134a2362010-07-06 23:11:01 +0000962 return false;
963
Jordy Rosed5d2e502010-07-08 23:57:29 +0000964 // Check and evaluate the call.
Ted Kremenekdc891422010-12-01 21:57:22 +0000965 (this->*evalFunction)(C, CE);
Jordy Rose134a2362010-07-06 23:11:01 +0000966 return true;
967}
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000968
969void CStringChecker::PreVisitDeclStmt(CheckerContext &C, const DeclStmt *DS) {
970 // Record string length for char a[] = "abc";
971 const GRState *state = C.getState();
972
973 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
974 I != E; ++I) {
975 const VarDecl *D = dyn_cast<VarDecl>(*I);
976 if (!D)
977 continue;
978
979 // FIXME: Handle array fields of structs.
980 if (!D->getType()->isArrayType())
981 continue;
982
983 const Expr *Init = D->getInit();
984 if (!Init)
985 continue;
986 if (!isa<StringLiteral>(Init))
987 continue;
988
989 Loc VarLoc = state->getLValue(D, C.getPredecessor()->getLocationContext());
990 const MemRegion *MR = VarLoc.getAsRegion();
991 if (!MR)
992 continue;
993
994 SVal StrVal = state->getSVal(Init);
995 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenek90af9092010-12-02 07:49:45 +0000996 DefinedOrUnknownSVal strLength
997 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rose2a2e21c2010-08-14 21:02:52 +0000998
Ted Kremenek90af9092010-12-02 07:49:45 +0000999 state = state->set<CStringLength>(MR, strLength);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001000 }
1001
1002 C.addTransition(state);
1003}
1004
Ted Kremenek926c9622011-01-11 02:34:45 +00001005bool CStringChecker::wantsRegionChangeUpdate(const GRState *state) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001006 CStringLength::EntryMap Entries = state->get<CStringLength>();
1007 return !Entries.isEmpty();
1008}
1009
1010const GRState *CStringChecker::EvalRegionChanges(const GRState *state,
1011 const MemRegion * const *Begin,
1012 const MemRegion * const *End,
1013 bool *) {
1014 CStringLength::EntryMap Entries = state->get<CStringLength>();
1015 if (Entries.isEmpty())
1016 return state;
1017
1018 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1019 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1020
1021 // First build sets for the changed regions and their super-regions.
1022 for ( ; Begin != End; ++Begin) {
1023 const MemRegion *MR = *Begin;
1024 Invalidated.insert(MR);
1025
1026 SuperRegions.insert(MR);
1027 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1028 MR = SR->getSuperRegion();
1029 SuperRegions.insert(MR);
1030 }
1031 }
1032
1033 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1034
1035 // Then loop over the entries in the current state.
1036 for (CStringLength::EntryMap::iterator I = Entries.begin(),
1037 E = Entries.end(); I != E; ++I) {
1038 const MemRegion *MR = I.getKey();
1039
1040 // Is this entry for a super-region of a changed region?
1041 if (SuperRegions.count(MR)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001042 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001043 continue;
1044 }
1045
1046 // Is this entry for a sub-region of a changed region?
1047 const MemRegion *Super = MR;
1048 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1049 Super = SR->getSuperRegion();
1050 if (Invalidated.count(Super)) {
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001051 Entries = F.remove(Entries, MR);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001052 break;
1053 }
1054 }
1055 }
1056
1057 return state->set<CStringLength>(Entries);
1058}
1059
1060void CStringChecker::MarkLiveSymbols(const GRState *state, SymbolReaper &SR) {
1061 // Mark all symbols in our string length map as valid.
1062 CStringLength::EntryMap Entries = state->get<CStringLength>();
1063
1064 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1065 I != E; ++I) {
1066 SVal Len = I.getData();
1067 if (SymbolRef Sym = Len.getAsSymbol())
1068 SR.markInUse(Sym);
1069 }
1070}
1071
Ted Kremenekdc891422010-12-01 21:57:22 +00001072void CStringChecker::evalDeadSymbols(CheckerContext &C, SymbolReaper &SR) {
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001073 if (!SR.hasDeadSymbols())
1074 return;
1075
1076 const GRState *state = C.getState();
1077 CStringLength::EntryMap Entries = state->get<CStringLength>();
1078 if (Entries.isEmpty())
1079 return;
1080
1081 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1082 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1083 I != E; ++I) {
1084 SVal Len = I.getData();
1085 if (SymbolRef Sym = Len.getAsSymbol()) {
1086 if (SR.isDead(Sym))
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001087 Entries = F.remove(Entries, I.getKey());
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001088 }
1089 }
1090
1091 state = state->set<CStringLength>(Entries);
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001092 C.generateNode(state);
Jordy Rose2a2e21c2010-08-14 21:02:52 +00001093}