blob: bc8d184af7f3a9e67143ad2f293e7e652f434244 [file] [log] [blame]
Anna Zaksc800f682011-10-11 16:49:54 +00001//= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This defines CStringChecker, which is an assortment of checks on calls
11// to functions in <string.h>.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidisa0decc92011-02-15 21:25:03 +000015#include "ClangSACheckers.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000016#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000017#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000018#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000019#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Jordy Roseccbf7ee2010-07-06 23:11:01 +000021#include "llvm/ADT/StringSwitch.h"
22
23using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000024using namespace ento;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000025
26namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000027class CStringChecker : public Checker< eval::Call,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000028 check::PreStmt<DeclStmt>,
29 check::LiveSymbols,
30 check::DeadSymbols,
31 check::RegionChanges
32 > {
Jordy Rose9e49d9f2011-06-20 02:06:40 +000033 mutable llvm::OwningPtr<BugType> BT_Null, BT_Bounds,
Jordy Rosed5af0e12011-06-15 05:52:56 +000034 BT_Overlap, BT_NotCString,
35 BT_AdditionOverflow;
Jordy Rose9e49d9f2011-06-20 02:06:40 +000036 mutable const char *CurrentFunctionDescription;
37
Jordy Roseccbf7ee2010-07-06 23:11:01 +000038public:
Jordy Roseccbf7ee2010-07-06 23:11:01 +000039 static void *getTag() { static int tag; return &tag; }
40
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000041 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
42 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000043 void checkLiveSymbols(const ProgramState *state, SymbolReaper &SR) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000044 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000045 bool wantsRegionChangeUpdate(const ProgramState *state) const;
Jordy Rosea5261542010-08-14 21:02:52 +000046
Ted Kremenek18c66fd2011-08-15 22:09:50 +000047 const ProgramState *
48 checkRegionChanges(const ProgramState *state,
49 const StoreManager::InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +000050 ArrayRef<const MemRegion *> ExplicitRegions,
51 ArrayRef<const MemRegion *> Regions) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000052
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000053 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
54 const CallExpr *) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000055
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000056 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000057 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000058 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
59 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000060 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000061 const ProgramState *state,
62 const Expr *Size,
63 const Expr *Source,
64 const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +000065 bool Restricted = false,
66 bool IsMempcpy = false) const;
Jordy Rosed325ffb2010-07-08 23:57:29 +000067
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000068 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000069
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000070 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
71 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000072 void evalstrLengthCommon(CheckerContext &C,
73 const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000074 bool IsStrnlen = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +000075
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000076 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
77 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
78 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000079 void evalStrcpyCommon(CheckerContext &C,
80 const CallExpr *CE,
81 bool returnEnd,
82 bool isBounded,
83 bool isAppending) const;
Lenny Maiorani067bbd02011-04-09 15:12:58 +000084
85 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
86 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Jordy Rosee64f3112010-08-16 07:51:42 +000087
Lenny Maiorani318dd922011-04-12 17:08:43 +000088 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani357f6ee2011-04-25 22:21:00 +000089 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranibd1d16a2011-04-28 15:09:11 +000090 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani454fd2d2011-05-02 19:05:49 +000091 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000092 void evalStrcmpCommon(CheckerContext &C,
93 const CallExpr *CE,
94 bool isBounded = false,
95 bool ignoreCase = false) const;
Lenny Maiorani318dd922011-04-12 17:08:43 +000096
Jordy Roseccbf7ee2010-07-06 23:11:01 +000097 // Utility methods
Ted Kremenek18c66fd2011-08-15 22:09:50 +000098 std::pair<const ProgramState*, const ProgramState*>
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000099 static assumeZero(CheckerContext &C,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000100 const ProgramState *state, SVal V, QualType Ty);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000101
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000102 static const ProgramState *setCStringLength(const ProgramState *state,
103 const MemRegion *MR,
104 SVal strLength);
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000105 static SVal getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000106 const ProgramState *&state,
107 const Expr *Ex,
108 const MemRegion *MR,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000109 bool hypothetical);
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000110 SVal getCStringLength(CheckerContext &C,
111 const ProgramState *&state,
112 const Expr *Ex,
113 SVal Buf,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000114 bool hypothetical = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000115
Lenny Maiorani318dd922011-04-12 17:08:43 +0000116 const StringLiteral *getCStringLiteral(CheckerContext &C,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000117 const ProgramState *&state,
Lenny Maiorani318dd922011-04-12 17:08:43 +0000118 const Expr *expr,
119 SVal val) const;
120
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000121 static const ProgramState *InvalidateBuffer(CheckerContext &C,
122 const ProgramState *state,
123 const Expr *Ex, SVal V);
Jordy Rosee64f3112010-08-16 07:51:42 +0000124
Ted Kremenek9c378f72011-08-12 23:37:29 +0000125 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000126 const MemRegion *MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000127
128 // Re-usable checks
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000129 const ProgramState *checkNonNull(CheckerContext &C,
130 const ProgramState *state,
131 const Expr *S,
132 SVal l) const;
133 const ProgramState *CheckLocation(CheckerContext &C,
134 const ProgramState *state,
135 const Expr *S,
136 SVal l,
137 const char *message = NULL) const;
138 const ProgramState *CheckBufferAccess(CheckerContext &C,
139 const ProgramState *state,
140 const Expr *Size,
141 const Expr *FirstBuf,
142 const Expr *SecondBuf,
143 const char *firstMessage = NULL,
144 const char *secondMessage = NULL,
145 bool WarnAboutSize = false) const;
146
147 const ProgramState *CheckBufferAccess(CheckerContext &C,
148 const ProgramState *state,
149 const Expr *Size,
150 const Expr *Buf,
151 const char *message = NULL,
152 bool WarnAboutSize = false) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000153 // This is a convenience override.
Jordy Rose5e5f1502011-06-20 03:49:16 +0000154 return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
155 WarnAboutSize);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000156 }
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000157 const ProgramState *CheckOverlap(CheckerContext &C,
158 const ProgramState *state,
159 const Expr *Size,
160 const Expr *First,
161 const Expr *Second) const;
162 void emitOverlapBug(CheckerContext &C,
163 const ProgramState *state,
164 const Stmt *First,
165 const Stmt *Second) const;
166
167 const ProgramState *checkAdditionOverflow(CheckerContext &C,
168 const ProgramState *state,
169 NonLoc left,
170 NonLoc right) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000171};
Jordy Rosea5261542010-08-14 21:02:52 +0000172
173class CStringLength {
174public:
175 typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
176};
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000177} //end anonymous namespace
178
Jordy Rosea5261542010-08-14 21:02:52 +0000179namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000180namespace ento {
Jordy Rosea5261542010-08-14 21:02:52 +0000181 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000182 struct ProgramStateTrait<CStringLength>
183 : public ProgramStatePartialTrait<CStringLength::EntryMap> {
Jordy Rosea5261542010-08-14 21:02:52 +0000184 static void *GDMIndex() { return CStringChecker::getTag(); }
185 };
186}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000187}
Jordy Rosea5261542010-08-14 21:02:52 +0000188
Jordy Rosed325ffb2010-07-08 23:57:29 +0000189//===----------------------------------------------------------------------===//
190// Individual checks and utility methods.
191//===----------------------------------------------------------------------===//
192
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000193std::pair<const ProgramState*, const ProgramState*>
194CStringChecker::assumeZero(CheckerContext &C, const ProgramState *state, SVal V,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000195 QualType Ty) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000196 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
197 if (!val)
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000198 return std::pair<const ProgramState*, const ProgramState *>(state, state);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000199
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000200 SValBuilder &svalBuilder = C.getSValBuilder();
201 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
202 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000203}
Jordy Rosea6b808c2010-07-07 07:48:06 +0000204
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000205const ProgramState *CStringChecker::checkNonNull(CheckerContext &C,
206 const ProgramState *state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000207 const Expr *S, SVal l) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000208 // If a previous check has failed, propagate the failure.
209 if (!state)
210 return NULL;
211
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000212 const ProgramState *stateNull, *stateNonNull;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000213 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed325ffb2010-07-08 23:57:29 +0000214
215 if (stateNull && !stateNonNull) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000216 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000217 if (!N)
218 return NULL;
219
Jordy Rosed325ffb2010-07-08 23:57:29 +0000220 if (!BT_Null)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000221 BT_Null.reset(new BuiltinBug("API",
222 "Null pointer argument in call to byte string function"));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000223
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000224 llvm::SmallString<80> buf;
225 llvm::raw_svector_ostream os(buf);
226 assert(CurrentFunctionDescription);
227 os << "Null pointer argument in call to " << CurrentFunctionDescription;
228
Jordy Rosea6b808c2010-07-07 07:48:06 +0000229 // Generate a report for this bug.
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000230 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Anna Zakse172e8b2011-08-17 23:00:25 +0000231 BugReport *report = new BugReport(*BT, os.str(), N);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000232
233 report->addRange(S->getSourceRange());
Anna Zaks50bbc162011-08-19 22:33:38 +0000234 report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, S));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000235 C.EmitReport(report);
236 return NULL;
237 }
238
239 // From here on, assume that the value is non-null.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000240 assert(stateNonNull);
241 return stateNonNull;
Jordy Rosea6b808c2010-07-07 07:48:06 +0000242}
243
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000244// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000245const ProgramState *CStringChecker::CheckLocation(CheckerContext &C,
246 const ProgramState *state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000247 const Expr *S, SVal l,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000248 const char *warningMsg) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000249 // If a previous check has failed, propagate the failure.
250 if (!state)
251 return NULL;
252
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000253 // Check for out of bound array element access.
254 const MemRegion *R = l.getAsRegion();
255 if (!R)
256 return state;
257
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000258 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
259 if (!ER)
260 return state;
261
Zhongxing Xu018220c2010-08-11 06:10:55 +0000262 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000263 "CheckLocation should only be called with char* ElementRegions");
264
265 // Get the size of the array.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000266 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
267 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000268 SVal Extent =
269 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000270 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
271
272 // Get the index of the accessed element.
Gabor Greif89b06582010-09-09 10:51:37 +0000273 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000274
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000275 const ProgramState *StInBound = state->assumeInBound(Idx, Size, true);
276 const ProgramState *StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000277 if (StOutBound && !StInBound) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000278 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000279 if (!N)
280 return NULL;
281
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000282 if (!BT_Bounds) {
283 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
284 "Byte string function accesses out-of-bound array element"));
285 }
286 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
287
288 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000289 BugReport *report;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000290 if (warningMsg) {
Anna Zakse172e8b2011-08-17 23:00:25 +0000291 report = new BugReport(*BT, warningMsg, N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000292 } else {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000293 assert(CurrentFunctionDescription);
294 assert(CurrentFunctionDescription[0] != '\0');
295
296 llvm::SmallString<80> buf;
297 llvm::raw_svector_ostream os(buf);
298 os << (char)toupper(CurrentFunctionDescription[0])
299 << &CurrentFunctionDescription[1]
300 << " accesses out-of-bound array element";
Anna Zakse172e8b2011-08-17 23:00:25 +0000301 report = new BugReport(*BT, os.str(), N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000302 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000303
304 // FIXME: It would be nice to eventually make this diagnostic more clear,
305 // e.g., by referencing the original declaration or by saying *why* this
306 // reference is outside the range.
307
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000308 report->addRange(S->getSourceRange());
309 C.EmitReport(report);
310 return NULL;
311 }
312
313 // Array bound check succeeded. From this point forward the array bound
314 // should always succeed.
315 return StInBound;
316}
317
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000318const ProgramState *CStringChecker::CheckBufferAccess(CheckerContext &C,
319 const ProgramState *state,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000320 const Expr *Size,
321 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000322 const Expr *SecondBuf,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000323 const char *firstMessage,
Jordy Rose5e5f1502011-06-20 03:49:16 +0000324 const char *secondMessage,
325 bool WarnAboutSize) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000326 // If a previous check has failed, propagate the failure.
327 if (!state)
328 return NULL;
329
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000330 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000331 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000332 const LocationContext *LCtx = C.getLocationContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000333
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000334 QualType sizeTy = Size->getType();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000335 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
336
Jordy Rosea6b808c2010-07-07 07:48:06 +0000337 // Check that the first buffer is non-null.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000338 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000339 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000340 if (!state)
341 return NULL;
342
Jordy Rosed325ffb2010-07-08 23:57:29 +0000343 // Get the access length and make sure it is known.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000344 // FIXME: This assumes the caller has already checked that the access length
345 // is positive. And that it's unsigned.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000346 SVal LengthVal = state->getSVal(Size, LCtx);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000347 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
348 if (!Length)
349 return state;
350
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000351 // Compute the offset of the last element to be accessed: size-1.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000352 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
353 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
354 *Length, One, sizeTy));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000355
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000356 // Check that the first buffer is sufficiently long.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000357 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000358 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000359 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
360
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000361 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
362 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000363 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000364
Jordy Roseb6a40262010-08-05 23:11:30 +0000365 // If the buffer isn't large enough, abort.
366 if (!state)
367 return NULL;
368 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000369
370 // If there's a second buffer, check it as well.
371 if (SecondBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000372 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000373 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000374 if (!state)
375 return NULL;
376
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000377 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000378 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000379 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
380
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000381 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
382 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000383 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseb6a40262010-08-05 23:11:30 +0000384 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000385 }
386
387 // Large enough or not, return this state!
388 return state;
389}
390
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000391const ProgramState *CStringChecker::CheckOverlap(CheckerContext &C,
392 const ProgramState *state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000393 const Expr *Size,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000394 const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000395 const Expr *Second) const {
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000396 // Do a simple check for overlap: if the two arguments are from the same
397 // buffer, see if the end of the first is greater than the start of the second
398 // or vice versa.
399
Jordy Rosed325ffb2010-07-08 23:57:29 +0000400 // If a previous check has failed, propagate the failure.
401 if (!state)
402 return NULL;
403
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000404 const ProgramState *stateTrue, *stateFalse;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000405
406 // Get the buffer values and make sure they're known locations.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000407 const LocationContext *LCtx = C.getLocationContext();
408 SVal firstVal = state->getSVal(First, LCtx);
409 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000410
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000411 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
412 if (!firstLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000413 return state;
414
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000415 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
416 if (!secondLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000417 return state;
418
419 // Are the two values the same?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000420 SValBuilder &svalBuilder = C.getSValBuilder();
421 llvm::tie(stateTrue, stateFalse) =
422 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000423
424 if (stateTrue && !stateFalse) {
425 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000426 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000427 return NULL;
428 }
429
Ted Kremenek28f47b92010-12-01 22:16:56 +0000430 // assume the two expressions are not equal.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000431 assert(stateFalse);
432 state = stateFalse;
433
434 // Which value comes first?
Jordy Roseee2fde12011-06-16 05:56:50 +0000435 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000436 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
437 *firstLoc, *secondLoc, cmpTy);
438 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
439 if (!reverseTest)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000440 return state;
441
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000442 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000443 if (stateTrue) {
444 if (stateFalse) {
445 // If we don't know which one comes first, we can't perform this test.
446 return state;
447 } else {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000448 // Switch the values so that firstVal is before secondVal.
449 Loc *tmpLoc = firstLoc;
450 firstLoc = secondLoc;
451 secondLoc = tmpLoc;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000452
453 // Switch the Exprs as well, so that they still correspond.
454 const Expr *tmpExpr = First;
455 First = Second;
456 Second = tmpExpr;
457 }
458 }
459
460 // Get the length, and make sure it too is known.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000461 SVal LengthVal = state->getSVal(Size, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000462 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
463 if (!Length)
464 return state;
465
466 // Convert the first buffer's start address to char*.
467 // Bail out if the cast fails.
Jordy Roseee2fde12011-06-16 05:56:50 +0000468 ASTContext &Ctx = svalBuilder.getContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000469 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose1e022412011-06-16 05:51:02 +0000470 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
471 First->getType());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000472 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
473 if (!FirstStartLoc)
474 return state;
475
476 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000477 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000478 *FirstStartLoc, *Length, CharPtrTy);
479 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
480 if (!FirstEndLoc)
481 return state;
482
483 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000484 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
485 *FirstEndLoc, *secondLoc, cmpTy);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000486 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
487 if (!OverlapTest)
488 return state;
489
Ted Kremenek28f47b92010-12-01 22:16:56 +0000490 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000491
492 if (stateTrue && !stateFalse) {
493 // Overlap!
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000494 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000495 return NULL;
496 }
497
Ted Kremenek28f47b92010-12-01 22:16:56 +0000498 // assume the two expressions don't overlap.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000499 assert(stateFalse);
500 return stateFalse;
501}
502
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000503void CStringChecker::emitOverlapBug(CheckerContext &C, const ProgramState *state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000504 const Stmt *First, const Stmt *Second) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000505 ExplodedNode *N = C.generateSink(state);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000506 if (!N)
507 return;
508
509 if (!BT_Overlap)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000510 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000511
512 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000513 BugReport *report =
514 new BugReport(*BT_Overlap,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000515 "Arguments must not be overlapping buffers", N);
516 report->addRange(First->getSourceRange());
517 report->addRange(Second->getSourceRange());
518
519 C.EmitReport(report);
520}
521
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000522const ProgramState *CStringChecker::checkAdditionOverflow(CheckerContext &C,
523 const ProgramState *state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000524 NonLoc left,
525 NonLoc right) const {
526 // If a previous check has failed, propagate the failure.
527 if (!state)
528 return NULL;
529
530 SValBuilder &svalBuilder = C.getSValBuilder();
531 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
532
533 QualType sizeTy = svalBuilder.getContext().getSizeType();
534 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
535 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
536
Anna Zakse3d250e2011-12-11 18:43:40 +0000537 SVal maxMinusRight;
538 if (isa<nonloc::ConcreteInt>(right)) {
539 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
540 sizeTy);
541 } else {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000542 // Try switching the operands. (The order of these two assignments is
543 // important!)
544 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
545 sizeTy);
546 left = right;
547 }
548
549 if (NonLoc *maxMinusRightNL = dyn_cast<NonLoc>(&maxMinusRight)) {
550 QualType cmpTy = svalBuilder.getConditionType();
551 // If left > max - right, we have an overflow.
552 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
553 *maxMinusRightNL, cmpTy);
554
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000555 const ProgramState *stateOverflow, *stateOkay;
Jordy Rosed5af0e12011-06-15 05:52:56 +0000556 llvm::tie(stateOverflow, stateOkay) =
557 state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
558
559 if (stateOverflow && !stateOkay) {
560 // We have an overflow. Emit a bug report.
561 ExplodedNode *N = C.generateSink(stateOverflow);
562 if (!N)
563 return NULL;
564
565 if (!BT_AdditionOverflow)
566 BT_AdditionOverflow.reset(new BuiltinBug("API",
567 "Sum of expressions causes overflow"));
568
Jordy Rosed5af0e12011-06-15 05:52:56 +0000569 // This isn't a great error message, but this should never occur in real
570 // code anyway -- you'd have to create a buffer longer than a size_t can
571 // represent, which is sort of a contradiction.
Jordy Rose8cc24912011-06-20 03:51:53 +0000572 const char *warning =
573 "This expression will create a string whose length is too big to "
574 "be represented as a size_t";
Jordy Rosed5af0e12011-06-15 05:52:56 +0000575
576 // Generate a report for this bug.
Jordy Rose8cc24912011-06-20 03:51:53 +0000577 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000578 C.EmitReport(report);
579
580 return NULL;
581 }
582
583 // From now on, assume an overflow didn't occur.
584 assert(stateOkay);
585 state = stateOkay;
586 }
587
588 return state;
589}
590
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000591const ProgramState *CStringChecker::setCStringLength(const ProgramState *state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000592 const MemRegion *MR,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000593 SVal strLength) {
594 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rosee64f3112010-08-16 07:51:42 +0000595
596 MR = MR->StripCasts();
597
598 switch (MR->getKind()) {
599 case MemRegion::StringRegionKind:
600 // FIXME: This can happen if we strcpy() into a string region. This is
601 // undefined [C99 6.4.5p6], but we should still warn about it.
602 return state;
603
604 case MemRegion::SymbolicRegionKind:
605 case MemRegion::AllocaRegionKind:
606 case MemRegion::VarRegionKind:
607 case MemRegion::FieldRegionKind:
608 case MemRegion::ObjCIvarRegionKind:
Jordy Rose210c05b2011-06-15 05:14:03 +0000609 // These are the types we can currently track string lengths for.
610 break;
Jordy Rosee64f3112010-08-16 07:51:42 +0000611
612 case MemRegion::ElementRegionKind:
613 // FIXME: Handle element regions by upper-bounding the parent region's
614 // string length.
615 return state;
616
617 default:
618 // Other regions (mostly non-data) can't have a reliable C string length.
619 // For now, just ignore the change.
620 // FIXME: These are rare but not impossible. We should output some kind of
621 // warning for things like strcpy((char[]){'a', 0}, "b");
622 return state;
623 }
Jordy Rose210c05b2011-06-15 05:14:03 +0000624
625 if (strLength.isUnknown())
626 return state->remove<CStringLength>(MR);
627
628 return state->set<CStringLength>(MR, strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +0000629}
630
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000631SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000632 const ProgramState *&state,
Jordy Rosea5261542010-08-14 21:02:52 +0000633 const Expr *Ex,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000634 const MemRegion *MR,
635 bool hypothetical) {
636 if (!hypothetical) {
637 // If there's a recorded length, go ahead and return it.
638 const SVal *Recorded = state->get<CStringLength>(MR);
639 if (Recorded)
640 return *Recorded;
641 }
Jordy Rosea5261542010-08-14 21:02:52 +0000642
643 // Otherwise, get a new symbol and update the state.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +0000644 unsigned Count = C.getCurrentBlockCount();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000645 SValBuilder &svalBuilder = C.getSValBuilder();
646 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000647 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
648 MR, Ex, sizeTy, Count);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000649
650 if (!hypothetical)
651 state = state->set<CStringLength>(MR, strLength);
652
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000653 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000654}
655
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000656SVal CStringChecker::getCStringLength(CheckerContext &C, const ProgramState *&state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000657 const Expr *Ex, SVal Buf,
658 bool hypothetical) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000659 const MemRegion *MR = Buf.getAsRegion();
660 if (!MR) {
661 // If we can't get a region, see if it's something we /know/ isn't a
662 // C string. In the context of locations, the only time we can issue such
663 // a warning is for labels.
664 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000665 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000666 if (!BT_NotCString)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000667 BT_NotCString.reset(new BuiltinBug("API",
668 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000669
670 llvm::SmallString<120> buf;
671 llvm::raw_svector_ostream os(buf);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000672 assert(CurrentFunctionDescription);
673 os << "Argument to " << CurrentFunctionDescription
674 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000675 << "', which is not a null-terminated string";
676
677 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000678 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000679 os.str(), N);
680
681 report->addRange(Ex->getSourceRange());
682 C.EmitReport(report);
683 }
684
685 return UndefinedVal();
686 }
687
Jordy Rosea5261542010-08-14 21:02:52 +0000688 // If it's not a region and not a label, give up.
689 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000690 }
691
Jordy Rosea5261542010-08-14 21:02:52 +0000692 // If we have a region, strip casts from it and see if we can figure out
693 // its length. For anything we can't figure out, just return UnknownVal.
694 MR = MR->StripCasts();
695
696 switch (MR->getKind()) {
697 case MemRegion::StringRegionKind: {
698 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
699 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000700 SValBuilder &svalBuilder = C.getSValBuilder();
701 QualType sizeTy = svalBuilder.getContext().getSizeType();
702 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
703 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000704 }
705 case MemRegion::SymbolicRegionKind:
706 case MemRegion::AllocaRegionKind:
707 case MemRegion::VarRegionKind:
708 case MemRegion::FieldRegionKind:
709 case MemRegion::ObjCIvarRegionKind:
Jordy Rosed5af0e12011-06-15 05:52:56 +0000710 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rosea5261542010-08-14 21:02:52 +0000711 case MemRegion::CompoundLiteralRegionKind:
712 // FIXME: Can we track this? Is it necessary?
713 return UnknownVal();
714 case MemRegion::ElementRegionKind:
715 // FIXME: How can we handle this? It's not good enough to subtract the
716 // offset from the base string length; consider "123\x00567" and &a[5].
717 return UnknownVal();
718 default:
719 // Other regions (mostly non-data) can't have a reliable C string length.
720 // In this case, an error is emitted and UndefinedVal is returned.
721 // The caller should always be prepared to handle this case.
Anna Zaks0bd6b112011-10-26 21:06:34 +0000722 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000723 if (!BT_NotCString)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000724 BT_NotCString.reset(new BuiltinBug("API",
725 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000726
727 llvm::SmallString<120> buf;
728 llvm::raw_svector_ostream os(buf);
729
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000730 assert(CurrentFunctionDescription);
731 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rosea5261542010-08-14 21:02:52 +0000732
733 if (SummarizeRegion(os, C.getASTContext(), MR))
734 os << ", which is not a null-terminated string";
735 else
736 os << "not a null-terminated string";
737
738 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000739 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rosea5261542010-08-14 21:02:52 +0000740 os.str(), N);
741
742 report->addRange(Ex->getSourceRange());
743 C.EmitReport(report);
744 }
745
746 return UndefinedVal();
747 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000748}
749
Lenny Maiorani318dd922011-04-12 17:08:43 +0000750const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000751 const ProgramState *&state, const Expr *expr, SVal val) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +0000752
753 // Get the memory region pointed to by the val.
754 const MemRegion *bufRegion = val.getAsRegion();
755 if (!bufRegion)
756 return NULL;
757
758 // Strip casts off the memory region.
759 bufRegion = bufRegion->StripCasts();
760
761 // Cast the memory region to a string region.
762 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
763 if (!strRegion)
764 return NULL;
765
766 // Return the actual string in the string region.
767 return strRegion->getStringLiteral();
768}
769
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000770const ProgramState *CStringChecker::InvalidateBuffer(CheckerContext &C,
771 const ProgramState *state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000772 const Expr *E, SVal V) {
773 Loc *L = dyn_cast<Loc>(&V);
774 if (!L)
775 return state;
776
777 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
778 // some assumptions about the value that CFRefCount can't. Even so, it should
779 // probably be refactored.
780 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
781 const MemRegion *R = MR->getRegion()->StripCasts();
782
783 // Are we dealing with an ElementRegion? If so, we should be invalidating
784 // the super-region.
785 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
786 R = ER->getSuperRegion();
787 // FIXME: What about layers of ElementRegions?
788 }
789
790 // Invalidate this region.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +0000791 unsigned Count = C.getCurrentBlockCount();
Jordy Rose537716a2011-08-27 22:51:26 +0000792 return state->invalidateRegions(R, E, Count);
Jordy Rosee64f3112010-08-16 07:51:42 +0000793 }
794
795 // If we have a non-region value by chance, just remove the binding.
796 // FIXME: is this necessary or correct? This handles the non-Region
797 // cases. Is it ever valid to store to these?
798 return state->unbindLoc(*L);
799}
800
Ted Kremenek9c378f72011-08-12 23:37:29 +0000801bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000802 const MemRegion *MR) {
Ted Kremenek96979342011-08-12 20:02:48 +0000803 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000804
Jordy Rose096aef92011-08-12 21:41:07 +0000805 switch (MR->getKind()) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000806 case MemRegion::FunctionTextRegionKind: {
Jordy Rose096aef92011-08-12 21:41:07 +0000807 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000808 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000809 os << "the address of the function '" << *FD << '\'';
Jordy Rose19c5dd12010-07-27 01:37:31 +0000810 else
811 os << "the address of a function";
812 return true;
813 }
814 case MemRegion::BlockTextRegionKind:
815 os << "block text";
816 return true;
817 case MemRegion::BlockDataRegionKind:
818 os << "a block";
819 return true;
820 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000821 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000822 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000823 return true;
824 case MemRegion::VarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000825 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000826 return true;
827 case MemRegion::FieldRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000828 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000829 return true;
830 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000831 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000832 return true;
833 default:
834 return false;
835 }
836}
837
Jordy Rosed325ffb2010-07-08 23:57:29 +0000838//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000839// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000840//===----------------------------------------------------------------------===//
841
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000842void CStringChecker::evalCopyCommon(CheckerContext &C,
843 const CallExpr *CE,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000844 const ProgramState *state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000845 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000846 const Expr *Source, bool Restricted,
847 bool IsMempcpy) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000848 CurrentFunctionDescription = "memory copy function";
849
Jordy Rosed325ffb2010-07-08 23:57:29 +0000850 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000851 const LocationContext *LCtx = C.getLocationContext();
852 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000853 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000854
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000855 const ProgramState *stateZeroSize, *stateNonZeroSize;
Jordy Rose1e022412011-06-16 05:51:02 +0000856 llvm::tie(stateZeroSize, stateNonZeroSize) =
857 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000858
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000859 // Get the value of the Dest.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000860 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000861
862 // If the size is zero, there won't be any actual memory access, so
863 // just bind the return value to the destination buffer and return.
864 if (stateZeroSize) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000865 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000866 C.addTransition(stateZeroSize);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000867 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000868
869 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000870 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000871 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000872
873 // Ensure the destination is not null. If it is NULL there will be a
874 // NULL pointer dereference.
875 state = checkNonNull(C, state, Dest, destVal);
876 if (!state)
877 return;
878
879 // Get the value of the Src.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000880 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000881
882 // Ensure the source is not null. If it is NULL there will be a
883 // NULL pointer dereference.
884 state = checkNonNull(C, state, Source, srcVal);
885 if (!state)
886 return;
887
Jordy Rose7182b962011-06-04 01:50:25 +0000888 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000889 const char * const writeWarning =
890 "Memory copy function overflows destination buffer";
Jordy Rosee64f3112010-08-16 07:51:42 +0000891 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000892 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000893 if (Restricted)
894 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000895
Jordy Rose7182b962011-06-04 01:50:25 +0000896 if (!state)
897 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000898
Jordy Rose7182b962011-06-04 01:50:25 +0000899 // If this is mempcpy, get the byte after the last byte copied and
900 // bind the expr.
901 if (IsMempcpy) {
902 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
903 assert(destRegVal && "Destination should be a known MemRegionVal here");
904
905 // Get the length to copy.
906 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
907
908 if (lenValNonLoc) {
909 // Get the byte after the last byte copied.
910 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
911 *destRegVal,
912 *lenValNonLoc,
913 Dest->getType());
914
915 // The byte after the last byte copied is the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000916 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000917 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000918 // If we don't know how much we copied, we can at least
919 // conjure a return value for later.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +0000920 unsigned Count = C.getCurrentBlockCount();
Jordy Rose7182b962011-06-04 01:50:25 +0000921 SVal result =
922 C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000923 state = state->BindExpr(CE, LCtx, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000924 }
925
Jordy Rose7182b962011-06-04 01:50:25 +0000926 } else {
927 // All other copies return the destination buffer.
928 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000929 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000930 }
Jordy Rose7182b962011-06-04 01:50:25 +0000931
932 // Invalidate the destination.
933 // FIXME: Even if we can't perfectly model the copy, we should see if we
934 // can use LazyCompoundVals to copy the source values into the destination.
935 // This would probably remove any existing bindings past the end of the
936 // copied region, but that's still an improvement over blank invalidation.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000937 state = InvalidateBuffer(C, state, Dest,
938 state->getSVal(Dest, C.getLocationContext()));
Anna Zaks0bd6b112011-10-26 21:06:34 +0000939 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000940 }
941}
942
943
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000944void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000945 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000946 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000947 const Expr *Dest = CE->getArg(0);
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000948 const ProgramState *state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000949
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000950 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
951}
952
953void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
954 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
955 // The return value is a pointer to the byte following the last written byte.
956 const Expr *Dest = CE->getArg(0);
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000957 const ProgramState *state = C.getState();
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000958
959 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000960}
961
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000962void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000963 // void *memmove(void *dst, const void *src, size_t n);
964 // The return value is the address of the destination buffer.
965 const Expr *Dest = CE->getArg(0);
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000966 const ProgramState *state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000967
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000968 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000969}
970
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000971void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000972 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000973 evalCopyCommon(C, CE, C.getState(),
974 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000975}
976
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000977void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000978 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000979 CurrentFunctionDescription = "memory comparison function";
980
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000981 const Expr *Left = CE->getArg(0);
982 const Expr *Right = CE->getArg(1);
983 const Expr *Size = CE->getArg(2);
984
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000985 const ProgramState *state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000986 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000987
Jordy Rosed325ffb2010-07-08 23:57:29 +0000988 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000989 const LocationContext *LCtx = C.getLocationContext();
990 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000991 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000992
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000993 const ProgramState *stateZeroSize, *stateNonZeroSize;
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000994 llvm::tie(stateZeroSize, stateNonZeroSize) =
995 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +0000996
Jordy Rosed325ffb2010-07-08 23:57:29 +0000997 // If the size can be zero, the result will be 0 in that case, and we don't
998 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000999 if (stateZeroSize) {
1000 state = stateZeroSize;
Ted Kremenek5eca4822012-01-06 22:09:28 +00001001 state = state->BindExpr(CE, LCtx,
1002 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001003 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001004 }
1005
Jordy Rosed325ffb2010-07-08 23:57:29 +00001006 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001007 if (stateNonZeroSize) {
1008 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +00001009 // If we know the two buffers are the same, we know the result is 0.
1010 // First, get the two buffers' addresses. Another checker will have already
1011 // made sure they're not undefined.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001012 DefinedOrUnknownSVal LV =
1013 cast<DefinedOrUnknownSVal>(state->getSVal(Left, LCtx));
1014 DefinedOrUnknownSVal RV =
1015 cast<DefinedOrUnknownSVal>(state->getSVal(Right, LCtx));
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001016
Jordy Rosed325ffb2010-07-08 23:57:29 +00001017 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001018 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001019 const ProgramState *StSameBuf, *StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +00001020 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001021
Jordy Rose1e022412011-06-16 05:51:02 +00001022 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +00001023 // and we only need to check one size.
1024 if (StSameBuf) {
1025 state = StSameBuf;
1026 state = CheckBufferAccess(C, state, Size, Left);
1027 if (state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001028 state = StSameBuf->BindExpr(CE, LCtx,
1029 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001030 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001031 }
1032 }
1033
1034 // If the two arguments might be different buffers, we have to check the
1035 // size of both of them.
1036 if (StNotSameBuf) {
1037 state = StNotSameBuf;
1038 state = CheckBufferAccess(C, state, Size, Left, Right);
1039 if (state) {
1040 // The return value is the comparison result, which we don't know.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001041 unsigned Count = C.getCurrentBlockCount();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001042 SVal CmpV = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001043 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001044 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001045 }
1046 }
1047 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001048}
1049
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001050void CStringChecker::evalstrLength(CheckerContext &C,
1051 const CallExpr *CE) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +00001052 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001053 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1054}
1055
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001056void CStringChecker::evalstrnLength(CheckerContext &C,
1057 const CallExpr *CE) const {
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001058 // size_t strnlen(const char *s, size_t maxlen);
1059 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1060}
1061
1062void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001063 bool IsStrnlen) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001064 CurrentFunctionDescription = "string length function";
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001065 const ProgramState *state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001066 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose793bff32011-06-14 01:15:31 +00001067
1068 if (IsStrnlen) {
1069 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001070 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rose793bff32011-06-14 01:15:31 +00001071
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001072 const ProgramState *stateZeroSize, *stateNonZeroSize;
Jordy Rose793bff32011-06-14 01:15:31 +00001073 llvm::tie(stateZeroSize, stateNonZeroSize) =
1074 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1075
1076 // If the size can be zero, the result will be 0 in that case, and we don't
1077 // have to check the string itself.
1078 if (stateZeroSize) {
1079 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001080 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001081 C.addTransition(stateZeroSize);
Jordy Rose793bff32011-06-14 01:15:31 +00001082 }
1083
1084 // If the size is GUARANTEED to be zero, we're done!
1085 if (!stateNonZeroSize)
1086 return;
1087
1088 // Otherwise, record the assumption that the size is nonzero.
1089 state = stateNonZeroSize;
1090 }
1091
1092 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001093 const Expr *Arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001094 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001095
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001096 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001097
Jordy Rosebd32bee2011-06-14 01:26:48 +00001098 if (!state)
1099 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001100
Jordy Rosebd32bee2011-06-14 01:26:48 +00001101 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001102
Jordy Rosebd32bee2011-06-14 01:26:48 +00001103 // If the argument isn't a valid C string, there's no valid state to
1104 // transition to.
1105 if (strLength.isUndef())
1106 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001107
Jordy Rosebd32bee2011-06-14 01:26:48 +00001108 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001109
Jordy Rosebd32bee2011-06-14 01:26:48 +00001110 // If the check is for strnlen() then bind the return value to no more than
1111 // the maxlen value.
1112 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001113 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001114
Jordy Rosebd32bee2011-06-14 01:26:48 +00001115 // It's a little unfortunate to be getting this again,
1116 // but it's not that expensive...
1117 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001118 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001119
Jordy Rosebd32bee2011-06-14 01:26:48 +00001120 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1121 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001122
Jordy Rosebd32bee2011-06-14 01:26:48 +00001123 if (strLengthNL && maxlenValNL) {
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001124 const ProgramState *stateStringTooLong, *stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001125
Jordy Rosebd32bee2011-06-14 01:26:48 +00001126 // Check if the strLength is greater than the maxlen.
1127 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
1128 state->assume(cast<DefinedOrUnknownSVal>
1129 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1130 *strLengthNL,
1131 *maxlenValNL,
1132 cmpTy)));
Jordy Rose793bff32011-06-14 01:15:31 +00001133
Jordy Rosebd32bee2011-06-14 01:26:48 +00001134 if (stateStringTooLong && !stateStringNotTooLong) {
1135 // If the string is longer than maxlen, return maxlen.
1136 result = *maxlenValNL;
1137 } else if (stateStringNotTooLong && !stateStringTooLong) {
1138 // If the string is shorter than maxlen, return its length.
1139 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001140 }
1141 }
1142
Jordy Rosebd32bee2011-06-14 01:26:48 +00001143 if (result.isUnknown()) {
1144 // If we don't have enough information for a comparison, there's
1145 // no guarantee the full string length will actually be returned.
1146 // All we know is the return value is the min of the string length
1147 // and the limit. This is better than nothing.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001148 unsigned Count = C.getCurrentBlockCount();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001149 result = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
1150 NonLoc *resultNL = cast<NonLoc>(&result);
1151
1152 if (strLengthNL) {
1153 state = state->assume(cast<DefinedOrUnknownSVal>
1154 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1155 *resultNL,
1156 *strLengthNL,
1157 cmpTy)), true);
1158 }
1159
1160 if (maxlenValNL) {
1161 state = state->assume(cast<DefinedOrUnknownSVal>
1162 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1163 *resultNL,
1164 *maxlenValNL,
1165 cmpTy)), true);
1166 }
1167 }
1168
1169 } else {
1170 // This is a plain strlen(), not strnlen().
1171 result = cast<DefinedOrUnknownSVal>(strLength);
1172
1173 // If we don't know the length of the string, conjure a return
1174 // value, so it can be used in constraints, at least.
1175 if (result.isUnknown()) {
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001176 unsigned Count = C.getCurrentBlockCount();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001177 result = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
1178 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001179 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001180
1181 // Bind the return value.
1182 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek5eca4822012-01-06 22:09:28 +00001183 state = state->BindExpr(CE, LCtx, result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001184 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001185}
1186
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001187void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosee64f3112010-08-16 07:51:42 +00001188 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001189 evalStrcpyCommon(C, CE,
1190 /* returnEnd = */ false,
1191 /* isBounded = */ false,
1192 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001193}
1194
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001195void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosec1525862011-06-04 00:05:23 +00001196 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001197 evalStrcpyCommon(C, CE,
1198 /* returnEnd = */ false,
1199 /* isBounded = */ true,
1200 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001201}
1202
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001203void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosee64f3112010-08-16 07:51:42 +00001204 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001205 evalStrcpyCommon(C, CE,
1206 /* returnEnd = */ true,
1207 /* isBounded = */ false,
1208 /* isAppending = */ false);
1209}
1210
1211void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
1212 //char *strcat(char *restrict s1, const char *restrict s2);
1213 evalStrcpyCommon(C, CE,
1214 /* returnEnd = */ false,
1215 /* isBounded = */ false,
1216 /* isAppending = */ true);
1217}
1218
1219void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
1220 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1221 evalStrcpyCommon(C, CE,
1222 /* returnEnd = */ false,
1223 /* isBounded = */ true,
1224 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001225}
1226
Ted Kremenek9c149532010-12-01 21:57:22 +00001227void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001228 bool returnEnd, bool isBounded,
1229 bool isAppending) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001230 CurrentFunctionDescription = "string copy function";
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001231 const ProgramState *state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001232 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosee64f3112010-08-16 07:51:42 +00001233
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001234 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001235 const Expr *Dst = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001236 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +00001237
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001238 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001239 if (!state)
1240 return;
1241
1242 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001243 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001244 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001245 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001246 if (!state)
1247 return;
1248
1249 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001250 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001251
1252 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001253 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001254 return;
1255
Jordy Rosed5af0e12011-06-15 05:52:56 +00001256 SValBuilder &svalBuilder = C.getSValBuilder();
1257 QualType cmpTy = svalBuilder.getConditionType();
Jordy Rose8912aae2011-06-20 21:55:40 +00001258 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001259
Jordy Rose8912aae2011-06-20 21:55:40 +00001260 // These two values allow checking two kinds of errors:
1261 // - actual overflows caused by a source that doesn't fit in the destination
1262 // - potential overflows caused by a bound that could exceed the destination
Jordy Rosed5af0e12011-06-15 05:52:56 +00001263 SVal amountCopied = UnknownVal();
Jordy Rose8912aae2011-06-20 21:55:40 +00001264 SVal maxLastElementIndex = UnknownVal();
1265 const char *boundWarning = NULL;
Jordy Rosed5af0e12011-06-15 05:52:56 +00001266
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001267 // If the function is strncpy, strncat, etc... it is bounded.
1268 if (isBounded) {
1269 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001270 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001271 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001272
Jordy Rosed5af0e12011-06-15 05:52:56 +00001273 // Protect against misdeclared strncpy().
Jordy Rose8912aae2011-06-20 21:55:40 +00001274 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001275
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001276 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1277 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1278
Jordy Rosed5af0e12011-06-15 05:52:56 +00001279 // If we know both values, we might be able to figure out how much
1280 // we're copying.
1281 if (strLengthNL && lenValNL) {
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001282 const ProgramState *stateSourceTooLong, *stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001283
Jordy Rosed5af0e12011-06-15 05:52:56 +00001284 // Check if the max number to copy is less than the length of the src.
Jordy Rose8912aae2011-06-20 21:55:40 +00001285 // If the bound is equal to the source length, strncpy won't null-
1286 // terminate the result!
Jordy Rosed5af0e12011-06-15 05:52:56 +00001287 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) =
1288 state->assume(cast<DefinedOrUnknownSVal>
Jordy Rose8912aae2011-06-20 21:55:40 +00001289 (svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL,
Jordy Rosed5af0e12011-06-15 05:52:56 +00001290 *lenValNL, cmpTy)));
1291
1292 if (stateSourceTooLong && !stateSourceNotTooLong) {
1293 // Max number to copy is less than the length of the src, so the actual
1294 // strLength copied is the max number arg.
1295 state = stateSourceTooLong;
1296 amountCopied = lenVal;
1297
1298 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1299 // The source buffer entirely fits in the bound.
1300 state = stateSourceNotTooLong;
1301 amountCopied = strLength;
1302 }
1303 }
1304
Jordy Rose5e5f1502011-06-20 03:49:16 +00001305 // We still want to know if the bound is known to be too large.
Jordy Rose8912aae2011-06-20 21:55:40 +00001306 if (lenValNL) {
1307 if (isAppending) {
1308 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1309
1310 // Get the string length of the destination. If the destination is
1311 // memory that can't have a string length, we shouldn't be copying
1312 // into it anyway.
1313 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1314 if (dstStrLength.isUndef())
1315 return;
1316
1317 if (NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength)) {
1318 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1319 *lenValNL,
1320 *dstStrLengthNL,
1321 sizeTy);
1322 boundWarning = "Size argument is greater than the free space in the "
1323 "destination buffer";
1324 }
1325
1326 } else {
1327 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1328 // (Yes, strncpy and strncat differ in how they treat termination.
1329 // strncat ALWAYS terminates, but strncpy doesn't.)
1330 NonLoc one = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
1331 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1332 one, sizeTy);
1333 boundWarning = "Size argument is greater than the length of the "
1334 "destination buffer";
1335 }
1336 }
Jordy Rose5e5f1502011-06-20 03:49:16 +00001337
Jordy Rosed5af0e12011-06-15 05:52:56 +00001338 // If we couldn't pin down the copy length, at least bound it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001339 // FIXME: We should actually run this code path for append as well, but
1340 // right now it creates problems with constraints (since we can end up
1341 // trying to pass constraints from symbol to symbol).
1342 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001343 // Try to get a "hypothetical" string length symbol, which we can later
1344 // set as a real value if that turns out to be the case.
1345 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1346 assert(!amountCopied.isUndef());
1347
1348 if (NonLoc *amountCopiedNL = dyn_cast<NonLoc>(&amountCopied)) {
1349 if (lenValNL) {
1350 // amountCopied <= lenVal
1351 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1352 *amountCopiedNL,
1353 *lenValNL,
1354 cmpTy);
1355 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanBound),
1356 true);
1357 if (!state)
1358 return;
1359 }
1360
1361 if (strLengthNL) {
1362 // amountCopied <= strlen(source)
1363 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1364 *amountCopiedNL,
1365 *strLengthNL,
1366 cmpTy);
1367 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanSrc),
1368 true);
1369 if (!state)
1370 return;
1371 }
1372 }
1373 }
1374
1375 } else {
1376 // The function isn't bounded. The amount copied should match the length
1377 // of the source buffer.
1378 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001379 }
1380
Jordy Rosed5af0e12011-06-15 05:52:56 +00001381 assert(state);
1382
1383 // This represents the number of characters copied into the destination
1384 // buffer. (It may not actually be the strlen if the destination buffer
1385 // is not terminated.)
1386 SVal finalStrLength = UnknownVal();
1387
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001388 // If this is an appending function (strcat, strncat...) then set the
1389 // string length to strlen(src) + strlen(dst) since the buffer will
1390 // ultimately contain both.
1391 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001392 // Get the string length of the destination. If the destination is memory
1393 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001394 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1395 if (dstStrLength.isUndef())
1396 return;
1397
Jordy Rosed5af0e12011-06-15 05:52:56 +00001398 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&amountCopied);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001399 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1400
Jordy Rosed5af0e12011-06-15 05:52:56 +00001401 // If we know both string lengths, we might know the final string length.
1402 if (srcStrLengthNL && dstStrLengthNL) {
1403 // Make sure the two lengths together don't overflow a size_t.
1404 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1405 if (!state)
1406 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001407
Jordy Rosed5af0e12011-06-15 05:52:56 +00001408 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1409 *dstStrLengthNL, sizeTy);
1410 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001411
Jordy Rosed5af0e12011-06-15 05:52:56 +00001412 // If we couldn't get a single value for the final string length,
1413 // we can at least bound it by the individual lengths.
1414 if (finalStrLength.isUnknown()) {
1415 // Try to get a "hypothetical" string length symbol, which we can later
1416 // set as a real value if that turns out to be the case.
1417 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1418 assert(!finalStrLength.isUndef());
1419
1420 if (NonLoc *finalStrLengthNL = dyn_cast<NonLoc>(&finalStrLength)) {
1421 if (srcStrLengthNL) {
1422 // finalStrLength >= srcStrLength
1423 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1424 *finalStrLengthNL,
1425 *srcStrLengthNL,
1426 cmpTy);
1427 state = state->assume(cast<DefinedOrUnknownSVal>(sourceInResult),
1428 true);
1429 if (!state)
1430 return;
1431 }
1432
1433 if (dstStrLengthNL) {
1434 // finalStrLength >= dstStrLength
1435 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1436 *finalStrLengthNL,
1437 *dstStrLengthNL,
1438 cmpTy);
1439 state = state->assume(cast<DefinedOrUnknownSVal>(destInResult),
1440 true);
1441 if (!state)
1442 return;
1443 }
1444 }
1445 }
1446
1447 } else {
1448 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1449 // the final string length will match the input string length.
1450 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001451 }
1452
Jordy Rosed5af0e12011-06-15 05:52:56 +00001453 // The final result of the function will either be a pointer past the last
1454 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001455 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001456
Jordy Rosed5af0e12011-06-15 05:52:56 +00001457 assert(state);
1458
Jordy Rosee64f3112010-08-16 07:51:42 +00001459 // If the destination is a MemRegion, try to check for a buffer overflow and
1460 // record the new string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001461 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001462 QualType ptrTy = Dst->getType();
1463
1464 // If we have an exact value on a bounded copy, use that to check for
1465 // overflows, rather than our estimate about how much is actually copied.
1466 if (boundWarning) {
1467 if (NonLoc *maxLastNL = dyn_cast<NonLoc>(&maxLastElementIndex)) {
1468 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1469 *maxLastNL, ptrTy);
1470 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1471 boundWarning);
1472 if (!state)
1473 return;
1474 }
1475 }
1476
1477 // Then, if the final length is known...
Jordy Rosed5af0e12011-06-15 05:52:56 +00001478 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&finalStrLength)) {
1479 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Rose8912aae2011-06-20 21:55:40 +00001480 *knownStrLength, ptrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +00001481
Jordy Rose8912aae2011-06-20 21:55:40 +00001482 // ...and we haven't checked the bound, we'll check the actual copy.
1483 if (!boundWarning) {
1484 const char * const warningMsg =
1485 "String copy function overflows destination buffer";
1486 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1487 if (!state)
1488 return;
1489 }
Jordy Rosee64f3112010-08-16 07:51:42 +00001490
1491 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001492 if (returnEnd)
1493 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001494 }
1495
1496 // Invalidate the destination. This must happen before we set the C string
1497 // length because invalidation will clear the length.
1498 // FIXME: Even if we can't perfectly model the copy, we should see if we
1499 // can use LazyCompoundVals to copy the source values into the destination.
1500 // This would probably remove any existing bindings past the end of the
1501 // string, but that's still an improvement over blank invalidation.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001502 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001503
Jordy Rose5e5f1502011-06-20 03:49:16 +00001504 // Set the C string length of the destination, if we know it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001505 if (isBounded && !isAppending) {
1506 // strncpy is annoying in that it doesn't guarantee to null-terminate
1507 // the result string. If the original string didn't fit entirely inside
1508 // the bound (including the null-terminator), we don't know how long the
1509 // result is.
1510 if (amountCopied != strLength)
1511 finalStrLength = UnknownVal();
1512 }
1513 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001514 }
1515
Jordy Rosed5af0e12011-06-15 05:52:56 +00001516 assert(state);
1517
Jordy Rosee64f3112010-08-16 07:51:42 +00001518 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1519 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001520 if (returnEnd && Result.isUnknown()) {
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001521 unsigned Count = C.getCurrentBlockCount();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001522 Result = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rosee64f3112010-08-16 07:51:42 +00001523 }
1524
1525 // Set the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001526 state = state->BindExpr(CE, LCtx, Result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001527 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +00001528}
1529
Lenny Maiorani318dd922011-04-12 17:08:43 +00001530void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Jordy Roseadc42d42011-06-16 07:13:34 +00001531 //int strcmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001532 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001533}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001534
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001535void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Jordy Roseadc42d42011-06-16 07:13:34 +00001536 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001537 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1538}
1539
1540void CStringChecker::evalStrcasecmp(CheckerContext &C,
1541 const CallExpr *CE) const {
Jordy Roseadc42d42011-06-16 07:13:34 +00001542 //int strcasecmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001543 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001544}
1545
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001546void CStringChecker::evalStrncasecmp(CheckerContext &C,
1547 const CallExpr *CE) const {
Jordy Roseadc42d42011-06-16 07:13:34 +00001548 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001549 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1550}
1551
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001552void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001553 bool isBounded, bool ignoreCase) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001554 CurrentFunctionDescription = "string comparison function";
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001555 const ProgramState *state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001556 const LocationContext *LCtx = C.getLocationContext();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001557
1558 // Check that the first string is non-null
1559 const Expr *s1 = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001560 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001561 state = checkNonNull(C, state, s1, s1Val);
1562 if (!state)
1563 return;
1564
1565 // Check that the second string is non-null.
1566 const Expr *s2 = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001567 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001568 state = checkNonNull(C, state, s2, s2Val);
1569 if (!state)
1570 return;
1571
1572 // Get the string length of the first string or give up.
1573 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1574 if (s1Length.isUndef())
1575 return;
1576
1577 // Get the string length of the second string or give up.
1578 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1579 if (s2Length.isUndef())
1580 return;
1581
Jordy Roseadc42d42011-06-16 07:13:34 +00001582 // If we know the two buffers are the same, we know the result is 0.
1583 // First, get the two buffers' addresses. Another checker will have already
1584 // made sure they're not undefined.
1585 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(s1Val);
1586 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(s2Val);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001587
Jordy Roseadc42d42011-06-16 07:13:34 +00001588 // See if they are the same.
Lenny Maiorani318dd922011-04-12 17:08:43 +00001589 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseadc42d42011-06-16 07:13:34 +00001590 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001591 const ProgramState *StSameBuf, *StNotSameBuf;
Jordy Roseadc42d42011-06-16 07:13:34 +00001592 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001593
Jordy Roseadc42d42011-06-16 07:13:34 +00001594 // If the two arguments might be the same buffer, we know the result is 0,
1595 // and we only need to check one size.
1596 if (StSameBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001597 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1598 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001599 C.addTransition(StSameBuf);
Jordy Roseadc42d42011-06-16 07:13:34 +00001600
1601 // If the two arguments are GUARANTEED to be the same, we're done!
1602 if (!StNotSameBuf)
1603 return;
1604 }
1605
1606 assert(StNotSameBuf);
1607 state = StNotSameBuf;
1608
1609 // At this point we can go about comparing the two buffers.
1610 // For now, we only do this if they're both known string literals.
1611
1612 // Attempt to extract string literals from both expressions.
1613 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1614 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1615 bool canComputeResult = false;
1616
1617 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001618 StringRef s1StrRef = s1StrLiteral->getString();
1619 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Roseadc42d42011-06-16 07:13:34 +00001620
1621 if (isBounded) {
1622 // Get the max number of characters to compare.
1623 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001624 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Roseadc42d42011-06-16 07:13:34 +00001625
1626 // If the length is known, we can get the right substrings.
1627 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1628 // Create substrings of each to compare the prefix.
1629 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1630 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1631 canComputeResult = true;
1632 }
1633 } else {
1634 // This is a normal, unbounded strcmp.
1635 canComputeResult = true;
1636 }
1637
1638 if (canComputeResult) {
1639 // Real strcmp stops at null characters.
1640 size_t s1Term = s1StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001641 if (s1Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001642 s1StrRef = s1StrRef.substr(0, s1Term);
1643
1644 size_t s2Term = s2StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001645 if (s2Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001646 s2StrRef = s2StrRef.substr(0, s2Term);
1647
1648 // Use StringRef's comparison methods to compute the actual result.
1649 int result;
1650
1651 if (ignoreCase) {
1652 // Compare string 1 to string 2 the same way strcasecmp() does.
1653 result = s1StrRef.compare_lower(s2StrRef);
1654 } else {
1655 // Compare string 1 to string 2 the same way strcmp() does.
1656 result = s1StrRef.compare(s2StrRef);
1657 }
1658
1659 // Build the SVal of the comparison and bind the return value.
1660 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001661 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001662 }
1663 }
1664
1665 if (!canComputeResult) {
1666 // Conjure a symbolic value. It's the best we can do.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001667 unsigned Count = C.getCurrentBlockCount();
Jordy Roseadc42d42011-06-16 07:13:34 +00001668 SVal resultVal = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001669 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001670 }
1671
1672 // Record this as a possible path.
Anna Zaks0bd6b112011-10-26 21:06:34 +00001673 C.addTransition(state);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001674}
1675
Jordy Rosed325ffb2010-07-08 23:57:29 +00001676//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001677// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001678//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001679
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001680bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaksb805c8f2011-12-01 05:57:37 +00001681 StringRef Name = C.getCalleeName(CE);
1682 if (Name.empty())
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001683 return false;
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001684 if (Name.startswith("__builtin_"))
1685 Name = Name.substr(10);
1686
Ted Kremenek9c149532010-12-01 21:57:22 +00001687 FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
1688 .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
Jordy Rosebe460d82011-06-03 23:42:56 +00001689 .Cases("mempcpy", "__mempcpy_chk", &CStringChecker::evalMempcpy)
Ted Kremenek9c149532010-12-01 21:57:22 +00001690 .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
1691 .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
1692 .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
Jordy Rose5e5f1502011-06-20 03:49:16 +00001693 .Cases("strncpy", "__strncpy_chk", &CStringChecker::evalStrncpy)
Ted Kremenek9c149532010-12-01 21:57:22 +00001694 .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001695 .Cases("strcat", "__strcat_chk", &CStringChecker::evalStrcat)
1696 .Cases("strncat", "__strncat_chk", &CStringChecker::evalStrncat)
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001697 .Case("strlen", &CStringChecker::evalstrLength)
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001698 .Case("strnlen", &CStringChecker::evalstrnLength)
Lenny Maiorani318dd922011-04-12 17:08:43 +00001699 .Case("strcmp", &CStringChecker::evalStrcmp)
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001700 .Case("strncmp", &CStringChecker::evalStrncmp)
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001701 .Case("strcasecmp", &CStringChecker::evalStrcasecmp)
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001702 .Case("strncasecmp", &CStringChecker::evalStrncasecmp)
Ted Kremenek9c149532010-12-01 21:57:22 +00001703 .Case("bcopy", &CStringChecker::evalBcopy)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001704 .Default(NULL);
1705
Jordy Rosed325ffb2010-07-08 23:57:29 +00001706 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001707 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001708 return false;
1709
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001710 // Make sure each function sets its own description.
1711 // (But don't bother in a release build.)
1712 assert(!(CurrentFunctionDescription = NULL));
1713
Jordy Rosed325ffb2010-07-08 23:57:29 +00001714 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001715 (this->*evalFunction)(C, CE);
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001716 return true;
1717}
Jordy Rosea5261542010-08-14 21:02:52 +00001718
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001719void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001720 // Record string length for char a[] = "abc";
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001721 const ProgramState *state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001722
1723 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1724 I != E; ++I) {
1725 const VarDecl *D = dyn_cast<VarDecl>(*I);
1726 if (!D)
1727 continue;
1728
1729 // FIXME: Handle array fields of structs.
1730 if (!D->getType()->isArrayType())
1731 continue;
1732
1733 const Expr *Init = D->getInit();
1734 if (!Init)
1735 continue;
1736 if (!isa<StringLiteral>(Init))
1737 continue;
1738
Anna Zaks39ac1872011-10-26 21:06:44 +00001739 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001740 const MemRegion *MR = VarLoc.getAsRegion();
1741 if (!MR)
1742 continue;
1743
Ted Kremenek5eca4822012-01-06 22:09:28 +00001744 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001745 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001746 DefinedOrUnknownSVal strLength
1747 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rosea5261542010-08-14 21:02:52 +00001748
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001749 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001750 }
1751
Anna Zaks0bd6b112011-10-26 21:06:34 +00001752 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001753}
1754
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001755bool CStringChecker::wantsRegionChangeUpdate(const ProgramState *state) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001756 CStringLength::EntryMap Entries = state->get<CStringLength>();
1757 return !Entries.isEmpty();
1758}
1759
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001760const ProgramState *
1761CStringChecker::checkRegionChanges(const ProgramState *state,
Ted Kremenek35bdbf42011-05-02 19:42:42 +00001762 const StoreManager::InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +00001763 ArrayRef<const MemRegion *> ExplicitRegions,
1764 ArrayRef<const MemRegion *> Regions) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001765 CStringLength::EntryMap Entries = state->get<CStringLength>();
1766 if (Entries.isEmpty())
1767 return state;
1768
1769 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1770 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1771
1772 // First build sets for the changed regions and their super-regions.
Jordy Rose537716a2011-08-27 22:51:26 +00001773 for (ArrayRef<const MemRegion *>::iterator
1774 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1775 const MemRegion *MR = *I;
Jordy Rosea5261542010-08-14 21:02:52 +00001776 Invalidated.insert(MR);
1777
1778 SuperRegions.insert(MR);
1779 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1780 MR = SR->getSuperRegion();
1781 SuperRegions.insert(MR);
1782 }
1783 }
1784
1785 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1786
1787 // Then loop over the entries in the current state.
1788 for (CStringLength::EntryMap::iterator I = Entries.begin(),
1789 E = Entries.end(); I != E; ++I) {
1790 const MemRegion *MR = I.getKey();
1791
1792 // Is this entry for a super-region of a changed region?
1793 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001794 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001795 continue;
1796 }
1797
1798 // Is this entry for a sub-region of a changed region?
1799 const MemRegion *Super = MR;
1800 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1801 Super = SR->getSuperRegion();
1802 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001803 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001804 break;
1805 }
1806 }
1807 }
1808
1809 return state->set<CStringLength>(Entries);
1810}
1811
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001812void CStringChecker::checkLiveSymbols(const ProgramState *state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001813 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001814 // Mark all symbols in our string length map as valid.
1815 CStringLength::EntryMap Entries = state->get<CStringLength>();
1816
1817 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1818 I != E; ++I) {
1819 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001820
Anna Zaks1d1d5152011-12-06 23:12:33 +00001821 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
1822 se = Len.symbol_end(); si != se; ++si)
Jordy Rosed5af0e12011-06-15 05:52:56 +00001823 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00001824 }
1825}
1826
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001827void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1828 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001829 if (!SR.hasDeadSymbols())
1830 return;
1831
Ted Kremenek18c66fd2011-08-15 22:09:50 +00001832 const ProgramState *state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001833 CStringLength::EntryMap Entries = state->get<CStringLength>();
1834 if (Entries.isEmpty())
1835 return;
1836
1837 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1838 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1839 I != E; ++I) {
1840 SVal Len = I.getData();
1841 if (SymbolRef Sym = Len.getAsSymbol()) {
1842 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00001843 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00001844 }
1845 }
1846
1847 state = state->set<CStringLength>(Entries);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001848 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001849}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001850
1851void ento::registerCStringChecker(CheckerManager &mgr) {
1852 mgr.registerChecker<CStringChecker>();
1853}