blob: eae9ddfc05b9a2af356eacb1c12049921e16816f [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
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000191} //end anonymous namespace
192
Jordan Rose166d5022012-11-02 01:54:06 +0000193REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
Jordy Rosea5261542010-08-14 21:02:52 +0000194
Jordy Rosed325ffb2010-07-08 23:57:29 +0000195//===----------------------------------------------------------------------===//
196// Individual checks and utility methods.
197//===----------------------------------------------------------------------===//
198
Ted Kremenek8bef8232012-01-26 21:29:00 +0000199std::pair<ProgramStateRef , ProgramStateRef >
200CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000201 QualType Ty) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000202 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
203 if (!val)
Ted Kremenek8bef8232012-01-26 21:29:00 +0000204 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000205
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000206 SValBuilder &svalBuilder = C.getSValBuilder();
207 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
208 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000209}
Jordy Rosea6b808c2010-07-07 07:48:06 +0000210
Ted Kremenek8bef8232012-01-26 21:29:00 +0000211ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
212 ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000213 const Expr *S, SVal l) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000214 // If a previous check has failed, propagate the failure.
215 if (!state)
216 return NULL;
217
Ted Kremenek8bef8232012-01-26 21:29:00 +0000218 ProgramStateRef stateNull, stateNonNull;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000219 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed325ffb2010-07-08 23:57:29 +0000220
221 if (stateNull && !stateNonNull) {
Anna Zaks57300762012-02-07 00:56:14 +0000222 if (!Filter.CheckCStringNullArg)
223 return NULL;
224
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000225 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000226 if (!N)
227 return NULL;
228
Jordy Rosed325ffb2010-07-08 23:57:29 +0000229 if (!BT_Null)
Anna Zaks57300762012-02-07 00:56:14 +0000230 BT_Null.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000231 "Null pointer argument in call to byte string function"));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000232
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000233 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000234 llvm::raw_svector_ostream os(buf);
235 assert(CurrentFunctionDescription);
236 os << "Null pointer argument in call to " << CurrentFunctionDescription;
237
Jordy Rosea6b808c2010-07-07 07:48:06 +0000238 // Generate a report for this bug.
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000239 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Anna Zakse172e8b2011-08-17 23:00:25 +0000240 BugReport *report = new BugReport(*BT, os.str(), N);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000241
242 report->addRange(S->getSourceRange());
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000243 bugreporter::trackNullOrUndefValue(N, S, *report);
Jordan Rose785950e2012-11-02 01:53:40 +0000244 C.emitReport(report);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000245 return NULL;
246 }
247
248 // From here on, assume that the value is non-null.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000249 assert(stateNonNull);
250 return stateNonNull;
Jordy Rosea6b808c2010-07-07 07:48:06 +0000251}
252
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000253// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek8bef8232012-01-26 21:29:00 +0000254ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
255 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000256 const Expr *S, SVal l,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000257 const char *warningMsg) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000258 // If a previous check has failed, propagate the failure.
259 if (!state)
260 return NULL;
261
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000262 // Check for out of bound array element access.
263 const MemRegion *R = l.getAsRegion();
264 if (!R)
265 return state;
266
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000267 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
268 if (!ER)
269 return state;
270
Zhongxing Xu018220c2010-08-11 06:10:55 +0000271 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000272 "CheckLocation should only be called with char* ElementRegions");
273
274 // Get the size of the array.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000275 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
276 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000277 SVal Extent =
278 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000279 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
280
281 // Get the index of the accessed element.
Gabor Greif89b06582010-09-09 10:51:37 +0000282 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000283
Ted Kremenek8bef8232012-01-26 21:29:00 +0000284 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
285 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000286 if (StOutBound && !StInBound) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000287 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000288 if (!N)
289 return NULL;
290
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000291 if (!BT_Bounds) {
292 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
293 "Byte string function accesses out-of-bound array element"));
294 }
295 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
296
297 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000298 BugReport *report;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000299 if (warningMsg) {
Anna Zakse172e8b2011-08-17 23:00:25 +0000300 report = new BugReport(*BT, warningMsg, N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000301 } else {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000302 assert(CurrentFunctionDescription);
303 assert(CurrentFunctionDescription[0] != '\0');
304
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000305 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000306 llvm::raw_svector_ostream os(buf);
307 os << (char)toupper(CurrentFunctionDescription[0])
308 << &CurrentFunctionDescription[1]
309 << " accesses out-of-bound array element";
Anna Zakse172e8b2011-08-17 23:00:25 +0000310 report = new BugReport(*BT, os.str(), N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000311 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000312
313 // FIXME: It would be nice to eventually make this diagnostic more clear,
314 // e.g., by referencing the original declaration or by saying *why* this
315 // reference is outside the range.
316
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000317 report->addRange(S->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000318 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000319 return NULL;
320 }
321
322 // Array bound check succeeded. From this point forward the array bound
323 // should always succeed.
324 return StInBound;
325}
326
Ted Kremenek8bef8232012-01-26 21:29:00 +0000327ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
328 ProgramStateRef state,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000329 const Expr *Size,
330 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000331 const Expr *SecondBuf,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000332 const char *firstMessage,
Jordy Rose5e5f1502011-06-20 03:49:16 +0000333 const char *secondMessage,
334 bool WarnAboutSize) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000335 // If a previous check has failed, propagate the failure.
336 if (!state)
337 return NULL;
338
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000339 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000340 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000341 const LocationContext *LCtx = C.getLocationContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000342
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000343 QualType sizeTy = Size->getType();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000344 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
345
Jordy Rosea6b808c2010-07-07 07:48:06 +0000346 // Check that the first buffer is non-null.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000347 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000348 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000349 if (!state)
350 return NULL;
351
Anna Zaks57300762012-02-07 00:56:14 +0000352 // If out-of-bounds checking is turned off, skip the rest.
353 if (!Filter.CheckCStringOutOfBounds)
354 return state;
355
Jordy Rosed325ffb2010-07-08 23:57:29 +0000356 // Get the access length and make sure it is known.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000357 // FIXME: This assumes the caller has already checked that the access length
358 // is positive. And that it's unsigned.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000359 SVal LengthVal = state->getSVal(Size, LCtx);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000360 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
361 if (!Length)
362 return state;
363
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000364 // Compute the offset of the last element to be accessed: size-1.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000365 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
366 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
367 *Length, One, sizeTy));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000368
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000369 // Check that the first buffer is sufficiently long.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000370 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000371 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000372 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
373
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000374 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
375 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000376 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000377
Jordy Roseb6a40262010-08-05 23:11:30 +0000378 // If the buffer isn't large enough, abort.
379 if (!state)
380 return NULL;
381 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000382
383 // If there's a second buffer, check it as well.
384 if (SecondBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000385 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000386 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000387 if (!state)
388 return NULL;
389
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000390 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000391 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000392 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
393
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000394 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
395 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000396 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseb6a40262010-08-05 23:11:30 +0000397 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000398 }
399
400 // Large enough or not, return this state!
401 return state;
402}
403
Ted Kremenek8bef8232012-01-26 21:29:00 +0000404ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
405 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000406 const Expr *Size,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000407 const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000408 const Expr *Second) const {
Anna Zaks57300762012-02-07 00:56:14 +0000409 if (!Filter.CheckCStringBufferOverlap)
410 return state;
411
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000412 // Do a simple check for overlap: if the two arguments are from the same
413 // buffer, see if the end of the first is greater than the start of the second
414 // or vice versa.
415
Jordy Rosed325ffb2010-07-08 23:57:29 +0000416 // If a previous check has failed, propagate the failure.
417 if (!state)
418 return NULL;
419
Ted Kremenek8bef8232012-01-26 21:29:00 +0000420 ProgramStateRef stateTrue, stateFalse;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000421
422 // Get the buffer values and make sure they're known locations.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000423 const LocationContext *LCtx = C.getLocationContext();
424 SVal firstVal = state->getSVal(First, LCtx);
425 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000426
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000427 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
428 if (!firstLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000429 return state;
430
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000431 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
432 if (!secondLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000433 return state;
434
435 // Are the two values the same?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000436 SValBuilder &svalBuilder = C.getSValBuilder();
437 llvm::tie(stateTrue, stateFalse) =
438 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000439
440 if (stateTrue && !stateFalse) {
441 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000442 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000443 return NULL;
444 }
445
Ted Kremenek28f47b92010-12-01 22:16:56 +0000446 // assume the two expressions are not equal.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000447 assert(stateFalse);
448 state = stateFalse;
449
450 // Which value comes first?
Jordy Roseee2fde12011-06-16 05:56:50 +0000451 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000452 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
453 *firstLoc, *secondLoc, cmpTy);
454 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
455 if (!reverseTest)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000456 return state;
457
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000458 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000459 if (stateTrue) {
460 if (stateFalse) {
461 // If we don't know which one comes first, we can't perform this test.
462 return state;
463 } else {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000464 // Switch the values so that firstVal is before secondVal.
465 Loc *tmpLoc = firstLoc;
466 firstLoc = secondLoc;
467 secondLoc = tmpLoc;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000468
469 // Switch the Exprs as well, so that they still correspond.
470 const Expr *tmpExpr = First;
471 First = Second;
472 Second = tmpExpr;
473 }
474 }
475
476 // Get the length, and make sure it too is known.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000477 SVal LengthVal = state->getSVal(Size, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000478 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
479 if (!Length)
480 return state;
481
482 // Convert the first buffer's start address to char*.
483 // Bail out if the cast fails.
Jordy Roseee2fde12011-06-16 05:56:50 +0000484 ASTContext &Ctx = svalBuilder.getContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000485 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose1e022412011-06-16 05:51:02 +0000486 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
487 First->getType());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000488 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
489 if (!FirstStartLoc)
490 return state;
491
492 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000493 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000494 *FirstStartLoc, *Length, CharPtrTy);
495 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
496 if (!FirstEndLoc)
497 return state;
498
499 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000500 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
501 *FirstEndLoc, *secondLoc, cmpTy);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000502 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
503 if (!OverlapTest)
504 return state;
505
Ted Kremenek28f47b92010-12-01 22:16:56 +0000506 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000507
508 if (stateTrue && !stateFalse) {
509 // Overlap!
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000510 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000511 return NULL;
512 }
513
Ted Kremenek28f47b92010-12-01 22:16:56 +0000514 // assume the two expressions don't overlap.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000515 assert(stateFalse);
516 return stateFalse;
517}
518
Ted Kremenek8bef8232012-01-26 21:29:00 +0000519void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000520 const Stmt *First, const Stmt *Second) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000521 ExplodedNode *N = C.generateSink(state);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000522 if (!N)
523 return;
524
525 if (!BT_Overlap)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000526 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000527
528 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000529 BugReport *report =
530 new BugReport(*BT_Overlap,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000531 "Arguments must not be overlapping buffers", N);
532 report->addRange(First->getSourceRange());
533 report->addRange(Second->getSourceRange());
534
Jordan Rose785950e2012-11-02 01:53:40 +0000535 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000536}
537
Ted Kremenek8bef8232012-01-26 21:29:00 +0000538ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
539 ProgramStateRef state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000540 NonLoc left,
541 NonLoc right) const {
Anna Zaks57300762012-02-07 00:56:14 +0000542 // If out-of-bounds checking is turned off, skip the rest.
543 if (!Filter.CheckCStringOutOfBounds)
544 return state;
545
Jordy Rosed5af0e12011-06-15 05:52:56 +0000546 // If a previous check has failed, propagate the failure.
547 if (!state)
548 return NULL;
549
550 SValBuilder &svalBuilder = C.getSValBuilder();
551 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
552
553 QualType sizeTy = svalBuilder.getContext().getSizeType();
554 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
555 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
556
Anna Zakse3d250e2011-12-11 18:43:40 +0000557 SVal maxMinusRight;
558 if (isa<nonloc::ConcreteInt>(right)) {
559 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
560 sizeTy);
561 } else {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000562 // Try switching the operands. (The order of these two assignments is
563 // important!)
564 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
565 sizeTy);
566 left = right;
567 }
568
569 if (NonLoc *maxMinusRightNL = dyn_cast<NonLoc>(&maxMinusRight)) {
570 QualType cmpTy = svalBuilder.getConditionType();
571 // If left > max - right, we have an overflow.
572 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
573 *maxMinusRightNL, cmpTy);
574
Ted Kremenek8bef8232012-01-26 21:29:00 +0000575 ProgramStateRef stateOverflow, stateOkay;
Jordy Rosed5af0e12011-06-15 05:52:56 +0000576 llvm::tie(stateOverflow, stateOkay) =
577 state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
578
579 if (stateOverflow && !stateOkay) {
580 // We have an overflow. Emit a bug report.
581 ExplodedNode *N = C.generateSink(stateOverflow);
582 if (!N)
583 return NULL;
584
585 if (!BT_AdditionOverflow)
586 BT_AdditionOverflow.reset(new BuiltinBug("API",
587 "Sum of expressions causes overflow"));
588
Jordy Rosed5af0e12011-06-15 05:52:56 +0000589 // This isn't a great error message, but this should never occur in real
590 // code anyway -- you'd have to create a buffer longer than a size_t can
591 // represent, which is sort of a contradiction.
Jordy Rose8cc24912011-06-20 03:51:53 +0000592 const char *warning =
593 "This expression will create a string whose length is too big to "
594 "be represented as a size_t";
Jordy Rosed5af0e12011-06-15 05:52:56 +0000595
596 // Generate a report for this bug.
Jordy Rose8cc24912011-06-20 03:51:53 +0000597 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
Jordan Rose785950e2012-11-02 01:53:40 +0000598 C.emitReport(report);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000599
600 return NULL;
601 }
602
603 // From now on, assume an overflow didn't occur.
604 assert(stateOkay);
605 state = stateOkay;
606 }
607
608 return state;
609}
610
Ted Kremenek8bef8232012-01-26 21:29:00 +0000611ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000612 const MemRegion *MR,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000613 SVal strLength) {
614 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rosee64f3112010-08-16 07:51:42 +0000615
616 MR = MR->StripCasts();
617
618 switch (MR->getKind()) {
619 case MemRegion::StringRegionKind:
620 // FIXME: This can happen if we strcpy() into a string region. This is
621 // undefined [C99 6.4.5p6], but we should still warn about it.
622 return state;
623
624 case MemRegion::SymbolicRegionKind:
625 case MemRegion::AllocaRegionKind:
626 case MemRegion::VarRegionKind:
627 case MemRegion::FieldRegionKind:
628 case MemRegion::ObjCIvarRegionKind:
Jordy Rose210c05b2011-06-15 05:14:03 +0000629 // These are the types we can currently track string lengths for.
630 break;
Jordy Rosee64f3112010-08-16 07:51:42 +0000631
632 case MemRegion::ElementRegionKind:
633 // FIXME: Handle element regions by upper-bounding the parent region's
634 // string length.
635 return state;
636
637 default:
638 // Other regions (mostly non-data) can't have a reliable C string length.
639 // For now, just ignore the change.
640 // FIXME: These are rare but not impossible. We should output some kind of
641 // warning for things like strcpy((char[]){'a', 0}, "b");
642 return state;
643 }
Jordy Rose210c05b2011-06-15 05:14:03 +0000644
645 if (strLength.isUnknown())
646 return state->remove<CStringLength>(MR);
647
648 return state->set<CStringLength>(MR, strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +0000649}
650
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000651SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000652 ProgramStateRef &state,
Jordy Rosea5261542010-08-14 21:02:52 +0000653 const Expr *Ex,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000654 const MemRegion *MR,
655 bool hypothetical) {
656 if (!hypothetical) {
657 // If there's a recorded length, go ahead and return it.
658 const SVal *Recorded = state->get<CStringLength>(MR);
659 if (Recorded)
660 return *Recorded;
661 }
Jordy Rosea5261542010-08-14 21:02:52 +0000662
663 // Otherwise, get a new symbol and update the state.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000664 SValBuilder &svalBuilder = C.getSValBuilder();
665 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000666 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
Ted Kremenek66c486f2012-08-22 06:26:15 +0000667 MR, Ex, sizeTy,
668 C.blockCount());
Jordy Rosed5af0e12011-06-15 05:52:56 +0000669
670 if (!hypothetical)
671 state = state->set<CStringLength>(MR, strLength);
672
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000673 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000674}
675
Ted Kremenek8bef8232012-01-26 21:29:00 +0000676SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000677 const Expr *Ex, SVal Buf,
678 bool hypothetical) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000679 const MemRegion *MR = Buf.getAsRegion();
680 if (!MR) {
681 // If we can't get a region, see if it's something we /know/ isn't a
682 // C string. In the context of locations, the only time we can issue such
683 // a warning is for labels.
684 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
Anna Zaks57300762012-02-07 00:56:14 +0000685 if (!Filter.CheckCStringNotNullTerm)
686 return UndefinedVal();
687
Anna Zaks0bd6b112011-10-26 21:06:34 +0000688 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000689 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000690 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000691 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000692
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000693 SmallString<120> buf;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000694 llvm::raw_svector_ostream os(buf);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000695 assert(CurrentFunctionDescription);
696 os << "Argument to " << CurrentFunctionDescription
697 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000698 << "', which is not a null-terminated string";
699
700 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000701 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000702 os.str(), N);
703
704 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000705 C.emitReport(report);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000706 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000707 return UndefinedVal();
Anna Zaks57300762012-02-07 00:56:14 +0000708
Jordy Rose19c5dd12010-07-27 01:37:31 +0000709 }
710
Jordy Rosea5261542010-08-14 21:02:52 +0000711 // If it's not a region and not a label, give up.
712 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000713 }
714
Jordy Rosea5261542010-08-14 21:02:52 +0000715 // If we have a region, strip casts from it and see if we can figure out
716 // its length. For anything we can't figure out, just return UnknownVal.
717 MR = MR->StripCasts();
718
719 switch (MR->getKind()) {
720 case MemRegion::StringRegionKind: {
721 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
722 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000723 SValBuilder &svalBuilder = C.getSValBuilder();
724 QualType sizeTy = svalBuilder.getContext().getSizeType();
725 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
726 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000727 }
728 case MemRegion::SymbolicRegionKind:
729 case MemRegion::AllocaRegionKind:
730 case MemRegion::VarRegionKind:
731 case MemRegion::FieldRegionKind:
732 case MemRegion::ObjCIvarRegionKind:
Jordy Rosed5af0e12011-06-15 05:52:56 +0000733 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rosea5261542010-08-14 21:02:52 +0000734 case MemRegion::CompoundLiteralRegionKind:
735 // FIXME: Can we track this? Is it necessary?
736 return UnknownVal();
737 case MemRegion::ElementRegionKind:
738 // FIXME: How can we handle this? It's not good enough to subtract the
739 // offset from the base string length; consider "123\x00567" and &a[5].
740 return UnknownVal();
741 default:
742 // Other regions (mostly non-data) can't have a reliable C string length.
743 // In this case, an error is emitted and UndefinedVal is returned.
744 // The caller should always be prepared to handle this case.
Anna Zaks57300762012-02-07 00:56:14 +0000745 if (!Filter.CheckCStringNotNullTerm)
746 return UndefinedVal();
747
Anna Zaks0bd6b112011-10-26 21:06:34 +0000748 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000749 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000750 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000751 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000752
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000753 SmallString<120> buf;
Jordy Rosea5261542010-08-14 21:02:52 +0000754 llvm::raw_svector_ostream os(buf);
755
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000756 assert(CurrentFunctionDescription);
757 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rosea5261542010-08-14 21:02:52 +0000758
759 if (SummarizeRegion(os, C.getASTContext(), MR))
760 os << ", which is not a null-terminated string";
761 else
762 os << "not a null-terminated string";
763
764 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000765 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rosea5261542010-08-14 21:02:52 +0000766 os.str(), N);
767
768 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000769 C.emitReport(report);
Jordy Rosea5261542010-08-14 21:02:52 +0000770 }
771
772 return UndefinedVal();
773 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000774}
775
Lenny Maiorani318dd922011-04-12 17:08:43 +0000776const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000777 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +0000778
779 // Get the memory region pointed to by the val.
780 const MemRegion *bufRegion = val.getAsRegion();
781 if (!bufRegion)
782 return NULL;
783
784 // Strip casts off the memory region.
785 bufRegion = bufRegion->StripCasts();
786
787 // Cast the memory region to a string region.
788 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
789 if (!strRegion)
790 return NULL;
791
792 // Return the actual string in the string region.
793 return strRegion->getStringLiteral();
794}
795
Ted Kremenek8bef8232012-01-26 21:29:00 +0000796ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
797 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000798 const Expr *E, SVal V) {
799 Loc *L = dyn_cast<Loc>(&V);
800 if (!L)
801 return state;
802
803 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
804 // some assumptions about the value that CFRefCount can't. Even so, it should
805 // probably be refactored.
806 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
807 const MemRegion *R = MR->getRegion()->StripCasts();
808
809 // Are we dealing with an ElementRegion? If so, we should be invalidating
810 // the super-region.
811 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
812 R = ER->getSuperRegion();
813 // FIXME: What about layers of ElementRegions?
814 }
815
816 // Invalidate this region.
Ted Kremenek3133f792012-02-17 23:13:45 +0000817 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
Ted Kremenek66c486f2012-08-22 06:26:15 +0000818 return state->invalidateRegions(R, E, C.blockCount(), LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +0000819 }
820
821 // If we have a non-region value by chance, just remove the binding.
822 // FIXME: is this necessary or correct? This handles the non-Region
823 // cases. Is it ever valid to store to these?
Ted Kremenek56a46b52012-08-22 06:37:46 +0000824 return state->killBinding(*L);
Jordy Rosee64f3112010-08-16 07:51:42 +0000825}
826
Ted Kremenek9c378f72011-08-12 23:37:29 +0000827bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000828 const MemRegion *MR) {
Ted Kremenek96979342011-08-12 20:02:48 +0000829 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000830
Jordy Rose096aef92011-08-12 21:41:07 +0000831 switch (MR->getKind()) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000832 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000833 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000834 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000835 os << "the address of the function '" << *FD << '\'';
Jordy Rose19c5dd12010-07-27 01:37:31 +0000836 else
837 os << "the address of a function";
838 return true;
839 }
840 case MemRegion::BlockTextRegionKind:
841 os << "block text";
842 return true;
843 case MemRegion::BlockDataRegionKind:
844 os << "a block";
845 return true;
846 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000847 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000848 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000849 return true;
850 case MemRegion::VarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000851 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000852 return true;
853 case MemRegion::FieldRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000854 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000855 return true;
856 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000857 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000858 return true;
859 default:
860 return false;
861 }
862}
863
Jordy Rosed325ffb2010-07-08 23:57:29 +0000864//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000865// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000866//===----------------------------------------------------------------------===//
867
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000868void CStringChecker::evalCopyCommon(CheckerContext &C,
869 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000870 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000871 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000872 const Expr *Source, bool Restricted,
873 bool IsMempcpy) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000874 CurrentFunctionDescription = "memory copy function";
875
Jordy Rosed325ffb2010-07-08 23:57:29 +0000876 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000877 const LocationContext *LCtx = C.getLocationContext();
878 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000879 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000880
Ted Kremenek8bef8232012-01-26 21:29:00 +0000881 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose1e022412011-06-16 05:51:02 +0000882 llvm::tie(stateZeroSize, stateNonZeroSize) =
883 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000884
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000885 // Get the value of the Dest.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000886 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000887
888 // If the size is zero, there won't be any actual memory access, so
889 // just bind the return value to the destination buffer and return.
Anna Zaksdd160f32012-05-03 18:21:28 +0000890 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000891 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000892 C.addTransition(stateZeroSize);
Anna Zaksdd160f32012-05-03 18:21:28 +0000893 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000894 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000895
896 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000897 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000898 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000899
900 // Ensure the destination is not null. If it is NULL there will be a
901 // NULL pointer dereference.
902 state = checkNonNull(C, state, Dest, destVal);
903 if (!state)
904 return;
905
906 // Get the value of the Src.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000907 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000908
909 // Ensure the source is not null. If it is NULL there will be a
910 // NULL pointer dereference.
911 state = checkNonNull(C, state, Source, srcVal);
912 if (!state)
913 return;
914
Jordy Rose7182b962011-06-04 01:50:25 +0000915 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000916 const char * const writeWarning =
917 "Memory copy function overflows destination buffer";
Jordy Rosee64f3112010-08-16 07:51:42 +0000918 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000919 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000920 if (Restricted)
921 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000922
Jordy Rose7182b962011-06-04 01:50:25 +0000923 if (!state)
924 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000925
Jordy Rose7182b962011-06-04 01:50:25 +0000926 // If this is mempcpy, get the byte after the last byte copied and
927 // bind the expr.
928 if (IsMempcpy) {
929 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
930 assert(destRegVal && "Destination should be a known MemRegionVal here");
931
932 // Get the length to copy.
933 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
934
935 if (lenValNonLoc) {
936 // Get the byte after the last byte copied.
937 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
938 *destRegVal,
939 *lenValNonLoc,
940 Dest->getType());
941
942 // The byte after the last byte copied is the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000943 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000944 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000945 // If we don't know how much we copied, we can at least
946 // conjure a return value for later.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000947 SVal result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx,
948 C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +0000949 state = state->BindExpr(CE, LCtx, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000950 }
951
Jordy Rose7182b962011-06-04 01:50:25 +0000952 } else {
953 // All other copies return the destination buffer.
954 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000955 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000956 }
Jordy Rose7182b962011-06-04 01:50:25 +0000957
958 // Invalidate the destination.
959 // FIXME: Even if we can't perfectly model the copy, we should see if we
960 // can use LazyCompoundVals to copy the source values into the destination.
961 // This would probably remove any existing bindings past the end of the
962 // copied region, but that's still an improvement over blank invalidation.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000963 state = InvalidateBuffer(C, state, Dest,
964 state->getSVal(Dest, C.getLocationContext()));
Anna Zaks0bd6b112011-10-26 21:06:34 +0000965 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000966 }
967}
968
969
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000970void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000971 if (CE->getNumArgs() < 3)
972 return;
973
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000974 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000975 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000976 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000977 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000978
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000979 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
980}
981
982void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000983 if (CE->getNumArgs() < 3)
984 return;
985
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000986 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
987 // The return value is a pointer to the byte following the last written byte.
988 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000989 ProgramStateRef state = C.getState();
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000990
991 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000992}
993
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000994void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000995 if (CE->getNumArgs() < 3)
996 return;
997
Jordy Rosed325ffb2010-07-08 23:57:29 +0000998 // void *memmove(void *dst, const void *src, size_t n);
999 // The return value is the address of the destination buffer.
1000 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001001 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001002
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001003 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001004}
1005
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001006void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001007 if (CE->getNumArgs() < 3)
1008 return;
1009
Jordy Rosed325ffb2010-07-08 23:57:29 +00001010 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001011 evalCopyCommon(C, CE, C.getState(),
1012 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001013}
1014
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001015void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001016 if (CE->getNumArgs() < 3)
1017 return;
1018
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001019 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001020 CurrentFunctionDescription = "memory comparison function";
1021
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001022 const Expr *Left = CE->getArg(0);
1023 const Expr *Right = CE->getArg(1);
1024 const Expr *Size = CE->getArg(2);
1025
Ted Kremenek8bef8232012-01-26 21:29:00 +00001026 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001027 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001028
Jordy Rosed325ffb2010-07-08 23:57:29 +00001029 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001030 const LocationContext *LCtx = C.getLocationContext();
1031 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001032 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001033
Ted Kremenek8bef8232012-01-26 21:29:00 +00001034 ProgramStateRef stateZeroSize, stateNonZeroSize;
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001035 llvm::tie(stateZeroSize, stateNonZeroSize) =
1036 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001037
Jordy Rosed325ffb2010-07-08 23:57:29 +00001038 // If the size can be zero, the result will be 0 in that case, and we don't
1039 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001040 if (stateZeroSize) {
1041 state = stateZeroSize;
Ted Kremenek5eca4822012-01-06 22:09:28 +00001042 state = state->BindExpr(CE, LCtx,
1043 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001044 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001045 }
1046
Jordy Rosed325ffb2010-07-08 23:57:29 +00001047 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001048 if (stateNonZeroSize) {
1049 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +00001050 // If we know the two buffers are the same, we know the result is 0.
1051 // First, get the two buffers' addresses. Another checker will have already
1052 // made sure they're not undefined.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001053 DefinedOrUnknownSVal LV =
1054 cast<DefinedOrUnknownSVal>(state->getSVal(Left, LCtx));
1055 DefinedOrUnknownSVal RV =
1056 cast<DefinedOrUnknownSVal>(state->getSVal(Right, LCtx));
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001057
Jordy Rosed325ffb2010-07-08 23:57:29 +00001058 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001059 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001060 ProgramStateRef StSameBuf, StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +00001061 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001062
Jordy Rose1e022412011-06-16 05:51:02 +00001063 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +00001064 // and we only need to check one size.
1065 if (StSameBuf) {
1066 state = StSameBuf;
1067 state = CheckBufferAccess(C, state, Size, Left);
1068 if (state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001069 state = StSameBuf->BindExpr(CE, LCtx,
1070 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001071 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001072 }
1073 }
1074
1075 // If the two arguments might be different buffers, we have to check the
1076 // size of both of them.
1077 if (StNotSameBuf) {
1078 state = StNotSameBuf;
1079 state = CheckBufferAccess(C, state, Size, Left, Right);
1080 if (state) {
1081 // The return value is the comparison result, which we don't know.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001082 SVal CmpV = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001083 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001084 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001085 }
1086 }
1087 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001088}
1089
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001090void CStringChecker::evalstrLength(CheckerContext &C,
1091 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001092 if (CE->getNumArgs() < 1)
1093 return;
1094
Jordy Rose19c5dd12010-07-27 01:37:31 +00001095 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001096 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1097}
1098
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001099void CStringChecker::evalstrnLength(CheckerContext &C,
1100 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001101 if (CE->getNumArgs() < 2)
1102 return;
1103
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001104 // size_t strnlen(const char *s, size_t maxlen);
1105 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1106}
1107
1108void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001109 bool IsStrnlen) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001110 CurrentFunctionDescription = "string length function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001111 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001112 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose793bff32011-06-14 01:15:31 +00001113
1114 if (IsStrnlen) {
1115 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001116 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rose793bff32011-06-14 01:15:31 +00001117
Ted Kremenek8bef8232012-01-26 21:29:00 +00001118 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose793bff32011-06-14 01:15:31 +00001119 llvm::tie(stateZeroSize, stateNonZeroSize) =
1120 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1121
1122 // If the size can be zero, the result will be 0 in that case, and we don't
1123 // have to check the string itself.
1124 if (stateZeroSize) {
1125 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001126 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001127 C.addTransition(stateZeroSize);
Jordy Rose793bff32011-06-14 01:15:31 +00001128 }
1129
1130 // If the size is GUARANTEED to be zero, we're done!
1131 if (!stateNonZeroSize)
1132 return;
1133
1134 // Otherwise, record the assumption that the size is nonzero.
1135 state = stateNonZeroSize;
1136 }
1137
1138 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001139 const Expr *Arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001140 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001141
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001142 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001143
Jordy Rosebd32bee2011-06-14 01:26:48 +00001144 if (!state)
1145 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001146
Jordy Rosebd32bee2011-06-14 01:26:48 +00001147 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001148
Jordy Rosebd32bee2011-06-14 01:26:48 +00001149 // If the argument isn't a valid C string, there's no valid state to
1150 // transition to.
1151 if (strLength.isUndef())
1152 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001153
Jordy Rosebd32bee2011-06-14 01:26:48 +00001154 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001155
Jordy Rosebd32bee2011-06-14 01:26:48 +00001156 // If the check is for strnlen() then bind the return value to no more than
1157 // the maxlen value.
1158 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001159 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001160
Jordy Rosebd32bee2011-06-14 01:26:48 +00001161 // It's a little unfortunate to be getting this again,
1162 // but it's not that expensive...
1163 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001164 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001165
Jordy Rosebd32bee2011-06-14 01:26:48 +00001166 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1167 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001168
Jordy Rosebd32bee2011-06-14 01:26:48 +00001169 if (strLengthNL && maxlenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001170 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001171
Jordy Rosebd32bee2011-06-14 01:26:48 +00001172 // Check if the strLength is greater than the maxlen.
1173 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
1174 state->assume(cast<DefinedOrUnknownSVal>
1175 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1176 *strLengthNL,
1177 *maxlenValNL,
1178 cmpTy)));
Jordy Rose793bff32011-06-14 01:15:31 +00001179
Jordy Rosebd32bee2011-06-14 01:26:48 +00001180 if (stateStringTooLong && !stateStringNotTooLong) {
1181 // If the string is longer than maxlen, return maxlen.
1182 result = *maxlenValNL;
1183 } else if (stateStringNotTooLong && !stateStringTooLong) {
1184 // If the string is shorter than maxlen, return its length.
1185 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001186 }
1187 }
1188
Jordy Rosebd32bee2011-06-14 01:26:48 +00001189 if (result.isUnknown()) {
1190 // If we don't have enough information for a comparison, there's
1191 // no guarantee the full string length will actually be returned.
1192 // All we know is the return value is the min of the string length
1193 // and the limit. This is better than nothing.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001194 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001195 NonLoc *resultNL = cast<NonLoc>(&result);
1196
1197 if (strLengthNL) {
1198 state = state->assume(cast<DefinedOrUnknownSVal>
1199 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1200 *resultNL,
1201 *strLengthNL,
1202 cmpTy)), true);
1203 }
1204
1205 if (maxlenValNL) {
1206 state = state->assume(cast<DefinedOrUnknownSVal>
1207 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1208 *resultNL,
1209 *maxlenValNL,
1210 cmpTy)), true);
1211 }
1212 }
1213
1214 } else {
1215 // This is a plain strlen(), not strnlen().
1216 result = cast<DefinedOrUnknownSVal>(strLength);
1217
1218 // If we don't know the length of the string, conjure a return
1219 // value, so it can be used in constraints, at least.
1220 if (result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001221 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001222 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001223 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001224
1225 // Bind the return value.
1226 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek5eca4822012-01-06 22:09:28 +00001227 state = state->BindExpr(CE, LCtx, result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001228 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001229}
1230
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001231void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001232 if (CE->getNumArgs() < 2)
1233 return;
1234
Jordy Rosee64f3112010-08-16 07:51:42 +00001235 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001236 evalStrcpyCommon(C, CE,
1237 /* returnEnd = */ false,
1238 /* isBounded = */ false,
1239 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001240}
1241
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001242void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001243 if (CE->getNumArgs() < 3)
1244 return;
1245
Jordy Rosec1525862011-06-04 00:05:23 +00001246 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001247 evalStrcpyCommon(C, CE,
1248 /* returnEnd = */ false,
1249 /* isBounded = */ true,
1250 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001251}
1252
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001253void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001254 if (CE->getNumArgs() < 2)
1255 return;
1256
Jordy Rosee64f3112010-08-16 07:51:42 +00001257 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001258 evalStrcpyCommon(C, CE,
1259 /* returnEnd = */ true,
1260 /* isBounded = */ false,
1261 /* isAppending = */ false);
1262}
1263
1264void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001265 if (CE->getNumArgs() < 2)
1266 return;
1267
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001268 //char *strcat(char *restrict s1, const char *restrict s2);
1269 evalStrcpyCommon(C, CE,
1270 /* returnEnd = */ false,
1271 /* isBounded = */ false,
1272 /* isAppending = */ true);
1273}
1274
1275void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001276 if (CE->getNumArgs() < 3)
1277 return;
1278
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001279 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1280 evalStrcpyCommon(C, CE,
1281 /* returnEnd = */ false,
1282 /* isBounded = */ true,
1283 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001284}
1285
Ted Kremenek9c149532010-12-01 21:57:22 +00001286void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001287 bool returnEnd, bool isBounded,
1288 bool isAppending) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001289 CurrentFunctionDescription = "string copy function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001290 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001291 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosee64f3112010-08-16 07:51:42 +00001292
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001293 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001294 const Expr *Dst = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001295 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +00001296
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001297 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001298 if (!state)
1299 return;
1300
1301 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001302 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001303 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001304 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001305 if (!state)
1306 return;
1307
1308 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001309 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001310
1311 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001312 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001313 return;
1314
Jordy Rosed5af0e12011-06-15 05:52:56 +00001315 SValBuilder &svalBuilder = C.getSValBuilder();
1316 QualType cmpTy = svalBuilder.getConditionType();
Jordy Rose8912aae2011-06-20 21:55:40 +00001317 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001318
Jordy Rose8912aae2011-06-20 21:55:40 +00001319 // These two values allow checking two kinds of errors:
1320 // - actual overflows caused by a source that doesn't fit in the destination
1321 // - potential overflows caused by a bound that could exceed the destination
Jordy Rosed5af0e12011-06-15 05:52:56 +00001322 SVal amountCopied = UnknownVal();
Jordy Rose8912aae2011-06-20 21:55:40 +00001323 SVal maxLastElementIndex = UnknownVal();
1324 const char *boundWarning = NULL;
Jordy Rosed5af0e12011-06-15 05:52:56 +00001325
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001326 // If the function is strncpy, strncat, etc... it is bounded.
1327 if (isBounded) {
1328 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001329 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001330 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001331
Jordy Rosed5af0e12011-06-15 05:52:56 +00001332 // Protect against misdeclared strncpy().
Jordy Rose8912aae2011-06-20 21:55:40 +00001333 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001334
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001335 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1336 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1337
Jordy Rosed5af0e12011-06-15 05:52:56 +00001338 // If we know both values, we might be able to figure out how much
1339 // we're copying.
1340 if (strLengthNL && lenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001341 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001342
Jordy Rosed5af0e12011-06-15 05:52:56 +00001343 // Check if the max number to copy is less than the length of the src.
Jordy Rose8912aae2011-06-20 21:55:40 +00001344 // If the bound is equal to the source length, strncpy won't null-
1345 // terminate the result!
Jordy Rosed5af0e12011-06-15 05:52:56 +00001346 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) =
1347 state->assume(cast<DefinedOrUnknownSVal>
Jordy Rose8912aae2011-06-20 21:55:40 +00001348 (svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL,
Jordy Rosed5af0e12011-06-15 05:52:56 +00001349 *lenValNL, cmpTy)));
1350
1351 if (stateSourceTooLong && !stateSourceNotTooLong) {
1352 // Max number to copy is less than the length of the src, so the actual
1353 // strLength copied is the max number arg.
1354 state = stateSourceTooLong;
1355 amountCopied = lenVal;
1356
1357 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1358 // The source buffer entirely fits in the bound.
1359 state = stateSourceNotTooLong;
1360 amountCopied = strLength;
1361 }
1362 }
1363
Jordy Rose5e5f1502011-06-20 03:49:16 +00001364 // We still want to know if the bound is known to be too large.
Jordy Rose8912aae2011-06-20 21:55:40 +00001365 if (lenValNL) {
1366 if (isAppending) {
1367 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1368
1369 // Get the string length of the destination. If the destination is
1370 // memory that can't have a string length, we shouldn't be copying
1371 // into it anyway.
1372 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1373 if (dstStrLength.isUndef())
1374 return;
1375
1376 if (NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength)) {
1377 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1378 *lenValNL,
1379 *dstStrLengthNL,
1380 sizeTy);
1381 boundWarning = "Size argument is greater than the free space in the "
1382 "destination buffer";
1383 }
1384
1385 } else {
1386 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1387 // (Yes, strncpy and strncat differ in how they treat termination.
1388 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose6e4244e2012-05-14 17:58:35 +00001389
1390 // We need a special case for when the copy size is zero, in which
1391 // case strncpy will do no work at all. Our bounds check uses n-1
1392 // as the last element accessed, so n == 0 is problematic.
1393 ProgramStateRef StateZeroSize, StateNonZeroSize;
1394 llvm::tie(StateZeroSize, StateNonZeroSize) =
1395 assumeZero(C, state, *lenValNL, sizeTy);
1396
1397 // If the size is known to be zero, we're done.
1398 if (StateZeroSize && !StateNonZeroSize) {
1399 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1400 C.addTransition(StateZeroSize);
1401 return;
1402 }
1403
1404 // Otherwise, go ahead and figure out the last element we'll touch.
1405 // We don't record the non-zero assumption here because we can't
1406 // be sure. We won't warn on a possible zero.
Jordy Rose8912aae2011-06-20 21:55:40 +00001407 NonLoc one = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
1408 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1409 one, sizeTy);
1410 boundWarning = "Size argument is greater than the length of the "
1411 "destination buffer";
1412 }
1413 }
Jordy Rose5e5f1502011-06-20 03:49:16 +00001414
Jordy Rosed5af0e12011-06-15 05:52:56 +00001415 // If we couldn't pin down the copy length, at least bound it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001416 // FIXME: We should actually run this code path for append as well, but
1417 // right now it creates problems with constraints (since we can end up
1418 // trying to pass constraints from symbol to symbol).
1419 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001420 // Try to get a "hypothetical" string length symbol, which we can later
1421 // set as a real value if that turns out to be the case.
1422 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1423 assert(!amountCopied.isUndef());
1424
1425 if (NonLoc *amountCopiedNL = dyn_cast<NonLoc>(&amountCopied)) {
1426 if (lenValNL) {
1427 // amountCopied <= lenVal
1428 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1429 *amountCopiedNL,
1430 *lenValNL,
1431 cmpTy);
1432 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanBound),
1433 true);
1434 if (!state)
1435 return;
1436 }
1437
1438 if (strLengthNL) {
1439 // amountCopied <= strlen(source)
1440 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1441 *amountCopiedNL,
1442 *strLengthNL,
1443 cmpTy);
1444 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanSrc),
1445 true);
1446 if (!state)
1447 return;
1448 }
1449 }
1450 }
1451
1452 } else {
1453 // The function isn't bounded. The amount copied should match the length
1454 // of the source buffer.
1455 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001456 }
1457
Jordy Rosed5af0e12011-06-15 05:52:56 +00001458 assert(state);
1459
1460 // This represents the number of characters copied into the destination
1461 // buffer. (It may not actually be the strlen if the destination buffer
1462 // is not terminated.)
1463 SVal finalStrLength = UnknownVal();
1464
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001465 // If this is an appending function (strcat, strncat...) then set the
1466 // string length to strlen(src) + strlen(dst) since the buffer will
1467 // ultimately contain both.
1468 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001469 // Get the string length of the destination. If the destination is memory
1470 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001471 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1472 if (dstStrLength.isUndef())
1473 return;
1474
Jordy Rosed5af0e12011-06-15 05:52:56 +00001475 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&amountCopied);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001476 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1477
Jordy Rosed5af0e12011-06-15 05:52:56 +00001478 // If we know both string lengths, we might know the final string length.
1479 if (srcStrLengthNL && dstStrLengthNL) {
1480 // Make sure the two lengths together don't overflow a size_t.
1481 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1482 if (!state)
1483 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001484
Jordy Rosed5af0e12011-06-15 05:52:56 +00001485 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1486 *dstStrLengthNL, sizeTy);
1487 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001488
Jordy Rosed5af0e12011-06-15 05:52:56 +00001489 // If we couldn't get a single value for the final string length,
1490 // we can at least bound it by the individual lengths.
1491 if (finalStrLength.isUnknown()) {
1492 // Try to get a "hypothetical" string length symbol, which we can later
1493 // set as a real value if that turns out to be the case.
1494 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1495 assert(!finalStrLength.isUndef());
1496
1497 if (NonLoc *finalStrLengthNL = dyn_cast<NonLoc>(&finalStrLength)) {
1498 if (srcStrLengthNL) {
1499 // finalStrLength >= srcStrLength
1500 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1501 *finalStrLengthNL,
1502 *srcStrLengthNL,
1503 cmpTy);
1504 state = state->assume(cast<DefinedOrUnknownSVal>(sourceInResult),
1505 true);
1506 if (!state)
1507 return;
1508 }
1509
1510 if (dstStrLengthNL) {
1511 // finalStrLength >= dstStrLength
1512 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1513 *finalStrLengthNL,
1514 *dstStrLengthNL,
1515 cmpTy);
1516 state = state->assume(cast<DefinedOrUnknownSVal>(destInResult),
1517 true);
1518 if (!state)
1519 return;
1520 }
1521 }
1522 }
1523
1524 } else {
1525 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1526 // the final string length will match the input string length.
1527 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001528 }
1529
Jordy Rosed5af0e12011-06-15 05:52:56 +00001530 // The final result of the function will either be a pointer past the last
1531 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001532 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001533
Jordy Rosed5af0e12011-06-15 05:52:56 +00001534 assert(state);
1535
Jordy Rosee64f3112010-08-16 07:51:42 +00001536 // If the destination is a MemRegion, try to check for a buffer overflow and
1537 // record the new string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001538 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001539 QualType ptrTy = Dst->getType();
1540
1541 // If we have an exact value on a bounded copy, use that to check for
1542 // overflows, rather than our estimate about how much is actually copied.
1543 if (boundWarning) {
1544 if (NonLoc *maxLastNL = dyn_cast<NonLoc>(&maxLastElementIndex)) {
1545 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1546 *maxLastNL, ptrTy);
1547 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1548 boundWarning);
1549 if (!state)
1550 return;
1551 }
1552 }
1553
1554 // Then, if the final length is known...
Jordy Rosed5af0e12011-06-15 05:52:56 +00001555 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&finalStrLength)) {
1556 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Rose8912aae2011-06-20 21:55:40 +00001557 *knownStrLength, ptrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +00001558
Jordy Rose8912aae2011-06-20 21:55:40 +00001559 // ...and we haven't checked the bound, we'll check the actual copy.
1560 if (!boundWarning) {
1561 const char * const warningMsg =
1562 "String copy function overflows destination buffer";
1563 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1564 if (!state)
1565 return;
1566 }
Jordy Rosee64f3112010-08-16 07:51:42 +00001567
1568 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001569 if (returnEnd)
1570 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001571 }
1572
1573 // Invalidate the destination. This must happen before we set the C string
1574 // length because invalidation will clear the length.
1575 // FIXME: Even if we can't perfectly model the copy, we should see if we
1576 // can use LazyCompoundVals to copy the source values into the destination.
1577 // This would probably remove any existing bindings past the end of the
1578 // string, but that's still an improvement over blank invalidation.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001579 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001580
Jordy Rose5e5f1502011-06-20 03:49:16 +00001581 // Set the C string length of the destination, if we know it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001582 if (isBounded && !isAppending) {
1583 // strncpy is annoying in that it doesn't guarantee to null-terminate
1584 // the result string. If the original string didn't fit entirely inside
1585 // the bound (including the null-terminator), we don't know how long the
1586 // result is.
1587 if (amountCopied != strLength)
1588 finalStrLength = UnknownVal();
1589 }
1590 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001591 }
1592
Jordy Rosed5af0e12011-06-15 05:52:56 +00001593 assert(state);
1594
Jordy Rosee64f3112010-08-16 07:51:42 +00001595 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1596 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001597 if (returnEnd && Result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001598 Result = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosee64f3112010-08-16 07:51:42 +00001599 }
1600
1601 // Set the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001602 state = state->BindExpr(CE, LCtx, Result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001603 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +00001604}
1605
Lenny Maiorani318dd922011-04-12 17:08:43 +00001606void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001607 if (CE->getNumArgs() < 2)
1608 return;
1609
Jordy Roseadc42d42011-06-16 07:13:34 +00001610 //int strcmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001611 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001612}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001613
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001614void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001615 if (CE->getNumArgs() < 3)
1616 return;
1617
Jordy Roseadc42d42011-06-16 07:13:34 +00001618 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001619 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1620}
1621
1622void CStringChecker::evalStrcasecmp(CheckerContext &C,
1623 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 strcasecmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001628 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001629}
1630
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001631void CStringChecker::evalStrncasecmp(CheckerContext &C,
1632 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001633 if (CE->getNumArgs() < 3)
1634 return;
1635
Jordy Roseadc42d42011-06-16 07:13:34 +00001636 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001637 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1638}
1639
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001640void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001641 bool isBounded, bool ignoreCase) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001642 CurrentFunctionDescription = "string comparison function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001643 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001644 const LocationContext *LCtx = C.getLocationContext();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001645
1646 // Check that the first string is non-null
1647 const Expr *s1 = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001648 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001649 state = checkNonNull(C, state, s1, s1Val);
1650 if (!state)
1651 return;
1652
1653 // Check that the second string is non-null.
1654 const Expr *s2 = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001655 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001656 state = checkNonNull(C, state, s2, s2Val);
1657 if (!state)
1658 return;
1659
1660 // Get the string length of the first string or give up.
1661 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1662 if (s1Length.isUndef())
1663 return;
1664
1665 // Get the string length of the second string or give up.
1666 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1667 if (s2Length.isUndef())
1668 return;
1669
Jordy Roseadc42d42011-06-16 07:13:34 +00001670 // If we know the two buffers are the same, we know the result is 0.
1671 // First, get the two buffers' addresses. Another checker will have already
1672 // made sure they're not undefined.
1673 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(s1Val);
1674 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(s2Val);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001675
Jordy Roseadc42d42011-06-16 07:13:34 +00001676 // See if they are the same.
Lenny Maiorani318dd922011-04-12 17:08:43 +00001677 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseadc42d42011-06-16 07:13:34 +00001678 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001679 ProgramStateRef StSameBuf, StNotSameBuf;
Jordy Roseadc42d42011-06-16 07:13:34 +00001680 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001681
Jordy Roseadc42d42011-06-16 07:13:34 +00001682 // If the two arguments might be the same buffer, we know the result is 0,
1683 // and we only need to check one size.
1684 if (StSameBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001685 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1686 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001687 C.addTransition(StSameBuf);
Jordy Roseadc42d42011-06-16 07:13:34 +00001688
1689 // If the two arguments are GUARANTEED to be the same, we're done!
1690 if (!StNotSameBuf)
1691 return;
1692 }
1693
1694 assert(StNotSameBuf);
1695 state = StNotSameBuf;
1696
1697 // At this point we can go about comparing the two buffers.
1698 // For now, we only do this if they're both known string literals.
1699
1700 // Attempt to extract string literals from both expressions.
1701 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1702 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1703 bool canComputeResult = false;
1704
1705 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001706 StringRef s1StrRef = s1StrLiteral->getString();
1707 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Roseadc42d42011-06-16 07:13:34 +00001708
1709 if (isBounded) {
1710 // Get the max number of characters to compare.
1711 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001712 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Roseadc42d42011-06-16 07:13:34 +00001713
1714 // If the length is known, we can get the right substrings.
1715 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1716 // Create substrings of each to compare the prefix.
1717 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1718 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1719 canComputeResult = true;
1720 }
1721 } else {
1722 // This is a normal, unbounded strcmp.
1723 canComputeResult = true;
1724 }
1725
1726 if (canComputeResult) {
1727 // Real strcmp stops at null characters.
1728 size_t s1Term = s1StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001729 if (s1Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001730 s1StrRef = s1StrRef.substr(0, s1Term);
1731
1732 size_t s2Term = s2StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001733 if (s2Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001734 s2StrRef = s2StrRef.substr(0, s2Term);
1735
1736 // Use StringRef's comparison methods to compute the actual result.
1737 int result;
1738
1739 if (ignoreCase) {
1740 // Compare string 1 to string 2 the same way strcasecmp() does.
1741 result = s1StrRef.compare_lower(s2StrRef);
1742 } else {
1743 // Compare string 1 to string 2 the same way strcmp() does.
1744 result = s1StrRef.compare(s2StrRef);
1745 }
1746
1747 // Build the SVal of the comparison and bind the return value.
1748 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001749 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001750 }
1751 }
1752
1753 if (!canComputeResult) {
1754 // Conjure a symbolic value. It's the best we can do.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001755 SVal resultVal = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001756 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001757 }
1758
1759 // Record this as a possible path.
Anna Zaks0bd6b112011-10-26 21:06:34 +00001760 C.addTransition(state);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001761}
1762
Jordy Rosed325ffb2010-07-08 23:57:29 +00001763//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001764// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001765//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001766
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001767bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks998e2752012-02-17 22:35:26 +00001768 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1769
1770 if (!FDecl)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001771 return false;
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001772
Anna Zaks998e2752012-02-17 22:35:26 +00001773 FnCheck evalFunction = 0;
1774 if (C.isCLibraryFunction(FDecl, "memcpy"))
1775 evalFunction = &CStringChecker::evalMemcpy;
1776 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1777 evalFunction = &CStringChecker::evalMempcpy;
1778 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1779 evalFunction = &CStringChecker::evalMemcmp;
1780 else if (C.isCLibraryFunction(FDecl, "memmove"))
1781 evalFunction = &CStringChecker::evalMemmove;
1782 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1783 evalFunction = &CStringChecker::evalStrcpy;
1784 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1785 evalFunction = &CStringChecker::evalStrncpy;
1786 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1787 evalFunction = &CStringChecker::evalStpcpy;
1788 else if (C.isCLibraryFunction(FDecl, "strcat"))
1789 evalFunction = &CStringChecker::evalStrcat;
1790 else if (C.isCLibraryFunction(FDecl, "strncat"))
1791 evalFunction = &CStringChecker::evalStrncat;
1792 else if (C.isCLibraryFunction(FDecl, "strlen"))
1793 evalFunction = &CStringChecker::evalstrLength;
1794 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1795 evalFunction = &CStringChecker::evalstrnLength;
1796 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1797 evalFunction = &CStringChecker::evalStrcmp;
1798 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1799 evalFunction = &CStringChecker::evalStrncmp;
1800 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1801 evalFunction = &CStringChecker::evalStrcasecmp;
1802 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1803 evalFunction = &CStringChecker::evalStrncasecmp;
1804 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1805 evalFunction = &CStringChecker::evalBcopy;
1806 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1807 evalFunction = &CStringChecker::evalMemcmp;
1808
Jordy Rosed325ffb2010-07-08 23:57:29 +00001809 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001810 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001811 return false;
1812
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001813 // Make sure each function sets its own description.
1814 // (But don't bother in a release build.)
1815 assert(!(CurrentFunctionDescription = NULL));
1816
Jordy Rosed325ffb2010-07-08 23:57:29 +00001817 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001818 (this->*evalFunction)(C, CE);
Anna Zaks57300762012-02-07 00:56:14 +00001819
1820 // If the evaluate call resulted in no change, chain to the next eval call
1821 // handler.
1822 // Note, the custom CString evaluation calls assume that basic safety
1823 // properties are held. However, if the user chooses to turn off some of these
1824 // checks, we ignore the issues and leave the call evaluation to a generic
1825 // handler.
1826 if (!C.isDifferent())
1827 return false;
1828
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001829 return true;
1830}
Jordy Rosea5261542010-08-14 21:02:52 +00001831
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001832void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001833 // Record string length for char a[] = "abc";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001834 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001835
1836 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1837 I != E; ++I) {
1838 const VarDecl *D = dyn_cast<VarDecl>(*I);
1839 if (!D)
1840 continue;
1841
1842 // FIXME: Handle array fields of structs.
1843 if (!D->getType()->isArrayType())
1844 continue;
1845
1846 const Expr *Init = D->getInit();
1847 if (!Init)
1848 continue;
1849 if (!isa<StringLiteral>(Init))
1850 continue;
1851
Anna Zaks39ac1872011-10-26 21:06:44 +00001852 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001853 const MemRegion *MR = VarLoc.getAsRegion();
1854 if (!MR)
1855 continue;
1856
Ted Kremenek5eca4822012-01-06 22:09:28 +00001857 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001858 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001859 DefinedOrUnknownSVal strLength
1860 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rosea5261542010-08-14 21:02:52 +00001861
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001862 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001863 }
1864
Anna Zaks0bd6b112011-10-26 21:06:34 +00001865 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001866}
1867
Ted Kremenek8bef8232012-01-26 21:29:00 +00001868bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001869 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001870 return !Entries.isEmpty();
1871}
1872
Ted Kremenek8bef8232012-01-26 21:29:00 +00001873ProgramStateRef
1874CStringChecker::checkRegionChanges(ProgramStateRef state,
Ted Kremenek35bdbf42011-05-02 19:42:42 +00001875 const StoreManager::InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +00001876 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001877 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001878 const CallEvent *Call) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001879 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001880 if (Entries.isEmpty())
1881 return state;
1882
1883 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1884 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1885
1886 // First build sets for the changed regions and their super-regions.
Jordy Rose537716a2011-08-27 22:51:26 +00001887 for (ArrayRef<const MemRegion *>::iterator
1888 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1889 const MemRegion *MR = *I;
Jordy Rosea5261542010-08-14 21:02:52 +00001890 Invalidated.insert(MR);
1891
1892 SuperRegions.insert(MR);
1893 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1894 MR = SR->getSuperRegion();
1895 SuperRegions.insert(MR);
1896 }
1897 }
1898
Jordan Rose166d5022012-11-02 01:54:06 +00001899 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001900
1901 // Then loop over the entries in the current state.
Jordan Rose166d5022012-11-02 01:54:06 +00001902 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rosea5261542010-08-14 21:02:52 +00001903 E = Entries.end(); I != E; ++I) {
1904 const MemRegion *MR = I.getKey();
1905
1906 // Is this entry for a super-region of a changed region?
1907 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001908 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001909 continue;
1910 }
1911
1912 // Is this entry for a sub-region of a changed region?
1913 const MemRegion *Super = MR;
1914 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1915 Super = SR->getSuperRegion();
1916 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001917 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001918 break;
1919 }
1920 }
1921 }
1922
1923 return state->set<CStringLength>(Entries);
1924}
1925
Ted Kremenek8bef8232012-01-26 21:29:00 +00001926void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001927 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001928 // Mark all symbols in our string length map as valid.
Jordan Rose166d5022012-11-02 01:54:06 +00001929 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001930
Jordan Rose166d5022012-11-02 01:54:06 +00001931 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00001932 I != E; ++I) {
1933 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001934
Anna Zaks1d1d5152011-12-06 23:12:33 +00001935 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
1936 se = Len.symbol_end(); si != se; ++si)
Jordy Rosed5af0e12011-06-15 05:52:56 +00001937 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00001938 }
1939}
1940
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001941void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1942 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001943 if (!SR.hasDeadSymbols())
1944 return;
1945
Ted Kremenek8bef8232012-01-26 21:29:00 +00001946 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00001947 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001948 if (Entries.isEmpty())
1949 return;
1950
Jordan Rose166d5022012-11-02 01:54:06 +00001951 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
1952 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00001953 I != E; ++I) {
1954 SVal Len = I.getData();
1955 if (SymbolRef Sym = Len.getAsSymbol()) {
1956 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00001957 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00001958 }
1959 }
1960
1961 state = state->set<CStringLength>(Entries);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001962 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001963}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001964
Anna Zaks57300762012-02-07 00:56:14 +00001965#define REGISTER_CHECKER(name) \
1966void ento::register##name(CheckerManager &mgr) {\
1967 static CStringChecker *TheChecker = 0; \
1968 if (TheChecker == 0) \
1969 TheChecker = mgr.registerChecker<CStringChecker>(); \
1970 TheChecker->Filter.Check##name = true; \
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001971}
Anna Zaks57300762012-02-07 00:56:14 +00001972
1973REGISTER_CHECKER(CStringNullArg)
1974REGISTER_CHECKER(CStringOutOfBounds)
1975REGISTER_CHECKER(CStringBufferOverlap)
1976REGISTER_CHECKER(CStringNotNullTerm)
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001977
1978void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
1979 registerCStringNullArg(Mgr);
1980}