blob: 8edcfe0e2f0697310e1c2b189362f3e0e3ddf7d6 [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"
Anna Zaksf0dfc9c2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000017#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000018#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000019#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000020#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000022#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000023#include "llvm/ADT/STLExtras.h"
Jordy Roseccbf7ee2010-07-06 23:11:01 +000024#include "llvm/ADT/StringSwitch.h"
25
26using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000027using namespace ento;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000028
29namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000030class CStringChecker : public Checker< eval::Call,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000031 check::PreStmt<DeclStmt>,
32 check::LiveSymbols,
33 check::DeadSymbols,
34 check::RegionChanges
35 > {
Anna Zaks57300762012-02-07 00:56:14 +000036 mutable OwningPtr<BugType> BT_Null,
37 BT_Bounds,
38 BT_Overlap,
39 BT_NotCString,
40 BT_AdditionOverflow;
41
Jordy Rose9e49d9f2011-06-20 02:06:40 +000042 mutable const char *CurrentFunctionDescription;
43
Jordy Roseccbf7ee2010-07-06 23:11:01 +000044public:
Anna Zaks57300762012-02-07 00:56:14 +000045 /// The filter is used to filter out the diagnostics which are not enabled by
46 /// the user.
47 struct CStringChecksFilter {
48 DefaultBool CheckCStringNullArg;
49 DefaultBool CheckCStringOutOfBounds;
50 DefaultBool CheckCStringBufferOverlap;
51 DefaultBool CheckCStringNotNullTerm;
52 };
53
54 CStringChecksFilter Filter;
55
Jordy Roseccbf7ee2010-07-06 23:11:01 +000056 static void *getTag() { static int tag; return &tag; }
57
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000058 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
59 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +000060 void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000061 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +000062 bool wantsRegionChangeUpdate(ProgramStateRef state) const;
Jordy Rosea5261542010-08-14 21:02:52 +000063
Ted Kremenek8bef8232012-01-26 21:29:00 +000064 ProgramStateRef
65 checkRegionChanges(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000066 const StoreManager::InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +000067 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +000068 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +000069 const CallEvent *Call) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000070
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000071 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
72 const CallExpr *) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000073
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000074 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000075 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000076 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
77 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000078 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +000079 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000080 const Expr *Size,
81 const Expr *Source,
82 const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +000083 bool Restricted = false,
84 bool IsMempcpy = false) const;
Jordy Rosed325ffb2010-07-08 23:57:29 +000085
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000086 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000087
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000088 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
89 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000090 void evalstrLengthCommon(CheckerContext &C,
91 const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000092 bool IsStrnlen = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +000093
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000094 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
95 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
96 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000097 void evalStrcpyCommon(CheckerContext &C,
98 const CallExpr *CE,
99 bool returnEnd,
100 bool isBounded,
101 bool isAppending) const;
Lenny Maiorani067bbd02011-04-09 15:12:58 +0000102
103 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
104 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Jordy Rosee64f3112010-08-16 07:51:42 +0000105
Lenny Maiorani318dd922011-04-12 17:08:43 +0000106 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani357f6ee2011-04-25 22:21:00 +0000107 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranibd1d16a2011-04-28 15:09:11 +0000108 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani454fd2d2011-05-02 19:05:49 +0000109 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000110 void evalStrcmpCommon(CheckerContext &C,
111 const CallExpr *CE,
112 bool isBounded = false,
113 bool ignoreCase = false) const;
Lenny Maiorani318dd922011-04-12 17:08:43 +0000114
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000115 // Utility methods
Ted Kremenek8bef8232012-01-26 21:29:00 +0000116 std::pair<ProgramStateRef , ProgramStateRef >
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000117 static assumeZero(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000118 ProgramStateRef state, SVal V, QualType Ty);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000119
Ted Kremenek8bef8232012-01-26 21:29:00 +0000120 static ProgramStateRef setCStringLength(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000121 const MemRegion *MR,
122 SVal strLength);
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000123 static SVal getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000124 ProgramStateRef &state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000125 const Expr *Ex,
126 const MemRegion *MR,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000127 bool hypothetical);
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000128 SVal getCStringLength(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000129 ProgramStateRef &state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000130 const Expr *Ex,
131 SVal Buf,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000132 bool hypothetical = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000133
Lenny Maiorani318dd922011-04-12 17:08:43 +0000134 const StringLiteral *getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000135 ProgramStateRef &state,
Lenny Maiorani318dd922011-04-12 17:08:43 +0000136 const Expr *expr,
137 SVal val) const;
138
Ted Kremenek8bef8232012-01-26 21:29:00 +0000139 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
140 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000141 const Expr *Ex, SVal V);
Jordy Rosee64f3112010-08-16 07:51:42 +0000142
Ted Kremenek9c378f72011-08-12 23:37:29 +0000143 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000144 const MemRegion *MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000145
146 // Re-usable checks
Ted Kremenek8bef8232012-01-26 21:29:00 +0000147 ProgramStateRef checkNonNull(CheckerContext &C,
148 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000149 const Expr *S,
150 SVal l) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000151 ProgramStateRef CheckLocation(CheckerContext &C,
152 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000153 const Expr *S,
154 SVal l,
155 const char *message = NULL) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000156 ProgramStateRef CheckBufferAccess(CheckerContext &C,
157 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000158 const Expr *Size,
159 const Expr *FirstBuf,
160 const Expr *SecondBuf,
161 const char *firstMessage = NULL,
162 const char *secondMessage = NULL,
163 bool WarnAboutSize = false) const;
164
Ted Kremenek8bef8232012-01-26 21:29:00 +0000165 ProgramStateRef CheckBufferAccess(CheckerContext &C,
166 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000167 const Expr *Size,
168 const Expr *Buf,
169 const char *message = NULL,
170 bool WarnAboutSize = false) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000171 // This is a convenience override.
Jordy Rose5e5f1502011-06-20 03:49:16 +0000172 return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
173 WarnAboutSize);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000174 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000175 ProgramStateRef CheckOverlap(CheckerContext &C,
176 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000177 const Expr *Size,
178 const Expr *First,
179 const Expr *Second) const;
180 void emitOverlapBug(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000181 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000182 const Stmt *First,
183 const Stmt *Second) const;
184
Ted Kremenek8bef8232012-01-26 21:29:00 +0000185 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
186 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000187 NonLoc left,
188 NonLoc right) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000189};
Jordy Rosea5261542010-08-14 21:02:52 +0000190
191class CStringLength {
192public:
193 typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
194};
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000195} //end anonymous namespace
196
Jordy Rosea5261542010-08-14 21:02:52 +0000197namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000198namespace ento {
Jordy Rosea5261542010-08-14 21:02:52 +0000199 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000200 struct ProgramStateTrait<CStringLength>
201 : public ProgramStatePartialTrait<CStringLength::EntryMap> {
Jordy Rosea5261542010-08-14 21:02:52 +0000202 static void *GDMIndex() { return CStringChecker::getTag(); }
203 };
204}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000205}
Jordy Rosea5261542010-08-14 21:02:52 +0000206
Jordy Rosed325ffb2010-07-08 23:57:29 +0000207//===----------------------------------------------------------------------===//
208// Individual checks and utility methods.
209//===----------------------------------------------------------------------===//
210
Ted Kremenek8bef8232012-01-26 21:29:00 +0000211std::pair<ProgramStateRef , ProgramStateRef >
212CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000213 QualType Ty) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000214 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
215 if (!val)
Ted Kremenek8bef8232012-01-26 21:29:00 +0000216 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000217
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000218 SValBuilder &svalBuilder = C.getSValBuilder();
219 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
220 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000221}
Jordy Rosea6b808c2010-07-07 07:48:06 +0000222
Ted Kremenek8bef8232012-01-26 21:29:00 +0000223ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
224 ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000225 const Expr *S, SVal l) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000226 // If a previous check has failed, propagate the failure.
227 if (!state)
228 return NULL;
229
Ted Kremenek8bef8232012-01-26 21:29:00 +0000230 ProgramStateRef stateNull, stateNonNull;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000231 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed325ffb2010-07-08 23:57:29 +0000232
233 if (stateNull && !stateNonNull) {
Anna Zaks57300762012-02-07 00:56:14 +0000234 if (!Filter.CheckCStringNullArg)
235 return NULL;
236
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000237 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000238 if (!N)
239 return NULL;
240
Jordy Rosed325ffb2010-07-08 23:57:29 +0000241 if (!BT_Null)
Anna Zaks57300762012-02-07 00:56:14 +0000242 BT_Null.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000243 "Null pointer argument in call to byte string function"));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000244
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000245 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000246 llvm::raw_svector_ostream os(buf);
247 assert(CurrentFunctionDescription);
248 os << "Null pointer argument in call to " << CurrentFunctionDescription;
249
Jordy Rosea6b808c2010-07-07 07:48:06 +0000250 // Generate a report for this bug.
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000251 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Anna Zakse172e8b2011-08-17 23:00:25 +0000252 BugReport *report = new BugReport(*BT, os.str(), N);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000253
254 report->addRange(S->getSourceRange());
Jordan Rose68537992012-08-03 23:09:01 +0000255 bugreporter::addTrackNullOrUndefValueVisitor(N, S, report);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000256 C.EmitReport(report);
257 return NULL;
258 }
259
260 // From here on, assume that the value is non-null.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000261 assert(stateNonNull);
262 return stateNonNull;
Jordy Rosea6b808c2010-07-07 07:48:06 +0000263}
264
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000265// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek8bef8232012-01-26 21:29:00 +0000266ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
267 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000268 const Expr *S, SVal l,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000269 const char *warningMsg) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000270 // If a previous check has failed, propagate the failure.
271 if (!state)
272 return NULL;
273
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000274 // Check for out of bound array element access.
275 const MemRegion *R = l.getAsRegion();
276 if (!R)
277 return state;
278
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000279 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
280 if (!ER)
281 return state;
282
Zhongxing Xu018220c2010-08-11 06:10:55 +0000283 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000284 "CheckLocation should only be called with char* ElementRegions");
285
286 // Get the size of the array.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000287 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
288 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000289 SVal Extent =
290 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000291 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
292
293 // Get the index of the accessed element.
Gabor Greif89b06582010-09-09 10:51:37 +0000294 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000295
Ted Kremenek8bef8232012-01-26 21:29:00 +0000296 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
297 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000298 if (StOutBound && !StInBound) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000299 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000300 if (!N)
301 return NULL;
302
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000303 if (!BT_Bounds) {
304 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
305 "Byte string function accesses out-of-bound array element"));
306 }
307 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
308
309 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000310 BugReport *report;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000311 if (warningMsg) {
Anna Zakse172e8b2011-08-17 23:00:25 +0000312 report = new BugReport(*BT, warningMsg, N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000313 } else {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000314 assert(CurrentFunctionDescription);
315 assert(CurrentFunctionDescription[0] != '\0');
316
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000317 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000318 llvm::raw_svector_ostream os(buf);
319 os << (char)toupper(CurrentFunctionDescription[0])
320 << &CurrentFunctionDescription[1]
321 << " accesses out-of-bound array element";
Anna Zakse172e8b2011-08-17 23:00:25 +0000322 report = new BugReport(*BT, os.str(), N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000323 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000324
325 // FIXME: It would be nice to eventually make this diagnostic more clear,
326 // e.g., by referencing the original declaration or by saying *why* this
327 // reference is outside the range.
328
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000329 report->addRange(S->getSourceRange());
330 C.EmitReport(report);
331 return NULL;
332 }
333
334 // Array bound check succeeded. From this point forward the array bound
335 // should always succeed.
336 return StInBound;
337}
338
Ted Kremenek8bef8232012-01-26 21:29:00 +0000339ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
340 ProgramStateRef state,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000341 const Expr *Size,
342 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000343 const Expr *SecondBuf,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000344 const char *firstMessage,
Jordy Rose5e5f1502011-06-20 03:49:16 +0000345 const char *secondMessage,
346 bool WarnAboutSize) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000347 // If a previous check has failed, propagate the failure.
348 if (!state)
349 return NULL;
350
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000351 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000352 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000353 const LocationContext *LCtx = C.getLocationContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000354
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000355 QualType sizeTy = Size->getType();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000356 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
357
Jordy Rosea6b808c2010-07-07 07:48:06 +0000358 // Check that the first buffer is non-null.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000359 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000360 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000361 if (!state)
362 return NULL;
363
Anna Zaks57300762012-02-07 00:56:14 +0000364 // If out-of-bounds checking is turned off, skip the rest.
365 if (!Filter.CheckCStringOutOfBounds)
366 return state;
367
Jordy Rosed325ffb2010-07-08 23:57:29 +0000368 // Get the access length and make sure it is known.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000369 // FIXME: This assumes the caller has already checked that the access length
370 // is positive. And that it's unsigned.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000371 SVal LengthVal = state->getSVal(Size, LCtx);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000372 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
373 if (!Length)
374 return state;
375
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000376 // Compute the offset of the last element to be accessed: size-1.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000377 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
378 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
379 *Length, One, sizeTy));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000380
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000381 // Check that the first buffer is sufficiently long.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000382 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000383 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000384 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
385
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000386 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
387 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000388 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000389
Jordy Roseb6a40262010-08-05 23:11:30 +0000390 // If the buffer isn't large enough, abort.
391 if (!state)
392 return NULL;
393 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000394
395 // If there's a second buffer, check it as well.
396 if (SecondBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000397 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000398 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000399 if (!state)
400 return NULL;
401
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000402 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000403 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000404 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
405
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000406 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
407 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000408 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseb6a40262010-08-05 23:11:30 +0000409 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000410 }
411
412 // Large enough or not, return this state!
413 return state;
414}
415
Ted Kremenek8bef8232012-01-26 21:29:00 +0000416ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
417 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000418 const Expr *Size,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000419 const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000420 const Expr *Second) const {
Anna Zaks57300762012-02-07 00:56:14 +0000421 if (!Filter.CheckCStringBufferOverlap)
422 return state;
423
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000424 // Do a simple check for overlap: if the two arguments are from the same
425 // buffer, see if the end of the first is greater than the start of the second
426 // or vice versa.
427
Jordy Rosed325ffb2010-07-08 23:57:29 +0000428 // If a previous check has failed, propagate the failure.
429 if (!state)
430 return NULL;
431
Ted Kremenek8bef8232012-01-26 21:29:00 +0000432 ProgramStateRef stateTrue, stateFalse;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000433
434 // Get the buffer values and make sure they're known locations.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000435 const LocationContext *LCtx = C.getLocationContext();
436 SVal firstVal = state->getSVal(First, LCtx);
437 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000438
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000439 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
440 if (!firstLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000441 return state;
442
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000443 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
444 if (!secondLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000445 return state;
446
447 // Are the two values the same?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000448 SValBuilder &svalBuilder = C.getSValBuilder();
449 llvm::tie(stateTrue, stateFalse) =
450 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000451
452 if (stateTrue && !stateFalse) {
453 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000454 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000455 return NULL;
456 }
457
Ted Kremenek28f47b92010-12-01 22:16:56 +0000458 // assume the two expressions are not equal.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000459 assert(stateFalse);
460 state = stateFalse;
461
462 // Which value comes first?
Jordy Roseee2fde12011-06-16 05:56:50 +0000463 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000464 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
465 *firstLoc, *secondLoc, cmpTy);
466 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
467 if (!reverseTest)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000468 return state;
469
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000470 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000471 if (stateTrue) {
472 if (stateFalse) {
473 // If we don't know which one comes first, we can't perform this test.
474 return state;
475 } else {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000476 // Switch the values so that firstVal is before secondVal.
477 Loc *tmpLoc = firstLoc;
478 firstLoc = secondLoc;
479 secondLoc = tmpLoc;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000480
481 // Switch the Exprs as well, so that they still correspond.
482 const Expr *tmpExpr = First;
483 First = Second;
484 Second = tmpExpr;
485 }
486 }
487
488 // Get the length, and make sure it too is known.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000489 SVal LengthVal = state->getSVal(Size, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000490 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
491 if (!Length)
492 return state;
493
494 // Convert the first buffer's start address to char*.
495 // Bail out if the cast fails.
Jordy Roseee2fde12011-06-16 05:56:50 +0000496 ASTContext &Ctx = svalBuilder.getContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000497 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose1e022412011-06-16 05:51:02 +0000498 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
499 First->getType());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000500 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
501 if (!FirstStartLoc)
502 return state;
503
504 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000505 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000506 *FirstStartLoc, *Length, CharPtrTy);
507 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
508 if (!FirstEndLoc)
509 return state;
510
511 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000512 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
513 *FirstEndLoc, *secondLoc, cmpTy);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000514 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
515 if (!OverlapTest)
516 return state;
517
Ted Kremenek28f47b92010-12-01 22:16:56 +0000518 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000519
520 if (stateTrue && !stateFalse) {
521 // Overlap!
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000522 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000523 return NULL;
524 }
525
Ted Kremenek28f47b92010-12-01 22:16:56 +0000526 // assume the two expressions don't overlap.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000527 assert(stateFalse);
528 return stateFalse;
529}
530
Ted Kremenek8bef8232012-01-26 21:29:00 +0000531void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000532 const Stmt *First, const Stmt *Second) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000533 ExplodedNode *N = C.generateSink(state);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000534 if (!N)
535 return;
536
537 if (!BT_Overlap)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000538 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000539
540 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000541 BugReport *report =
542 new BugReport(*BT_Overlap,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000543 "Arguments must not be overlapping buffers", N);
544 report->addRange(First->getSourceRange());
545 report->addRange(Second->getSourceRange());
546
547 C.EmitReport(report);
548}
549
Ted Kremenek8bef8232012-01-26 21:29:00 +0000550ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
551 ProgramStateRef state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000552 NonLoc left,
553 NonLoc right) const {
Anna Zaks57300762012-02-07 00:56:14 +0000554 // If out-of-bounds checking is turned off, skip the rest.
555 if (!Filter.CheckCStringOutOfBounds)
556 return state;
557
Jordy Rosed5af0e12011-06-15 05:52:56 +0000558 // If a previous check has failed, propagate the failure.
559 if (!state)
560 return NULL;
561
562 SValBuilder &svalBuilder = C.getSValBuilder();
563 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
564
565 QualType sizeTy = svalBuilder.getContext().getSizeType();
566 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
567 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
568
Anna Zakse3d250e2011-12-11 18:43:40 +0000569 SVal maxMinusRight;
570 if (isa<nonloc::ConcreteInt>(right)) {
571 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
572 sizeTy);
573 } else {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000574 // Try switching the operands. (The order of these two assignments is
575 // important!)
576 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
577 sizeTy);
578 left = right;
579 }
580
581 if (NonLoc *maxMinusRightNL = dyn_cast<NonLoc>(&maxMinusRight)) {
582 QualType cmpTy = svalBuilder.getConditionType();
583 // If left > max - right, we have an overflow.
584 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
585 *maxMinusRightNL, cmpTy);
586
Ted Kremenek8bef8232012-01-26 21:29:00 +0000587 ProgramStateRef stateOverflow, stateOkay;
Jordy Rosed5af0e12011-06-15 05:52:56 +0000588 llvm::tie(stateOverflow, stateOkay) =
589 state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
590
591 if (stateOverflow && !stateOkay) {
592 // We have an overflow. Emit a bug report.
593 ExplodedNode *N = C.generateSink(stateOverflow);
594 if (!N)
595 return NULL;
596
597 if (!BT_AdditionOverflow)
598 BT_AdditionOverflow.reset(new BuiltinBug("API",
599 "Sum of expressions causes overflow"));
600
Jordy Rosed5af0e12011-06-15 05:52:56 +0000601 // This isn't a great error message, but this should never occur in real
602 // code anyway -- you'd have to create a buffer longer than a size_t can
603 // represent, which is sort of a contradiction.
Jordy Rose8cc24912011-06-20 03:51:53 +0000604 const char *warning =
605 "This expression will create a string whose length is too big to "
606 "be represented as a size_t";
Jordy Rosed5af0e12011-06-15 05:52:56 +0000607
608 // Generate a report for this bug.
Jordy Rose8cc24912011-06-20 03:51:53 +0000609 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000610 C.EmitReport(report);
611
612 return NULL;
613 }
614
615 // From now on, assume an overflow didn't occur.
616 assert(stateOkay);
617 state = stateOkay;
618 }
619
620 return state;
621}
622
Ted Kremenek8bef8232012-01-26 21:29:00 +0000623ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000624 const MemRegion *MR,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000625 SVal strLength) {
626 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rosee64f3112010-08-16 07:51:42 +0000627
628 MR = MR->StripCasts();
629
630 switch (MR->getKind()) {
631 case MemRegion::StringRegionKind:
632 // FIXME: This can happen if we strcpy() into a string region. This is
633 // undefined [C99 6.4.5p6], but we should still warn about it.
634 return state;
635
636 case MemRegion::SymbolicRegionKind:
637 case MemRegion::AllocaRegionKind:
638 case MemRegion::VarRegionKind:
639 case MemRegion::FieldRegionKind:
640 case MemRegion::ObjCIvarRegionKind:
Jordy Rose210c05b2011-06-15 05:14:03 +0000641 // These are the types we can currently track string lengths for.
642 break;
Jordy Rosee64f3112010-08-16 07:51:42 +0000643
644 case MemRegion::ElementRegionKind:
645 // FIXME: Handle element regions by upper-bounding the parent region's
646 // string length.
647 return state;
648
649 default:
650 // Other regions (mostly non-data) can't have a reliable C string length.
651 // For now, just ignore the change.
652 // FIXME: These are rare but not impossible. We should output some kind of
653 // warning for things like strcpy((char[]){'a', 0}, "b");
654 return state;
655 }
Jordy Rose210c05b2011-06-15 05:14:03 +0000656
657 if (strLength.isUnknown())
658 return state->remove<CStringLength>(MR);
659
660 return state->set<CStringLength>(MR, strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +0000661}
662
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000663SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000664 ProgramStateRef &state,
Jordy Rosea5261542010-08-14 21:02:52 +0000665 const Expr *Ex,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000666 const MemRegion *MR,
667 bool hypothetical) {
668 if (!hypothetical) {
669 // If there's a recorded length, go ahead and return it.
670 const SVal *Recorded = state->get<CStringLength>(MR);
671 if (Recorded)
672 return *Recorded;
673 }
Jordy Rosea5261542010-08-14 21:02:52 +0000674
675 // Otherwise, get a new symbol and update the state.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +0000676 unsigned Count = C.getCurrentBlockCount();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000677 SValBuilder &svalBuilder = C.getSValBuilder();
678 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000679 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
680 MR, Ex, sizeTy, Count);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000681
682 if (!hypothetical)
683 state = state->set<CStringLength>(MR, strLength);
684
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000685 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000686}
687
Ted Kremenek8bef8232012-01-26 21:29:00 +0000688SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000689 const Expr *Ex, SVal Buf,
690 bool hypothetical) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000691 const MemRegion *MR = Buf.getAsRegion();
692 if (!MR) {
693 // If we can't get a region, see if it's something we /know/ isn't a
694 // C string. In the context of locations, the only time we can issue such
695 // a warning is for labels.
696 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
Anna Zaks57300762012-02-07 00:56:14 +0000697 if (!Filter.CheckCStringNotNullTerm)
698 return UndefinedVal();
699
Anna Zaks0bd6b112011-10-26 21:06:34 +0000700 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000701 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000702 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000703 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000704
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000705 SmallString<120> buf;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000706 llvm::raw_svector_ostream os(buf);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000707 assert(CurrentFunctionDescription);
708 os << "Argument to " << CurrentFunctionDescription
709 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000710 << "', which is not a null-terminated string";
711
712 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000713 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000714 os.str(), N);
715
716 report->addRange(Ex->getSourceRange());
717 C.EmitReport(report);
718 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000719 return UndefinedVal();
Anna Zaks57300762012-02-07 00:56:14 +0000720
Jordy Rose19c5dd12010-07-27 01:37:31 +0000721 }
722
Jordy Rosea5261542010-08-14 21:02:52 +0000723 // If it's not a region and not a label, give up.
724 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000725 }
726
Jordy Rosea5261542010-08-14 21:02:52 +0000727 // If we have a region, strip casts from it and see if we can figure out
728 // its length. For anything we can't figure out, just return UnknownVal.
729 MR = MR->StripCasts();
730
731 switch (MR->getKind()) {
732 case MemRegion::StringRegionKind: {
733 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
734 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000735 SValBuilder &svalBuilder = C.getSValBuilder();
736 QualType sizeTy = svalBuilder.getContext().getSizeType();
737 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
738 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000739 }
740 case MemRegion::SymbolicRegionKind:
741 case MemRegion::AllocaRegionKind:
742 case MemRegion::VarRegionKind:
743 case MemRegion::FieldRegionKind:
744 case MemRegion::ObjCIvarRegionKind:
Jordy Rosed5af0e12011-06-15 05:52:56 +0000745 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rosea5261542010-08-14 21:02:52 +0000746 case MemRegion::CompoundLiteralRegionKind:
747 // FIXME: Can we track this? Is it necessary?
748 return UnknownVal();
749 case MemRegion::ElementRegionKind:
750 // FIXME: How can we handle this? It's not good enough to subtract the
751 // offset from the base string length; consider "123\x00567" and &a[5].
752 return UnknownVal();
753 default:
754 // Other regions (mostly non-data) can't have a reliable C string length.
755 // In this case, an error is emitted and UndefinedVal is returned.
756 // The caller should always be prepared to handle this case.
Anna Zaks57300762012-02-07 00:56:14 +0000757 if (!Filter.CheckCStringNotNullTerm)
758 return UndefinedVal();
759
Anna Zaks0bd6b112011-10-26 21:06:34 +0000760 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000761 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000762 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000763 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000764
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000765 SmallString<120> buf;
Jordy Rosea5261542010-08-14 21:02:52 +0000766 llvm::raw_svector_ostream os(buf);
767
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000768 assert(CurrentFunctionDescription);
769 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rosea5261542010-08-14 21:02:52 +0000770
771 if (SummarizeRegion(os, C.getASTContext(), MR))
772 os << ", which is not a null-terminated string";
773 else
774 os << "not a null-terminated string";
775
776 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000777 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rosea5261542010-08-14 21:02:52 +0000778 os.str(), N);
779
780 report->addRange(Ex->getSourceRange());
781 C.EmitReport(report);
782 }
783
784 return UndefinedVal();
785 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000786}
787
Lenny Maiorani318dd922011-04-12 17:08:43 +0000788const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000789 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +0000790
791 // Get the memory region pointed to by the val.
792 const MemRegion *bufRegion = val.getAsRegion();
793 if (!bufRegion)
794 return NULL;
795
796 // Strip casts off the memory region.
797 bufRegion = bufRegion->StripCasts();
798
799 // Cast the memory region to a string region.
800 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
801 if (!strRegion)
802 return NULL;
803
804 // Return the actual string in the string region.
805 return strRegion->getStringLiteral();
806}
807
Ted Kremenek8bef8232012-01-26 21:29:00 +0000808ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
809 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000810 const Expr *E, SVal V) {
811 Loc *L = dyn_cast<Loc>(&V);
812 if (!L)
813 return state;
814
815 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
816 // some assumptions about the value that CFRefCount can't. Even so, it should
817 // probably be refactored.
818 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
819 const MemRegion *R = MR->getRegion()->StripCasts();
820
821 // Are we dealing with an ElementRegion? If so, we should be invalidating
822 // the super-region.
823 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
824 R = ER->getSuperRegion();
825 // FIXME: What about layers of ElementRegions?
826 }
827
828 // Invalidate this region.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +0000829 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3133f792012-02-17 23:13:45 +0000830 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
831 return state->invalidateRegions(R, E, Count, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +0000832 }
833
834 // If we have a non-region value by chance, just remove the binding.
835 // FIXME: is this necessary or correct? This handles the non-Region
836 // cases. Is it ever valid to store to these?
837 return state->unbindLoc(*L);
838}
839
Ted Kremenek9c378f72011-08-12 23:37:29 +0000840bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000841 const MemRegion *MR) {
Ted Kremenek96979342011-08-12 20:02:48 +0000842 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000843
Jordy Rose096aef92011-08-12 21:41:07 +0000844 switch (MR->getKind()) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000845 case MemRegion::FunctionTextRegionKind: {
Jordy Rose096aef92011-08-12 21:41:07 +0000846 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000847 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000848 os << "the address of the function '" << *FD << '\'';
Jordy Rose19c5dd12010-07-27 01:37:31 +0000849 else
850 os << "the address of a function";
851 return true;
852 }
853 case MemRegion::BlockTextRegionKind:
854 os << "block text";
855 return true;
856 case MemRegion::BlockDataRegionKind:
857 os << "a block";
858 return true;
859 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000860 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000861 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000862 return true;
863 case MemRegion::VarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000864 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000865 return true;
866 case MemRegion::FieldRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000867 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000868 return true;
869 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000870 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000871 return true;
872 default:
873 return false;
874 }
875}
876
Jordy Rosed325ffb2010-07-08 23:57:29 +0000877//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000878// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000879//===----------------------------------------------------------------------===//
880
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000881void CStringChecker::evalCopyCommon(CheckerContext &C,
882 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000883 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000884 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000885 const Expr *Source, bool Restricted,
886 bool IsMempcpy) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000887 CurrentFunctionDescription = "memory copy function";
888
Jordy Rosed325ffb2010-07-08 23:57:29 +0000889 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000890 const LocationContext *LCtx = C.getLocationContext();
891 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000892 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000893
Ted Kremenek8bef8232012-01-26 21:29:00 +0000894 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose1e022412011-06-16 05:51:02 +0000895 llvm::tie(stateZeroSize, stateNonZeroSize) =
896 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000897
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000898 // Get the value of the Dest.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000899 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000900
901 // If the size is zero, there won't be any actual memory access, so
902 // just bind the return value to the destination buffer and return.
Anna Zaksdd160f32012-05-03 18:21:28 +0000903 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000904 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000905 C.addTransition(stateZeroSize);
Anna Zaksdd160f32012-05-03 18:21:28 +0000906 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000907 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000908
909 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000910 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000911 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000912
913 // Ensure the destination is not null. If it is NULL there will be a
914 // NULL pointer dereference.
915 state = checkNonNull(C, state, Dest, destVal);
916 if (!state)
917 return;
918
919 // Get the value of the Src.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000920 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000921
922 // Ensure the source is not null. If it is NULL there will be a
923 // NULL pointer dereference.
924 state = checkNonNull(C, state, Source, srcVal);
925 if (!state)
926 return;
927
Jordy Rose7182b962011-06-04 01:50:25 +0000928 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000929 const char * const writeWarning =
930 "Memory copy function overflows destination buffer";
Jordy Rosee64f3112010-08-16 07:51:42 +0000931 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000932 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000933 if (Restricted)
934 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000935
Jordy Rose7182b962011-06-04 01:50:25 +0000936 if (!state)
937 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000938
Jordy Rose7182b962011-06-04 01:50:25 +0000939 // If this is mempcpy, get the byte after the last byte copied and
940 // bind the expr.
941 if (IsMempcpy) {
942 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
943 assert(destRegVal && "Destination should be a known MemRegionVal here");
944
945 // Get the length to copy.
946 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
947
948 if (lenValNonLoc) {
949 // Get the byte after the last byte copied.
950 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
951 *destRegVal,
952 *lenValNonLoc,
953 Dest->getType());
954
955 // The byte after the last byte copied is the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000956 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000957 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000958 // If we don't know how much we copied, we can at least
959 // conjure a return value for later.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +0000960 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3b1df8b2012-08-22 06:26:06 +0000961 SVal result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, Count);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000962 state = state->BindExpr(CE, LCtx, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000963 }
964
Jordy Rose7182b962011-06-04 01:50:25 +0000965 } else {
966 // All other copies return the destination buffer.
967 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000968 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000969 }
Jordy Rose7182b962011-06-04 01:50:25 +0000970
971 // Invalidate the destination.
972 // FIXME: Even if we can't perfectly model the copy, we should see if we
973 // can use LazyCompoundVals to copy the source values into the destination.
974 // This would probably remove any existing bindings past the end of the
975 // copied region, but that's still an improvement over blank invalidation.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000976 state = InvalidateBuffer(C, state, Dest,
977 state->getSVal(Dest, C.getLocationContext()));
Anna Zaks0bd6b112011-10-26 21:06:34 +0000978 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000979 }
980}
981
982
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000983void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000984 if (CE->getNumArgs() < 3)
985 return;
986
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000987 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000988 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000989 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000990 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000991
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000992 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
993}
994
995void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000996 if (CE->getNumArgs() < 3)
997 return;
998
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000999 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
1000 // The return value is a pointer to the byte following the last written byte.
1001 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001002 ProgramStateRef state = C.getState();
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001003
1004 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001005}
1006
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001007void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001008 if (CE->getNumArgs() < 3)
1009 return;
1010
Jordy Rosed325ffb2010-07-08 23:57:29 +00001011 // void *memmove(void *dst, const void *src, size_t n);
1012 // The return value is the address of the destination buffer.
1013 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001014 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001015
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001016 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001017}
1018
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001019void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001020 if (CE->getNumArgs() < 3)
1021 return;
1022
Jordy Rosed325ffb2010-07-08 23:57:29 +00001023 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001024 evalCopyCommon(C, CE, C.getState(),
1025 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001026}
1027
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001028void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001029 if (CE->getNumArgs() < 3)
1030 return;
1031
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001032 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001033 CurrentFunctionDescription = "memory comparison function";
1034
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001035 const Expr *Left = CE->getArg(0);
1036 const Expr *Right = CE->getArg(1);
1037 const Expr *Size = CE->getArg(2);
1038
Ted Kremenek8bef8232012-01-26 21:29:00 +00001039 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001040 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001041
Jordy Rosed325ffb2010-07-08 23:57:29 +00001042 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001043 const LocationContext *LCtx = C.getLocationContext();
1044 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001045 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001046
Ted Kremenek8bef8232012-01-26 21:29:00 +00001047 ProgramStateRef stateZeroSize, stateNonZeroSize;
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001048 llvm::tie(stateZeroSize, stateNonZeroSize) =
1049 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001050
Jordy Rosed325ffb2010-07-08 23:57:29 +00001051 // If the size can be zero, the result will be 0 in that case, and we don't
1052 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001053 if (stateZeroSize) {
1054 state = stateZeroSize;
Ted Kremenek5eca4822012-01-06 22:09:28 +00001055 state = state->BindExpr(CE, LCtx,
1056 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001057 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001058 }
1059
Jordy Rosed325ffb2010-07-08 23:57:29 +00001060 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001061 if (stateNonZeroSize) {
1062 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +00001063 // If we know the two buffers are the same, we know the result is 0.
1064 // First, get the two buffers' addresses. Another checker will have already
1065 // made sure they're not undefined.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001066 DefinedOrUnknownSVal LV =
1067 cast<DefinedOrUnknownSVal>(state->getSVal(Left, LCtx));
1068 DefinedOrUnknownSVal RV =
1069 cast<DefinedOrUnknownSVal>(state->getSVal(Right, LCtx));
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001070
Jordy Rosed325ffb2010-07-08 23:57:29 +00001071 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001072 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001073 ProgramStateRef StSameBuf, StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +00001074 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001075
Jordy Rose1e022412011-06-16 05:51:02 +00001076 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +00001077 // and we only need to check one size.
1078 if (StSameBuf) {
1079 state = StSameBuf;
1080 state = CheckBufferAccess(C, state, Size, Left);
1081 if (state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001082 state = StSameBuf->BindExpr(CE, LCtx,
1083 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001084 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001085 }
1086 }
1087
1088 // If the two arguments might be different buffers, we have to check the
1089 // size of both of them.
1090 if (StNotSameBuf) {
1091 state = StNotSameBuf;
1092 state = CheckBufferAccess(C, state, Size, Left, Right);
1093 if (state) {
1094 // The return value is the comparison result, which we don't know.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001095 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3b1df8b2012-08-22 06:26:06 +00001096 SVal CmpV = svalBuilder.conjureSymbolVal(0, CE, LCtx, Count);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001097 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001098 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001099 }
1100 }
1101 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001102}
1103
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001104void CStringChecker::evalstrLength(CheckerContext &C,
1105 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001106 if (CE->getNumArgs() < 1)
1107 return;
1108
Jordy Rose19c5dd12010-07-27 01:37:31 +00001109 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001110 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1111}
1112
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001113void CStringChecker::evalstrnLength(CheckerContext &C,
1114 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001115 if (CE->getNumArgs() < 2)
1116 return;
1117
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001118 // size_t strnlen(const char *s, size_t maxlen);
1119 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1120}
1121
1122void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001123 bool IsStrnlen) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001124 CurrentFunctionDescription = "string length function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001125 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001126 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose793bff32011-06-14 01:15:31 +00001127
1128 if (IsStrnlen) {
1129 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001130 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rose793bff32011-06-14 01:15:31 +00001131
Ted Kremenek8bef8232012-01-26 21:29:00 +00001132 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose793bff32011-06-14 01:15:31 +00001133 llvm::tie(stateZeroSize, stateNonZeroSize) =
1134 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1135
1136 // If the size can be zero, the result will be 0 in that case, and we don't
1137 // have to check the string itself.
1138 if (stateZeroSize) {
1139 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001140 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001141 C.addTransition(stateZeroSize);
Jordy Rose793bff32011-06-14 01:15:31 +00001142 }
1143
1144 // If the size is GUARANTEED to be zero, we're done!
1145 if (!stateNonZeroSize)
1146 return;
1147
1148 // Otherwise, record the assumption that the size is nonzero.
1149 state = stateNonZeroSize;
1150 }
1151
1152 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001153 const Expr *Arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001154 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001155
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001156 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001157
Jordy Rosebd32bee2011-06-14 01:26:48 +00001158 if (!state)
1159 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001160
Jordy Rosebd32bee2011-06-14 01:26:48 +00001161 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001162
Jordy Rosebd32bee2011-06-14 01:26:48 +00001163 // If the argument isn't a valid C string, there's no valid state to
1164 // transition to.
1165 if (strLength.isUndef())
1166 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001167
Jordy Rosebd32bee2011-06-14 01:26:48 +00001168 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001169
Jordy Rosebd32bee2011-06-14 01:26:48 +00001170 // If the check is for strnlen() then bind the return value to no more than
1171 // the maxlen value.
1172 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001173 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001174
Jordy Rosebd32bee2011-06-14 01:26:48 +00001175 // It's a little unfortunate to be getting this again,
1176 // but it's not that expensive...
1177 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001178 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001179
Jordy Rosebd32bee2011-06-14 01:26:48 +00001180 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1181 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001182
Jordy Rosebd32bee2011-06-14 01:26:48 +00001183 if (strLengthNL && maxlenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001184 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001185
Jordy Rosebd32bee2011-06-14 01:26:48 +00001186 // Check if the strLength is greater than the maxlen.
1187 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
1188 state->assume(cast<DefinedOrUnknownSVal>
1189 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1190 *strLengthNL,
1191 *maxlenValNL,
1192 cmpTy)));
Jordy Rose793bff32011-06-14 01:15:31 +00001193
Jordy Rosebd32bee2011-06-14 01:26:48 +00001194 if (stateStringTooLong && !stateStringNotTooLong) {
1195 // If the string is longer than maxlen, return maxlen.
1196 result = *maxlenValNL;
1197 } else if (stateStringNotTooLong && !stateStringTooLong) {
1198 // If the string is shorter than maxlen, return its length.
1199 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001200 }
1201 }
1202
Jordy Rosebd32bee2011-06-14 01:26:48 +00001203 if (result.isUnknown()) {
1204 // If we don't have enough information for a comparison, there's
1205 // no guarantee the full string length will actually be returned.
1206 // All we know is the return value is the min of the string length
1207 // and the limit. This is better than nothing.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001208 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3b1df8b2012-08-22 06:26:06 +00001209 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, Count);
Jordy Rosebd32bee2011-06-14 01:26:48 +00001210 NonLoc *resultNL = cast<NonLoc>(&result);
1211
1212 if (strLengthNL) {
1213 state = state->assume(cast<DefinedOrUnknownSVal>
1214 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1215 *resultNL,
1216 *strLengthNL,
1217 cmpTy)), true);
1218 }
1219
1220 if (maxlenValNL) {
1221 state = state->assume(cast<DefinedOrUnknownSVal>
1222 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1223 *resultNL,
1224 *maxlenValNL,
1225 cmpTy)), true);
1226 }
1227 }
1228
1229 } else {
1230 // This is a plain strlen(), not strnlen().
1231 result = cast<DefinedOrUnknownSVal>(strLength);
1232
1233 // If we don't know the length of the string, conjure a return
1234 // value, so it can be used in constraints, at least.
1235 if (result.isUnknown()) {
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001236 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3b1df8b2012-08-22 06:26:06 +00001237 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, Count);
Jordy Rosebd32bee2011-06-14 01:26:48 +00001238 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001239 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001240
1241 // Bind the return value.
1242 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek5eca4822012-01-06 22:09:28 +00001243 state = state->BindExpr(CE, LCtx, result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001244 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001245}
1246
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001247void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001248 if (CE->getNumArgs() < 2)
1249 return;
1250
Jordy Rosee64f3112010-08-16 07:51:42 +00001251 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001252 evalStrcpyCommon(C, CE,
1253 /* returnEnd = */ false,
1254 /* isBounded = */ false,
1255 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001256}
1257
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001258void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001259 if (CE->getNumArgs() < 3)
1260 return;
1261
Jordy Rosec1525862011-06-04 00:05:23 +00001262 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001263 evalStrcpyCommon(C, CE,
1264 /* returnEnd = */ false,
1265 /* isBounded = */ true,
1266 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001267}
1268
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001269void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001270 if (CE->getNumArgs() < 2)
1271 return;
1272
Jordy Rosee64f3112010-08-16 07:51:42 +00001273 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001274 evalStrcpyCommon(C, CE,
1275 /* returnEnd = */ true,
1276 /* isBounded = */ false,
1277 /* isAppending = */ false);
1278}
1279
1280void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001281 if (CE->getNumArgs() < 2)
1282 return;
1283
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001284 //char *strcat(char *restrict s1, const char *restrict s2);
1285 evalStrcpyCommon(C, CE,
1286 /* returnEnd = */ false,
1287 /* isBounded = */ false,
1288 /* isAppending = */ true);
1289}
1290
1291void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001292 if (CE->getNumArgs() < 3)
1293 return;
1294
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001295 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1296 evalStrcpyCommon(C, CE,
1297 /* returnEnd = */ false,
1298 /* isBounded = */ true,
1299 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001300}
1301
Ted Kremenek9c149532010-12-01 21:57:22 +00001302void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001303 bool returnEnd, bool isBounded,
1304 bool isAppending) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001305 CurrentFunctionDescription = "string copy function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001306 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001307 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosee64f3112010-08-16 07:51:42 +00001308
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001309 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001310 const Expr *Dst = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001311 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +00001312
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001313 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001314 if (!state)
1315 return;
1316
1317 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001318 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001319 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001320 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001321 if (!state)
1322 return;
1323
1324 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001325 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001326
1327 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001328 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001329 return;
1330
Jordy Rosed5af0e12011-06-15 05:52:56 +00001331 SValBuilder &svalBuilder = C.getSValBuilder();
1332 QualType cmpTy = svalBuilder.getConditionType();
Jordy Rose8912aae2011-06-20 21:55:40 +00001333 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001334
Jordy Rose8912aae2011-06-20 21:55:40 +00001335 // These two values allow checking two kinds of errors:
1336 // - actual overflows caused by a source that doesn't fit in the destination
1337 // - potential overflows caused by a bound that could exceed the destination
Jordy Rosed5af0e12011-06-15 05:52:56 +00001338 SVal amountCopied = UnknownVal();
Jordy Rose8912aae2011-06-20 21:55:40 +00001339 SVal maxLastElementIndex = UnknownVal();
1340 const char *boundWarning = NULL;
Jordy Rosed5af0e12011-06-15 05:52:56 +00001341
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001342 // If the function is strncpy, strncat, etc... it is bounded.
1343 if (isBounded) {
1344 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001345 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001346 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001347
Jordy Rosed5af0e12011-06-15 05:52:56 +00001348 // Protect against misdeclared strncpy().
Jordy Rose8912aae2011-06-20 21:55:40 +00001349 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001350
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001351 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1352 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1353
Jordy Rosed5af0e12011-06-15 05:52:56 +00001354 // If we know both values, we might be able to figure out how much
1355 // we're copying.
1356 if (strLengthNL && lenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001357 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001358
Jordy Rosed5af0e12011-06-15 05:52:56 +00001359 // Check if the max number to copy is less than the length of the src.
Jordy Rose8912aae2011-06-20 21:55:40 +00001360 // If the bound is equal to the source length, strncpy won't null-
1361 // terminate the result!
Jordy Rosed5af0e12011-06-15 05:52:56 +00001362 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) =
1363 state->assume(cast<DefinedOrUnknownSVal>
Jordy Rose8912aae2011-06-20 21:55:40 +00001364 (svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL,
Jordy Rosed5af0e12011-06-15 05:52:56 +00001365 *lenValNL, cmpTy)));
1366
1367 if (stateSourceTooLong && !stateSourceNotTooLong) {
1368 // Max number to copy is less than the length of the src, so the actual
1369 // strLength copied is the max number arg.
1370 state = stateSourceTooLong;
1371 amountCopied = lenVal;
1372
1373 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1374 // The source buffer entirely fits in the bound.
1375 state = stateSourceNotTooLong;
1376 amountCopied = strLength;
1377 }
1378 }
1379
Jordy Rose5e5f1502011-06-20 03:49:16 +00001380 // We still want to know if the bound is known to be too large.
Jordy Rose8912aae2011-06-20 21:55:40 +00001381 if (lenValNL) {
1382 if (isAppending) {
1383 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1384
1385 // Get the string length of the destination. If the destination is
1386 // memory that can't have a string length, we shouldn't be copying
1387 // into it anyway.
1388 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1389 if (dstStrLength.isUndef())
1390 return;
1391
1392 if (NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength)) {
1393 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1394 *lenValNL,
1395 *dstStrLengthNL,
1396 sizeTy);
1397 boundWarning = "Size argument is greater than the free space in the "
1398 "destination buffer";
1399 }
1400
1401 } else {
1402 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1403 // (Yes, strncpy and strncat differ in how they treat termination.
1404 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose6e4244e2012-05-14 17:58:35 +00001405
1406 // We need a special case for when the copy size is zero, in which
1407 // case strncpy will do no work at all. Our bounds check uses n-1
1408 // as the last element accessed, so n == 0 is problematic.
1409 ProgramStateRef StateZeroSize, StateNonZeroSize;
1410 llvm::tie(StateZeroSize, StateNonZeroSize) =
1411 assumeZero(C, state, *lenValNL, sizeTy);
1412
1413 // If the size is known to be zero, we're done.
1414 if (StateZeroSize && !StateNonZeroSize) {
1415 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1416 C.addTransition(StateZeroSize);
1417 return;
1418 }
1419
1420 // Otherwise, go ahead and figure out the last element we'll touch.
1421 // We don't record the non-zero assumption here because we can't
1422 // be sure. We won't warn on a possible zero.
Jordy Rose8912aae2011-06-20 21:55:40 +00001423 NonLoc one = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
1424 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1425 one, sizeTy);
1426 boundWarning = "Size argument is greater than the length of the "
1427 "destination buffer";
1428 }
1429 }
Jordy Rose5e5f1502011-06-20 03:49:16 +00001430
Jordy Rosed5af0e12011-06-15 05:52:56 +00001431 // If we couldn't pin down the copy length, at least bound it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001432 // FIXME: We should actually run this code path for append as well, but
1433 // right now it creates problems with constraints (since we can end up
1434 // trying to pass constraints from symbol to symbol).
1435 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001436 // Try to get a "hypothetical" string length symbol, which we can later
1437 // set as a real value if that turns out to be the case.
1438 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1439 assert(!amountCopied.isUndef());
1440
1441 if (NonLoc *amountCopiedNL = dyn_cast<NonLoc>(&amountCopied)) {
1442 if (lenValNL) {
1443 // amountCopied <= lenVal
1444 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1445 *amountCopiedNL,
1446 *lenValNL,
1447 cmpTy);
1448 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanBound),
1449 true);
1450 if (!state)
1451 return;
1452 }
1453
1454 if (strLengthNL) {
1455 // amountCopied <= strlen(source)
1456 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1457 *amountCopiedNL,
1458 *strLengthNL,
1459 cmpTy);
1460 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanSrc),
1461 true);
1462 if (!state)
1463 return;
1464 }
1465 }
1466 }
1467
1468 } else {
1469 // The function isn't bounded. The amount copied should match the length
1470 // of the source buffer.
1471 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001472 }
1473
Jordy Rosed5af0e12011-06-15 05:52:56 +00001474 assert(state);
1475
1476 // This represents the number of characters copied into the destination
1477 // buffer. (It may not actually be the strlen if the destination buffer
1478 // is not terminated.)
1479 SVal finalStrLength = UnknownVal();
1480
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001481 // If this is an appending function (strcat, strncat...) then set the
1482 // string length to strlen(src) + strlen(dst) since the buffer will
1483 // ultimately contain both.
1484 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001485 // Get the string length of the destination. If the destination is memory
1486 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001487 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1488 if (dstStrLength.isUndef())
1489 return;
1490
Jordy Rosed5af0e12011-06-15 05:52:56 +00001491 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&amountCopied);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001492 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1493
Jordy Rosed5af0e12011-06-15 05:52:56 +00001494 // If we know both string lengths, we might know the final string length.
1495 if (srcStrLengthNL && dstStrLengthNL) {
1496 // Make sure the two lengths together don't overflow a size_t.
1497 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1498 if (!state)
1499 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001500
Jordy Rosed5af0e12011-06-15 05:52:56 +00001501 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1502 *dstStrLengthNL, sizeTy);
1503 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001504
Jordy Rosed5af0e12011-06-15 05:52:56 +00001505 // If we couldn't get a single value for the final string length,
1506 // we can at least bound it by the individual lengths.
1507 if (finalStrLength.isUnknown()) {
1508 // Try to get a "hypothetical" string length symbol, which we can later
1509 // set as a real value if that turns out to be the case.
1510 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1511 assert(!finalStrLength.isUndef());
1512
1513 if (NonLoc *finalStrLengthNL = dyn_cast<NonLoc>(&finalStrLength)) {
1514 if (srcStrLengthNL) {
1515 // finalStrLength >= srcStrLength
1516 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1517 *finalStrLengthNL,
1518 *srcStrLengthNL,
1519 cmpTy);
1520 state = state->assume(cast<DefinedOrUnknownSVal>(sourceInResult),
1521 true);
1522 if (!state)
1523 return;
1524 }
1525
1526 if (dstStrLengthNL) {
1527 // finalStrLength >= dstStrLength
1528 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1529 *finalStrLengthNL,
1530 *dstStrLengthNL,
1531 cmpTy);
1532 state = state->assume(cast<DefinedOrUnknownSVal>(destInResult),
1533 true);
1534 if (!state)
1535 return;
1536 }
1537 }
1538 }
1539
1540 } else {
1541 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1542 // the final string length will match the input string length.
1543 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001544 }
1545
Jordy Rosed5af0e12011-06-15 05:52:56 +00001546 // The final result of the function will either be a pointer past the last
1547 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001548 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001549
Jordy Rosed5af0e12011-06-15 05:52:56 +00001550 assert(state);
1551
Jordy Rosee64f3112010-08-16 07:51:42 +00001552 // If the destination is a MemRegion, try to check for a buffer overflow and
1553 // record the new string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001554 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001555 QualType ptrTy = Dst->getType();
1556
1557 // If we have an exact value on a bounded copy, use that to check for
1558 // overflows, rather than our estimate about how much is actually copied.
1559 if (boundWarning) {
1560 if (NonLoc *maxLastNL = dyn_cast<NonLoc>(&maxLastElementIndex)) {
1561 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1562 *maxLastNL, ptrTy);
1563 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1564 boundWarning);
1565 if (!state)
1566 return;
1567 }
1568 }
1569
1570 // Then, if the final length is known...
Jordy Rosed5af0e12011-06-15 05:52:56 +00001571 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&finalStrLength)) {
1572 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Rose8912aae2011-06-20 21:55:40 +00001573 *knownStrLength, ptrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +00001574
Jordy Rose8912aae2011-06-20 21:55:40 +00001575 // ...and we haven't checked the bound, we'll check the actual copy.
1576 if (!boundWarning) {
1577 const char * const warningMsg =
1578 "String copy function overflows destination buffer";
1579 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1580 if (!state)
1581 return;
1582 }
Jordy Rosee64f3112010-08-16 07:51:42 +00001583
1584 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001585 if (returnEnd)
1586 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001587 }
1588
1589 // Invalidate the destination. This must happen before we set the C string
1590 // length because invalidation will clear the length.
1591 // FIXME: Even if we can't perfectly model the copy, we should see if we
1592 // can use LazyCompoundVals to copy the source values into the destination.
1593 // This would probably remove any existing bindings past the end of the
1594 // string, but that's still an improvement over blank invalidation.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001595 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001596
Jordy Rose5e5f1502011-06-20 03:49:16 +00001597 // Set the C string length of the destination, if we know it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001598 if (isBounded && !isAppending) {
1599 // strncpy is annoying in that it doesn't guarantee to null-terminate
1600 // the result string. If the original string didn't fit entirely inside
1601 // the bound (including the null-terminator), we don't know how long the
1602 // result is.
1603 if (amountCopied != strLength)
1604 finalStrLength = UnknownVal();
1605 }
1606 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001607 }
1608
Jordy Rosed5af0e12011-06-15 05:52:56 +00001609 assert(state);
1610
Jordy Rosee64f3112010-08-16 07:51:42 +00001611 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1612 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001613 if (returnEnd && Result.isUnknown()) {
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001614 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3b1df8b2012-08-22 06:26:06 +00001615 Result = svalBuilder.conjureSymbolVal(0, CE, LCtx, Count);
Jordy Rosee64f3112010-08-16 07:51:42 +00001616 }
1617
1618 // Set the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001619 state = state->BindExpr(CE, LCtx, Result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001620 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +00001621}
1622
Lenny Maiorani318dd922011-04-12 17:08:43 +00001623void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001624 if (CE->getNumArgs() < 2)
1625 return;
1626
Jordy Roseadc42d42011-06-16 07:13:34 +00001627 //int strcmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001628 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001629}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001630
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001631void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001632 if (CE->getNumArgs() < 3)
1633 return;
1634
Jordy Roseadc42d42011-06-16 07:13:34 +00001635 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001636 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1637}
1638
1639void CStringChecker::evalStrcasecmp(CheckerContext &C,
1640 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001641 if (CE->getNumArgs() < 2)
1642 return;
1643
Jordy Roseadc42d42011-06-16 07:13:34 +00001644 //int strcasecmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001645 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001646}
1647
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001648void CStringChecker::evalStrncasecmp(CheckerContext &C,
1649 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001650 if (CE->getNumArgs() < 3)
1651 return;
1652
Jordy Roseadc42d42011-06-16 07:13:34 +00001653 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001654 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1655}
1656
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001657void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001658 bool isBounded, bool ignoreCase) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001659 CurrentFunctionDescription = "string comparison function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001660 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001661 const LocationContext *LCtx = C.getLocationContext();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001662
1663 // Check that the first string is non-null
1664 const Expr *s1 = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001665 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001666 state = checkNonNull(C, state, s1, s1Val);
1667 if (!state)
1668 return;
1669
1670 // Check that the second string is non-null.
1671 const Expr *s2 = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001672 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001673 state = checkNonNull(C, state, s2, s2Val);
1674 if (!state)
1675 return;
1676
1677 // Get the string length of the first string or give up.
1678 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1679 if (s1Length.isUndef())
1680 return;
1681
1682 // Get the string length of the second string or give up.
1683 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1684 if (s2Length.isUndef())
1685 return;
1686
Jordy Roseadc42d42011-06-16 07:13:34 +00001687 // If we know the two buffers are the same, we know the result is 0.
1688 // First, get the two buffers' addresses. Another checker will have already
1689 // made sure they're not undefined.
1690 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(s1Val);
1691 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(s2Val);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001692
Jordy Roseadc42d42011-06-16 07:13:34 +00001693 // See if they are the same.
Lenny Maiorani318dd922011-04-12 17:08:43 +00001694 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseadc42d42011-06-16 07:13:34 +00001695 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001696 ProgramStateRef StSameBuf, StNotSameBuf;
Jordy Roseadc42d42011-06-16 07:13:34 +00001697 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001698
Jordy Roseadc42d42011-06-16 07:13:34 +00001699 // If the two arguments might be the same buffer, we know the result is 0,
1700 // and we only need to check one size.
1701 if (StSameBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001702 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1703 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001704 C.addTransition(StSameBuf);
Jordy Roseadc42d42011-06-16 07:13:34 +00001705
1706 // If the two arguments are GUARANTEED to be the same, we're done!
1707 if (!StNotSameBuf)
1708 return;
1709 }
1710
1711 assert(StNotSameBuf);
1712 state = StNotSameBuf;
1713
1714 // At this point we can go about comparing the two buffers.
1715 // For now, we only do this if they're both known string literals.
1716
1717 // Attempt to extract string literals from both expressions.
1718 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1719 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1720 bool canComputeResult = false;
1721
1722 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001723 StringRef s1StrRef = s1StrLiteral->getString();
1724 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Roseadc42d42011-06-16 07:13:34 +00001725
1726 if (isBounded) {
1727 // Get the max number of characters to compare.
1728 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001729 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Roseadc42d42011-06-16 07:13:34 +00001730
1731 // If the length is known, we can get the right substrings.
1732 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1733 // Create substrings of each to compare the prefix.
1734 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1735 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1736 canComputeResult = true;
1737 }
1738 } else {
1739 // This is a normal, unbounded strcmp.
1740 canComputeResult = true;
1741 }
1742
1743 if (canComputeResult) {
1744 // Real strcmp stops at null characters.
1745 size_t s1Term = s1StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001746 if (s1Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001747 s1StrRef = s1StrRef.substr(0, s1Term);
1748
1749 size_t s2Term = s2StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001750 if (s2Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001751 s2StrRef = s2StrRef.substr(0, s2Term);
1752
1753 // Use StringRef's comparison methods to compute the actual result.
1754 int result;
1755
1756 if (ignoreCase) {
1757 // Compare string 1 to string 2 the same way strcasecmp() does.
1758 result = s1StrRef.compare_lower(s2StrRef);
1759 } else {
1760 // Compare string 1 to string 2 the same way strcmp() does.
1761 result = s1StrRef.compare(s2StrRef);
1762 }
1763
1764 // Build the SVal of the comparison and bind the return value.
1765 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001766 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001767 }
1768 }
1769
1770 if (!canComputeResult) {
1771 // Conjure a symbolic value. It's the best we can do.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001772 unsigned Count = C.getCurrentBlockCount();
Ted Kremenek3b1df8b2012-08-22 06:26:06 +00001773 SVal resultVal = svalBuilder.conjureSymbolVal(0, CE, LCtx, Count);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001774 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001775 }
1776
1777 // Record this as a possible path.
Anna Zaks0bd6b112011-10-26 21:06:34 +00001778 C.addTransition(state);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001779}
1780
Jordy Rosed325ffb2010-07-08 23:57:29 +00001781//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001782// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001783//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001784
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001785bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks998e2752012-02-17 22:35:26 +00001786 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1787
1788 if (!FDecl)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001789 return false;
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001790
Anna Zaks998e2752012-02-17 22:35:26 +00001791 FnCheck evalFunction = 0;
1792 if (C.isCLibraryFunction(FDecl, "memcpy"))
1793 evalFunction = &CStringChecker::evalMemcpy;
1794 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1795 evalFunction = &CStringChecker::evalMempcpy;
1796 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1797 evalFunction = &CStringChecker::evalMemcmp;
1798 else if (C.isCLibraryFunction(FDecl, "memmove"))
1799 evalFunction = &CStringChecker::evalMemmove;
1800 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1801 evalFunction = &CStringChecker::evalStrcpy;
1802 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1803 evalFunction = &CStringChecker::evalStrncpy;
1804 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1805 evalFunction = &CStringChecker::evalStpcpy;
1806 else if (C.isCLibraryFunction(FDecl, "strcat"))
1807 evalFunction = &CStringChecker::evalStrcat;
1808 else if (C.isCLibraryFunction(FDecl, "strncat"))
1809 evalFunction = &CStringChecker::evalStrncat;
1810 else if (C.isCLibraryFunction(FDecl, "strlen"))
1811 evalFunction = &CStringChecker::evalstrLength;
1812 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1813 evalFunction = &CStringChecker::evalstrnLength;
1814 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1815 evalFunction = &CStringChecker::evalStrcmp;
1816 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1817 evalFunction = &CStringChecker::evalStrncmp;
1818 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1819 evalFunction = &CStringChecker::evalStrcasecmp;
1820 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1821 evalFunction = &CStringChecker::evalStrncasecmp;
1822 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1823 evalFunction = &CStringChecker::evalBcopy;
1824 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1825 evalFunction = &CStringChecker::evalMemcmp;
1826
Jordy Rosed325ffb2010-07-08 23:57:29 +00001827 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001828 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001829 return false;
1830
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001831 // Make sure each function sets its own description.
1832 // (But don't bother in a release build.)
1833 assert(!(CurrentFunctionDescription = NULL));
1834
Jordy Rosed325ffb2010-07-08 23:57:29 +00001835 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001836 (this->*evalFunction)(C, CE);
Anna Zaks57300762012-02-07 00:56:14 +00001837
1838 // If the evaluate call resulted in no change, chain to the next eval call
1839 // handler.
1840 // Note, the custom CString evaluation calls assume that basic safety
1841 // properties are held. However, if the user chooses to turn off some of these
1842 // checks, we ignore the issues and leave the call evaluation to a generic
1843 // handler.
1844 if (!C.isDifferent())
1845 return false;
1846
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001847 return true;
1848}
Jordy Rosea5261542010-08-14 21:02:52 +00001849
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001850void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001851 // Record string length for char a[] = "abc";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001852 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001853
1854 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1855 I != E; ++I) {
1856 const VarDecl *D = dyn_cast<VarDecl>(*I);
1857 if (!D)
1858 continue;
1859
1860 // FIXME: Handle array fields of structs.
1861 if (!D->getType()->isArrayType())
1862 continue;
1863
1864 const Expr *Init = D->getInit();
1865 if (!Init)
1866 continue;
1867 if (!isa<StringLiteral>(Init))
1868 continue;
1869
Anna Zaks39ac1872011-10-26 21:06:44 +00001870 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001871 const MemRegion *MR = VarLoc.getAsRegion();
1872 if (!MR)
1873 continue;
1874
Ted Kremenek5eca4822012-01-06 22:09:28 +00001875 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001876 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001877 DefinedOrUnknownSVal strLength
1878 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rosea5261542010-08-14 21:02:52 +00001879
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001880 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001881 }
1882
Anna Zaks0bd6b112011-10-26 21:06:34 +00001883 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001884}
1885
Ted Kremenek8bef8232012-01-26 21:29:00 +00001886bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001887 CStringLength::EntryMap Entries = state->get<CStringLength>();
1888 return !Entries.isEmpty();
1889}
1890
Ted Kremenek8bef8232012-01-26 21:29:00 +00001891ProgramStateRef
1892CStringChecker::checkRegionChanges(ProgramStateRef state,
Ted Kremenek35bdbf42011-05-02 19:42:42 +00001893 const StoreManager::InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +00001894 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001895 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001896 const CallEvent *Call) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001897 CStringLength::EntryMap Entries = state->get<CStringLength>();
1898 if (Entries.isEmpty())
1899 return state;
1900
1901 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1902 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1903
1904 // First build sets for the changed regions and their super-regions.
Jordy Rose537716a2011-08-27 22:51:26 +00001905 for (ArrayRef<const MemRegion *>::iterator
1906 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1907 const MemRegion *MR = *I;
Jordy Rosea5261542010-08-14 21:02:52 +00001908 Invalidated.insert(MR);
1909
1910 SuperRegions.insert(MR);
1911 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1912 MR = SR->getSuperRegion();
1913 SuperRegions.insert(MR);
1914 }
1915 }
1916
1917 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1918
1919 // Then loop over the entries in the current state.
1920 for (CStringLength::EntryMap::iterator I = Entries.begin(),
1921 E = Entries.end(); I != E; ++I) {
1922 const MemRegion *MR = I.getKey();
1923
1924 // Is this entry for a super-region of a changed region?
1925 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001926 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001927 continue;
1928 }
1929
1930 // Is this entry for a sub-region of a changed region?
1931 const MemRegion *Super = MR;
1932 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1933 Super = SR->getSuperRegion();
1934 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001935 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001936 break;
1937 }
1938 }
1939 }
1940
1941 return state->set<CStringLength>(Entries);
1942}
1943
Ted Kremenek8bef8232012-01-26 21:29:00 +00001944void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001945 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001946 // Mark all symbols in our string length map as valid.
1947 CStringLength::EntryMap Entries = state->get<CStringLength>();
1948
1949 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1950 I != E; ++I) {
1951 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001952
Anna Zaks1d1d5152011-12-06 23:12:33 +00001953 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
1954 se = Len.symbol_end(); si != se; ++si)
Jordy Rosed5af0e12011-06-15 05:52:56 +00001955 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00001956 }
1957}
1958
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001959void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1960 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001961 if (!SR.hasDeadSymbols())
1962 return;
1963
Ted Kremenek8bef8232012-01-26 21:29:00 +00001964 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001965 CStringLength::EntryMap Entries = state->get<CStringLength>();
1966 if (Entries.isEmpty())
1967 return;
1968
1969 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1970 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1971 I != E; ++I) {
1972 SVal Len = I.getData();
1973 if (SymbolRef Sym = Len.getAsSymbol()) {
1974 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00001975 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00001976 }
1977 }
1978
1979 state = state->set<CStringLength>(Entries);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001980 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001981}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001982
Anna Zaks57300762012-02-07 00:56:14 +00001983#define REGISTER_CHECKER(name) \
1984void ento::register##name(CheckerManager &mgr) {\
1985 static CStringChecker *TheChecker = 0; \
1986 if (TheChecker == 0) \
1987 TheChecker = mgr.registerChecker<CStringChecker>(); \
1988 TheChecker->Filter.Check##name = true; \
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001989}
Anna Zaks57300762012-02-07 00:56:14 +00001990
1991REGISTER_CHECKER(CStringNullArg)
1992REGISTER_CHECKER(CStringOutOfBounds)
1993REGISTER_CHECKER(CStringBufferOverlap)
1994REGISTER_CHECKER(CStringNotNullTerm)
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001995
1996void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
1997 registerCStringNullArg(Mgr);
1998}