blob: 362672df7edfde432c5d3b8b4f65e9c44046366c [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"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000025#include "llvm/Support/raw_ostream.h"
Jordy Roseccbf7ee2010-07-06 23:11:01 +000026
27using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000028using namespace ento;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000029
30namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000031class CStringChecker : public Checker< eval::Call,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000032 check::PreStmt<DeclStmt>,
33 check::LiveSymbols,
34 check::DeadSymbols,
35 check::RegionChanges
36 > {
Anna Zaks57300762012-02-07 00:56:14 +000037 mutable OwningPtr<BugType> BT_Null,
38 BT_Bounds,
39 BT_Overlap,
40 BT_NotCString,
41 BT_AdditionOverflow;
42
Jordy Rose9e49d9f2011-06-20 02:06:40 +000043 mutable const char *CurrentFunctionDescription;
44
Jordy Roseccbf7ee2010-07-06 23:11:01 +000045public:
Anna Zaks57300762012-02-07 00:56:14 +000046 /// The filter is used to filter out the diagnostics which are not enabled by
47 /// the user.
48 struct CStringChecksFilter {
49 DefaultBool CheckCStringNullArg;
50 DefaultBool CheckCStringOutOfBounds;
51 DefaultBool CheckCStringBufferOverlap;
52 DefaultBool CheckCStringNotNullTerm;
53 };
54
55 CStringChecksFilter Filter;
56
Jordy Roseccbf7ee2010-07-06 23:11:01 +000057 static void *getTag() { static int tag; return &tag; }
58
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000059 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
60 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +000061 void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000062 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +000063 bool wantsRegionChangeUpdate(ProgramStateRef state) const;
Jordy Rosea5261542010-08-14 21:02:52 +000064
Ted Kremenek8bef8232012-01-26 21:29:00 +000065 ProgramStateRef
66 checkRegionChanges(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000067 const StoreManager::InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +000068 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +000069 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +000070 const CallEvent *Call) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000071
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000072 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
73 const CallExpr *) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000074
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000075 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000076 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000077 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
78 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000079 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +000080 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000081 const Expr *Size,
82 const Expr *Source,
83 const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +000084 bool Restricted = false,
85 bool IsMempcpy = false) const;
Jordy Rosed325ffb2010-07-08 23:57:29 +000086
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000087 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000088
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000089 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
90 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000091 void evalstrLengthCommon(CheckerContext &C,
92 const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000093 bool IsStrnlen = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +000094
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000095 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
96 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
97 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000098 void evalStrcpyCommon(CheckerContext &C,
99 const CallExpr *CE,
100 bool returnEnd,
101 bool isBounded,
102 bool isAppending) const;
Lenny Maiorani067bbd02011-04-09 15:12:58 +0000103
104 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
105 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Jordy Rosee64f3112010-08-16 07:51:42 +0000106
Lenny Maiorani318dd922011-04-12 17:08:43 +0000107 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani357f6ee2011-04-25 22:21:00 +0000108 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranibd1d16a2011-04-28 15:09:11 +0000109 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani454fd2d2011-05-02 19:05:49 +0000110 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000111 void evalStrcmpCommon(CheckerContext &C,
112 const CallExpr *CE,
113 bool isBounded = false,
114 bool ignoreCase = false) const;
Lenny Maiorani318dd922011-04-12 17:08:43 +0000115
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000116 // Utility methods
Ted Kremenek8bef8232012-01-26 21:29:00 +0000117 std::pair<ProgramStateRef , ProgramStateRef >
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000118 static assumeZero(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000119 ProgramStateRef state, SVal V, QualType Ty);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000120
Ted Kremenek8bef8232012-01-26 21:29:00 +0000121 static ProgramStateRef setCStringLength(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000122 const MemRegion *MR,
123 SVal strLength);
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000124 static SVal getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000125 ProgramStateRef &state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000126 const Expr *Ex,
127 const MemRegion *MR,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000128 bool hypothetical);
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000129 SVal getCStringLength(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000130 ProgramStateRef &state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000131 const Expr *Ex,
132 SVal Buf,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000133 bool hypothetical = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000134
Lenny Maiorani318dd922011-04-12 17:08:43 +0000135 const StringLiteral *getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000136 ProgramStateRef &state,
Lenny Maiorani318dd922011-04-12 17:08:43 +0000137 const Expr *expr,
138 SVal val) const;
139
Ted Kremenek8bef8232012-01-26 21:29:00 +0000140 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
141 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000142 const Expr *Ex, SVal V);
Jordy Rosee64f3112010-08-16 07:51:42 +0000143
Ted Kremenek9c378f72011-08-12 23:37:29 +0000144 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000145 const MemRegion *MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000146
147 // Re-usable checks
Ted Kremenek8bef8232012-01-26 21:29:00 +0000148 ProgramStateRef checkNonNull(CheckerContext &C,
149 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000150 const Expr *S,
151 SVal l) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000152 ProgramStateRef CheckLocation(CheckerContext &C,
153 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000154 const Expr *S,
155 SVal l,
156 const char *message = NULL) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000157 ProgramStateRef CheckBufferAccess(CheckerContext &C,
158 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000159 const Expr *Size,
160 const Expr *FirstBuf,
161 const Expr *SecondBuf,
162 const char *firstMessage = NULL,
163 const char *secondMessage = NULL,
164 bool WarnAboutSize = false) const;
165
Ted Kremenek8bef8232012-01-26 21:29:00 +0000166 ProgramStateRef CheckBufferAccess(CheckerContext &C,
167 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000168 const Expr *Size,
169 const Expr *Buf,
170 const char *message = NULL,
171 bool WarnAboutSize = false) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000172 // This is a convenience override.
Jordy Rose5e5f1502011-06-20 03:49:16 +0000173 return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
174 WarnAboutSize);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000175 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000176 ProgramStateRef CheckOverlap(CheckerContext &C,
177 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000178 const Expr *Size,
179 const Expr *First,
180 const Expr *Second) const;
181 void emitOverlapBug(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000182 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000183 const Stmt *First,
184 const Stmt *Second) const;
185
Ted Kremenek8bef8232012-01-26 21:29:00 +0000186 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
187 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000188 NonLoc left,
189 NonLoc right) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000190};
Jordy Rosea5261542010-08-14 21:02:52 +0000191
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000192} //end anonymous namespace
193
Jordan Rose166d5022012-11-02 01:54:06 +0000194REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal)
Jordy Rosea5261542010-08-14 21:02:52 +0000195
Jordy Rosed325ffb2010-07-08 23:57:29 +0000196//===----------------------------------------------------------------------===//
197// Individual checks and utility methods.
198//===----------------------------------------------------------------------===//
199
Ted Kremenek8bef8232012-01-26 21:29:00 +0000200std::pair<ProgramStateRef , ProgramStateRef >
201CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000202 QualType Ty) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000203 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
204 if (!val)
Ted Kremenek8bef8232012-01-26 21:29:00 +0000205 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000206
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000207 SValBuilder &svalBuilder = C.getSValBuilder();
208 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
209 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000210}
Jordy Rosea6b808c2010-07-07 07:48:06 +0000211
Ted Kremenek8bef8232012-01-26 21:29:00 +0000212ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
213 ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000214 const Expr *S, SVal l) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000215 // If a previous check has failed, propagate the failure.
216 if (!state)
217 return NULL;
218
Ted Kremenek8bef8232012-01-26 21:29:00 +0000219 ProgramStateRef stateNull, stateNonNull;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000220 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed325ffb2010-07-08 23:57:29 +0000221
222 if (stateNull && !stateNonNull) {
Anna Zaks57300762012-02-07 00:56:14 +0000223 if (!Filter.CheckCStringNullArg)
224 return NULL;
225
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000226 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000227 if (!N)
228 return NULL;
229
Jordy Rosed325ffb2010-07-08 23:57:29 +0000230 if (!BT_Null)
Anna Zaks57300762012-02-07 00:56:14 +0000231 BT_Null.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000232 "Null pointer argument in call to byte string function"));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000233
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000234 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000235 llvm::raw_svector_ostream os(buf);
236 assert(CurrentFunctionDescription);
237 os << "Null pointer argument in call to " << CurrentFunctionDescription;
238
Jordy Rosea6b808c2010-07-07 07:48:06 +0000239 // Generate a report for this bug.
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000240 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Anna Zakse172e8b2011-08-17 23:00:25 +0000241 BugReport *report = new BugReport(*BT, os.str(), N);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000242
243 report->addRange(S->getSourceRange());
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000244 bugreporter::trackNullOrUndefValue(N, S, *report);
Jordan Rose785950e2012-11-02 01:53:40 +0000245 C.emitReport(report);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000246 return NULL;
247 }
248
249 // From here on, assume that the value is non-null.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000250 assert(stateNonNull);
251 return stateNonNull;
Jordy Rosea6b808c2010-07-07 07:48:06 +0000252}
253
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000254// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek8bef8232012-01-26 21:29:00 +0000255ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
256 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000257 const Expr *S, SVal l,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000258 const char *warningMsg) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000259 // If a previous check has failed, propagate the failure.
260 if (!state)
261 return NULL;
262
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000263 // Check for out of bound array element access.
264 const MemRegion *R = l.getAsRegion();
265 if (!R)
266 return state;
267
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000268 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
269 if (!ER)
270 return state;
271
Zhongxing Xu018220c2010-08-11 06:10:55 +0000272 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000273 "CheckLocation should only be called with char* ElementRegions");
274
275 // Get the size of the array.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000276 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
277 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000278 SVal Extent =
279 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000280 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
281
282 // Get the index of the accessed element.
Gabor Greif89b06582010-09-09 10:51:37 +0000283 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000284
Ted Kremenek8bef8232012-01-26 21:29:00 +0000285 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
286 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000287 if (StOutBound && !StInBound) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000288 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000289 if (!N)
290 return NULL;
291
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000292 if (!BT_Bounds) {
293 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
294 "Byte string function accesses out-of-bound array element"));
295 }
296 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
297
298 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000299 BugReport *report;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000300 if (warningMsg) {
Anna Zakse172e8b2011-08-17 23:00:25 +0000301 report = new BugReport(*BT, warningMsg, N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000302 } else {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000303 assert(CurrentFunctionDescription);
304 assert(CurrentFunctionDescription[0] != '\0');
305
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000306 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000307 llvm::raw_svector_ostream os(buf);
308 os << (char)toupper(CurrentFunctionDescription[0])
309 << &CurrentFunctionDescription[1]
310 << " accesses out-of-bound array element";
Anna Zakse172e8b2011-08-17 23:00:25 +0000311 report = new BugReport(*BT, os.str(), N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000312 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000313
314 // FIXME: It would be nice to eventually make this diagnostic more clear,
315 // e.g., by referencing the original declaration or by saying *why* this
316 // reference is outside the range.
317
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000318 report->addRange(S->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000319 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000320 return NULL;
321 }
322
323 // Array bound check succeeded. From this point forward the array bound
324 // should always succeed.
325 return StInBound;
326}
327
Ted Kremenek8bef8232012-01-26 21:29:00 +0000328ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
329 ProgramStateRef state,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000330 const Expr *Size,
331 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000332 const Expr *SecondBuf,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000333 const char *firstMessage,
Jordy Rose5e5f1502011-06-20 03:49:16 +0000334 const char *secondMessage,
335 bool WarnAboutSize) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000336 // If a previous check has failed, propagate the failure.
337 if (!state)
338 return NULL;
339
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000340 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000341 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000342 const LocationContext *LCtx = C.getLocationContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000343
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000344 QualType sizeTy = Size->getType();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000345 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
346
Jordy Rosea6b808c2010-07-07 07:48:06 +0000347 // Check that the first buffer is non-null.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000348 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000349 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000350 if (!state)
351 return NULL;
352
Anna Zaks57300762012-02-07 00:56:14 +0000353 // If out-of-bounds checking is turned off, skip the rest.
354 if (!Filter.CheckCStringOutOfBounds)
355 return state;
356
Jordy Rosed325ffb2010-07-08 23:57:29 +0000357 // Get the access length and make sure it is known.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000358 // FIXME: This assumes the caller has already checked that the access length
359 // is positive. And that it's unsigned.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000360 SVal LengthVal = state->getSVal(Size, LCtx);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000361 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
362 if (!Length)
363 return state;
364
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000365 // Compute the offset of the last element to be accessed: size-1.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000366 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
367 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
368 *Length, One, sizeTy));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000369
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000370 // Check that the first buffer is sufficiently long.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000371 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000372 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000373 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
374
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000375 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
376 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000377 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000378
Jordy Roseb6a40262010-08-05 23:11:30 +0000379 // If the buffer isn't large enough, abort.
380 if (!state)
381 return NULL;
382 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000383
384 // If there's a second buffer, check it as well.
385 if (SecondBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000386 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000387 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000388 if (!state)
389 return NULL;
390
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000391 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000392 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000393 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
394
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000395 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
396 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000397 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseb6a40262010-08-05 23:11:30 +0000398 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000399 }
400
401 // Large enough or not, return this state!
402 return state;
403}
404
Ted Kremenek8bef8232012-01-26 21:29:00 +0000405ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
406 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000407 const Expr *Size,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000408 const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000409 const Expr *Second) const {
Anna Zaks57300762012-02-07 00:56:14 +0000410 if (!Filter.CheckCStringBufferOverlap)
411 return state;
412
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000413 // Do a simple check for overlap: if the two arguments are from the same
414 // buffer, see if the end of the first is greater than the start of the second
415 // or vice versa.
416
Jordy Rosed325ffb2010-07-08 23:57:29 +0000417 // If a previous check has failed, propagate the failure.
418 if (!state)
419 return NULL;
420
Ted Kremenek8bef8232012-01-26 21:29:00 +0000421 ProgramStateRef stateTrue, stateFalse;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000422
423 // Get the buffer values and make sure they're known locations.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000424 const LocationContext *LCtx = C.getLocationContext();
425 SVal firstVal = state->getSVal(First, LCtx);
426 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000427
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000428 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
429 if (!firstLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000430 return state;
431
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000432 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
433 if (!secondLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000434 return state;
435
436 // Are the two values the same?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000437 SValBuilder &svalBuilder = C.getSValBuilder();
438 llvm::tie(stateTrue, stateFalse) =
439 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000440
441 if (stateTrue && !stateFalse) {
442 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000443 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000444 return NULL;
445 }
446
Ted Kremenek28f47b92010-12-01 22:16:56 +0000447 // assume the two expressions are not equal.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000448 assert(stateFalse);
449 state = stateFalse;
450
451 // Which value comes first?
Jordy Roseee2fde12011-06-16 05:56:50 +0000452 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000453 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
454 *firstLoc, *secondLoc, cmpTy);
455 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
456 if (!reverseTest)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000457 return state;
458
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000459 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000460 if (stateTrue) {
461 if (stateFalse) {
462 // If we don't know which one comes first, we can't perform this test.
463 return state;
464 } else {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000465 // Switch the values so that firstVal is before secondVal.
466 Loc *tmpLoc = firstLoc;
467 firstLoc = secondLoc;
468 secondLoc = tmpLoc;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000469
470 // Switch the Exprs as well, so that they still correspond.
471 const Expr *tmpExpr = First;
472 First = Second;
473 Second = tmpExpr;
474 }
475 }
476
477 // Get the length, and make sure it too is known.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000478 SVal LengthVal = state->getSVal(Size, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000479 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
480 if (!Length)
481 return state;
482
483 // Convert the first buffer's start address to char*.
484 // Bail out if the cast fails.
Jordy Roseee2fde12011-06-16 05:56:50 +0000485 ASTContext &Ctx = svalBuilder.getContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000486 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose1e022412011-06-16 05:51:02 +0000487 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
488 First->getType());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000489 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
490 if (!FirstStartLoc)
491 return state;
492
493 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000494 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000495 *FirstStartLoc, *Length, CharPtrTy);
496 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
497 if (!FirstEndLoc)
498 return state;
499
500 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000501 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
502 *FirstEndLoc, *secondLoc, cmpTy);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000503 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
504 if (!OverlapTest)
505 return state;
506
Ted Kremenek28f47b92010-12-01 22:16:56 +0000507 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000508
509 if (stateTrue && !stateFalse) {
510 // Overlap!
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000511 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000512 return NULL;
513 }
514
Ted Kremenek28f47b92010-12-01 22:16:56 +0000515 // assume the two expressions don't overlap.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000516 assert(stateFalse);
517 return stateFalse;
518}
519
Ted Kremenek8bef8232012-01-26 21:29:00 +0000520void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000521 const Stmt *First, const Stmt *Second) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000522 ExplodedNode *N = C.generateSink(state);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000523 if (!N)
524 return;
525
526 if (!BT_Overlap)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000527 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000528
529 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000530 BugReport *report =
531 new BugReport(*BT_Overlap,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000532 "Arguments must not be overlapping buffers", N);
533 report->addRange(First->getSourceRange());
534 report->addRange(Second->getSourceRange());
535
Jordan Rose785950e2012-11-02 01:53:40 +0000536 C.emitReport(report);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000537}
538
Ted Kremenek8bef8232012-01-26 21:29:00 +0000539ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
540 ProgramStateRef state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000541 NonLoc left,
542 NonLoc right) const {
Anna Zaks57300762012-02-07 00:56:14 +0000543 // If out-of-bounds checking is turned off, skip the rest.
544 if (!Filter.CheckCStringOutOfBounds)
545 return state;
546
Jordy Rosed5af0e12011-06-15 05:52:56 +0000547 // If a previous check has failed, propagate the failure.
548 if (!state)
549 return NULL;
550
551 SValBuilder &svalBuilder = C.getSValBuilder();
552 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
553
554 QualType sizeTy = svalBuilder.getContext().getSizeType();
555 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
556 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
557
Anna Zakse3d250e2011-12-11 18:43:40 +0000558 SVal maxMinusRight;
559 if (isa<nonloc::ConcreteInt>(right)) {
560 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
561 sizeTy);
562 } else {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000563 // Try switching the operands. (The order of these two assignments is
564 // important!)
565 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
566 sizeTy);
567 left = right;
568 }
569
570 if (NonLoc *maxMinusRightNL = dyn_cast<NonLoc>(&maxMinusRight)) {
571 QualType cmpTy = svalBuilder.getConditionType();
572 // If left > max - right, we have an overflow.
573 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
574 *maxMinusRightNL, cmpTy);
575
Ted Kremenek8bef8232012-01-26 21:29:00 +0000576 ProgramStateRef stateOverflow, stateOkay;
Jordy Rosed5af0e12011-06-15 05:52:56 +0000577 llvm::tie(stateOverflow, stateOkay) =
578 state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
579
580 if (stateOverflow && !stateOkay) {
581 // We have an overflow. Emit a bug report.
582 ExplodedNode *N = C.generateSink(stateOverflow);
583 if (!N)
584 return NULL;
585
586 if (!BT_AdditionOverflow)
587 BT_AdditionOverflow.reset(new BuiltinBug("API",
588 "Sum of expressions causes overflow"));
589
Jordy Rosed5af0e12011-06-15 05:52:56 +0000590 // This isn't a great error message, but this should never occur in real
591 // code anyway -- you'd have to create a buffer longer than a size_t can
592 // represent, which is sort of a contradiction.
Jordy Rose8cc24912011-06-20 03:51:53 +0000593 const char *warning =
594 "This expression will create a string whose length is too big to "
595 "be represented as a size_t";
Jordy Rosed5af0e12011-06-15 05:52:56 +0000596
597 // Generate a report for this bug.
Jordy Rose8cc24912011-06-20 03:51:53 +0000598 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
Jordan Rose785950e2012-11-02 01:53:40 +0000599 C.emitReport(report);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000600
601 return NULL;
602 }
603
604 // From now on, assume an overflow didn't occur.
605 assert(stateOkay);
606 state = stateOkay;
607 }
608
609 return state;
610}
611
Ted Kremenek8bef8232012-01-26 21:29:00 +0000612ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000613 const MemRegion *MR,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000614 SVal strLength) {
615 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rosee64f3112010-08-16 07:51:42 +0000616
617 MR = MR->StripCasts();
618
619 switch (MR->getKind()) {
620 case MemRegion::StringRegionKind:
621 // FIXME: This can happen if we strcpy() into a string region. This is
622 // undefined [C99 6.4.5p6], but we should still warn about it.
623 return state;
624
625 case MemRegion::SymbolicRegionKind:
626 case MemRegion::AllocaRegionKind:
627 case MemRegion::VarRegionKind:
628 case MemRegion::FieldRegionKind:
629 case MemRegion::ObjCIvarRegionKind:
Jordy Rose210c05b2011-06-15 05:14:03 +0000630 // These are the types we can currently track string lengths for.
631 break;
Jordy Rosee64f3112010-08-16 07:51:42 +0000632
633 case MemRegion::ElementRegionKind:
634 // FIXME: Handle element regions by upper-bounding the parent region's
635 // string length.
636 return state;
637
638 default:
639 // Other regions (mostly non-data) can't have a reliable C string length.
640 // For now, just ignore the change.
641 // FIXME: These are rare but not impossible. We should output some kind of
642 // warning for things like strcpy((char[]){'a', 0}, "b");
643 return state;
644 }
Jordy Rose210c05b2011-06-15 05:14:03 +0000645
646 if (strLength.isUnknown())
647 return state->remove<CStringLength>(MR);
648
649 return state->set<CStringLength>(MR, strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +0000650}
651
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000652SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000653 ProgramStateRef &state,
Jordy Rosea5261542010-08-14 21:02:52 +0000654 const Expr *Ex,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000655 const MemRegion *MR,
656 bool hypothetical) {
657 if (!hypothetical) {
658 // If there's a recorded length, go ahead and return it.
659 const SVal *Recorded = state->get<CStringLength>(MR);
660 if (Recorded)
661 return *Recorded;
662 }
Jordy Rosea5261542010-08-14 21:02:52 +0000663
664 // Otherwise, get a new symbol and update the state.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000665 SValBuilder &svalBuilder = C.getSValBuilder();
666 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000667 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
Ted Kremenek66c486f2012-08-22 06:26:15 +0000668 MR, Ex, sizeTy,
669 C.blockCount());
Jordy Rosed5af0e12011-06-15 05:52:56 +0000670
671 if (!hypothetical)
672 state = state->set<CStringLength>(MR, strLength);
673
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000674 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000675}
676
Ted Kremenek8bef8232012-01-26 21:29:00 +0000677SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000678 const Expr *Ex, SVal Buf,
679 bool hypothetical) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000680 const MemRegion *MR = Buf.getAsRegion();
681 if (!MR) {
682 // If we can't get a region, see if it's something we /know/ isn't a
683 // C string. In the context of locations, the only time we can issue such
684 // a warning is for labels.
685 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
Anna Zaks57300762012-02-07 00:56:14 +0000686 if (!Filter.CheckCStringNotNullTerm)
687 return UndefinedVal();
688
Anna Zaks0bd6b112011-10-26 21:06:34 +0000689 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000690 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000691 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000692 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000693
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000694 SmallString<120> buf;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000695 llvm::raw_svector_ostream os(buf);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000696 assert(CurrentFunctionDescription);
697 os << "Argument to " << CurrentFunctionDescription
698 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000699 << "', which is not a null-terminated string";
700
701 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000702 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000703 os.str(), N);
704
705 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000706 C.emitReport(report);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000707 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000708 return UndefinedVal();
Anna Zaks57300762012-02-07 00:56:14 +0000709
Jordy Rose19c5dd12010-07-27 01:37:31 +0000710 }
711
Jordy Rosea5261542010-08-14 21:02:52 +0000712 // If it's not a region and not a label, give up.
713 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000714 }
715
Jordy Rosea5261542010-08-14 21:02:52 +0000716 // If we have a region, strip casts from it and see if we can figure out
717 // its length. For anything we can't figure out, just return UnknownVal.
718 MR = MR->StripCasts();
719
720 switch (MR->getKind()) {
721 case MemRegion::StringRegionKind: {
722 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
723 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000724 SValBuilder &svalBuilder = C.getSValBuilder();
725 QualType sizeTy = svalBuilder.getContext().getSizeType();
726 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
727 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000728 }
729 case MemRegion::SymbolicRegionKind:
730 case MemRegion::AllocaRegionKind:
731 case MemRegion::VarRegionKind:
732 case MemRegion::FieldRegionKind:
733 case MemRegion::ObjCIvarRegionKind:
Jordy Rosed5af0e12011-06-15 05:52:56 +0000734 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rosea5261542010-08-14 21:02:52 +0000735 case MemRegion::CompoundLiteralRegionKind:
736 // FIXME: Can we track this? Is it necessary?
737 return UnknownVal();
738 case MemRegion::ElementRegionKind:
739 // FIXME: How can we handle this? It's not good enough to subtract the
740 // offset from the base string length; consider "123\x00567" and &a[5].
741 return UnknownVal();
742 default:
743 // Other regions (mostly non-data) can't have a reliable C string length.
744 // In this case, an error is emitted and UndefinedVal is returned.
745 // The caller should always be prepared to handle this case.
Anna Zaks57300762012-02-07 00:56:14 +0000746 if (!Filter.CheckCStringNotNullTerm)
747 return UndefinedVal();
748
Anna Zaks0bd6b112011-10-26 21:06:34 +0000749 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000750 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000751 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000752 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000753
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000754 SmallString<120> buf;
Jordy Rosea5261542010-08-14 21:02:52 +0000755 llvm::raw_svector_ostream os(buf);
756
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000757 assert(CurrentFunctionDescription);
758 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rosea5261542010-08-14 21:02:52 +0000759
760 if (SummarizeRegion(os, C.getASTContext(), MR))
761 os << ", which is not a null-terminated string";
762 else
763 os << "not a null-terminated string";
764
765 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000766 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rosea5261542010-08-14 21:02:52 +0000767 os.str(), N);
768
769 report->addRange(Ex->getSourceRange());
Jordan Rose785950e2012-11-02 01:53:40 +0000770 C.emitReport(report);
Jordy Rosea5261542010-08-14 21:02:52 +0000771 }
772
773 return UndefinedVal();
774 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000775}
776
Lenny Maiorani318dd922011-04-12 17:08:43 +0000777const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000778 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +0000779
780 // Get the memory region pointed to by the val.
781 const MemRegion *bufRegion = val.getAsRegion();
782 if (!bufRegion)
783 return NULL;
784
785 // Strip casts off the memory region.
786 bufRegion = bufRegion->StripCasts();
787
788 // Cast the memory region to a string region.
789 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
790 if (!strRegion)
791 return NULL;
792
793 // Return the actual string in the string region.
794 return strRegion->getStringLiteral();
795}
796
Ted Kremenek8bef8232012-01-26 21:29:00 +0000797ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
798 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000799 const Expr *E, SVal V) {
800 Loc *L = dyn_cast<Loc>(&V);
801 if (!L)
802 return state;
803
804 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
805 // some assumptions about the value that CFRefCount can't. Even so, it should
806 // probably be refactored.
807 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
808 const MemRegion *R = MR->getRegion()->StripCasts();
809
810 // Are we dealing with an ElementRegion? If so, we should be invalidating
811 // the super-region.
812 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
813 R = ER->getSuperRegion();
814 // FIXME: What about layers of ElementRegions?
815 }
816
817 // Invalidate this region.
Ted Kremenek3133f792012-02-17 23:13:45 +0000818 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
Ted Kremenek66c486f2012-08-22 06:26:15 +0000819 return state->invalidateRegions(R, E, C.blockCount(), LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +0000820 }
821
822 // If we have a non-region value by chance, just remove the binding.
823 // FIXME: is this necessary or correct? This handles the non-Region
824 // cases. Is it ever valid to store to these?
Ted Kremenek56a46b52012-08-22 06:37:46 +0000825 return state->killBinding(*L);
Jordy Rosee64f3112010-08-16 07:51:42 +0000826}
827
Ted Kremenek9c378f72011-08-12 23:37:29 +0000828bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000829 const MemRegion *MR) {
Ted Kremenek96979342011-08-12 20:02:48 +0000830 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000831
Jordy Rose096aef92011-08-12 21:41:07 +0000832 switch (MR->getKind()) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000833 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000834 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000835 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000836 os << "the address of the function '" << *FD << '\'';
Jordy Rose19c5dd12010-07-27 01:37:31 +0000837 else
838 os << "the address of a function";
839 return true;
840 }
841 case MemRegion::BlockTextRegionKind:
842 os << "block text";
843 return true;
844 case MemRegion::BlockDataRegionKind:
845 os << "a block";
846 return true;
847 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000848 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000849 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000850 return true;
851 case MemRegion::VarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000852 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000853 return true;
854 case MemRegion::FieldRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000855 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000856 return true;
857 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000858 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000859 return true;
860 default:
861 return false;
862 }
863}
864
Jordy Rosed325ffb2010-07-08 23:57:29 +0000865//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000866// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000867//===----------------------------------------------------------------------===//
868
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000869void CStringChecker::evalCopyCommon(CheckerContext &C,
870 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000871 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000872 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000873 const Expr *Source, bool Restricted,
874 bool IsMempcpy) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000875 CurrentFunctionDescription = "memory copy function";
876
Jordy Rosed325ffb2010-07-08 23:57:29 +0000877 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000878 const LocationContext *LCtx = C.getLocationContext();
879 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000880 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000881
Ted Kremenek8bef8232012-01-26 21:29:00 +0000882 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose1e022412011-06-16 05:51:02 +0000883 llvm::tie(stateZeroSize, stateNonZeroSize) =
884 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000885
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000886 // Get the value of the Dest.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000887 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000888
889 // If the size is zero, there won't be any actual memory access, so
890 // just bind the return value to the destination buffer and return.
Anna Zaksdd160f32012-05-03 18:21:28 +0000891 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000892 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000893 C.addTransition(stateZeroSize);
Anna Zaksdd160f32012-05-03 18:21:28 +0000894 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000895 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000896
897 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000898 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000899 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000900
901 // Ensure the destination is not null. If it is NULL there will be a
902 // NULL pointer dereference.
903 state = checkNonNull(C, state, Dest, destVal);
904 if (!state)
905 return;
906
907 // Get the value of the Src.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000908 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000909
910 // Ensure the source is not null. If it is NULL there will be a
911 // NULL pointer dereference.
912 state = checkNonNull(C, state, Source, srcVal);
913 if (!state)
914 return;
915
Jordy Rose7182b962011-06-04 01:50:25 +0000916 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000917 const char * const writeWarning =
918 "Memory copy function overflows destination buffer";
Jordy Rosee64f3112010-08-16 07:51:42 +0000919 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000920 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000921 if (Restricted)
922 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000923
Jordy Rose7182b962011-06-04 01:50:25 +0000924 if (!state)
925 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000926
Jordy Rose7182b962011-06-04 01:50:25 +0000927 // If this is mempcpy, get the byte after the last byte copied and
928 // bind the expr.
929 if (IsMempcpy) {
930 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
931 assert(destRegVal && "Destination should be a known MemRegionVal here");
932
933 // Get the length to copy.
934 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
935
936 if (lenValNonLoc) {
937 // Get the byte after the last byte copied.
938 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
939 *destRegVal,
940 *lenValNonLoc,
941 Dest->getType());
942
943 // The byte after the last byte copied is the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000944 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000945 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000946 // If we don't know how much we copied, we can at least
947 // conjure a return value for later.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000948 SVal result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx,
949 C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +0000950 state = state->BindExpr(CE, LCtx, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000951 }
952
Jordy Rose7182b962011-06-04 01:50:25 +0000953 } else {
954 // All other copies return the destination buffer.
955 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000956 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000957 }
Jordy Rose7182b962011-06-04 01:50:25 +0000958
959 // Invalidate the destination.
960 // FIXME: Even if we can't perfectly model the copy, we should see if we
961 // can use LazyCompoundVals to copy the source values into the destination.
962 // This would probably remove any existing bindings past the end of the
963 // copied region, but that's still an improvement over blank invalidation.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000964 state = InvalidateBuffer(C, state, Dest,
965 state->getSVal(Dest, C.getLocationContext()));
Anna Zaks0bd6b112011-10-26 21:06:34 +0000966 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000967 }
968}
969
970
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000971void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000972 if (CE->getNumArgs() < 3)
973 return;
974
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000975 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000976 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000977 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000978 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000979
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000980 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
981}
982
983void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000984 if (CE->getNumArgs() < 3)
985 return;
986
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000987 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
988 // The return value is a pointer to the byte following the last written byte.
989 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000990 ProgramStateRef state = C.getState();
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000991
992 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000993}
994
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000995void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000996 if (CE->getNumArgs() < 3)
997 return;
998
Jordy Rosed325ffb2010-07-08 23:57:29 +0000999 // void *memmove(void *dst, const void *src, size_t n);
1000 // The return value is the address of the destination buffer.
1001 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001002 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001003
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001004 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001005}
1006
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001007void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001008 if (CE->getNumArgs() < 3)
1009 return;
1010
Jordy Rosed325ffb2010-07-08 23:57:29 +00001011 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001012 evalCopyCommon(C, CE, C.getState(),
1013 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001014}
1015
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001016void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001017 if (CE->getNumArgs() < 3)
1018 return;
1019
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001020 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001021 CurrentFunctionDescription = "memory comparison function";
1022
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001023 const Expr *Left = CE->getArg(0);
1024 const Expr *Right = CE->getArg(1);
1025 const Expr *Size = CE->getArg(2);
1026
Ted Kremenek8bef8232012-01-26 21:29:00 +00001027 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001028 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001029
Jordy Rosed325ffb2010-07-08 23:57:29 +00001030 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001031 const LocationContext *LCtx = C.getLocationContext();
1032 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001033 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001034
Ted Kremenek8bef8232012-01-26 21:29:00 +00001035 ProgramStateRef stateZeroSize, stateNonZeroSize;
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001036 llvm::tie(stateZeroSize, stateNonZeroSize) =
1037 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001038
Jordy Rosed325ffb2010-07-08 23:57:29 +00001039 // If the size can be zero, the result will be 0 in that case, and we don't
1040 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001041 if (stateZeroSize) {
1042 state = stateZeroSize;
Ted Kremenek5eca4822012-01-06 22:09:28 +00001043 state = state->BindExpr(CE, LCtx,
1044 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001045 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001046 }
1047
Jordy Rosed325ffb2010-07-08 23:57:29 +00001048 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001049 if (stateNonZeroSize) {
1050 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +00001051 // If we know the two buffers are the same, we know the result is 0.
1052 // First, get the two buffers' addresses. Another checker will have already
1053 // made sure they're not undefined.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001054 DefinedOrUnknownSVal LV =
1055 cast<DefinedOrUnknownSVal>(state->getSVal(Left, LCtx));
1056 DefinedOrUnknownSVal RV =
1057 cast<DefinedOrUnknownSVal>(state->getSVal(Right, LCtx));
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001058
Jordy Rosed325ffb2010-07-08 23:57:29 +00001059 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001060 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001061 ProgramStateRef StSameBuf, StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +00001062 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001063
Jordy Rose1e022412011-06-16 05:51:02 +00001064 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +00001065 // and we only need to check one size.
1066 if (StSameBuf) {
1067 state = StSameBuf;
1068 state = CheckBufferAccess(C, state, Size, Left);
1069 if (state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001070 state = StSameBuf->BindExpr(CE, LCtx,
1071 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001072 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001073 }
1074 }
1075
1076 // If the two arguments might be different buffers, we have to check the
1077 // size of both of them.
1078 if (StNotSameBuf) {
1079 state = StNotSameBuf;
1080 state = CheckBufferAccess(C, state, Size, Left, Right);
1081 if (state) {
1082 // The return value is the comparison result, which we don't know.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001083 SVal CmpV = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001084 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001085 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001086 }
1087 }
1088 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001089}
1090
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001091void CStringChecker::evalstrLength(CheckerContext &C,
1092 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001093 if (CE->getNumArgs() < 1)
1094 return;
1095
Jordy Rose19c5dd12010-07-27 01:37:31 +00001096 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001097 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1098}
1099
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001100void CStringChecker::evalstrnLength(CheckerContext &C,
1101 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001102 if (CE->getNumArgs() < 2)
1103 return;
1104
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001105 // size_t strnlen(const char *s, size_t maxlen);
1106 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1107}
1108
1109void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001110 bool IsStrnlen) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001111 CurrentFunctionDescription = "string length function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001112 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001113 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose793bff32011-06-14 01:15:31 +00001114
1115 if (IsStrnlen) {
1116 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001117 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rose793bff32011-06-14 01:15:31 +00001118
Ted Kremenek8bef8232012-01-26 21:29:00 +00001119 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose793bff32011-06-14 01:15:31 +00001120 llvm::tie(stateZeroSize, stateNonZeroSize) =
1121 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1122
1123 // If the size can be zero, the result will be 0 in that case, and we don't
1124 // have to check the string itself.
1125 if (stateZeroSize) {
1126 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001127 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001128 C.addTransition(stateZeroSize);
Jordy Rose793bff32011-06-14 01:15:31 +00001129 }
1130
1131 // If the size is GUARANTEED to be zero, we're done!
1132 if (!stateNonZeroSize)
1133 return;
1134
1135 // Otherwise, record the assumption that the size is nonzero.
1136 state = stateNonZeroSize;
1137 }
1138
1139 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001140 const Expr *Arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001141 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001142
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001143 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001144
Jordy Rosebd32bee2011-06-14 01:26:48 +00001145 if (!state)
1146 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001147
Jordy Rosebd32bee2011-06-14 01:26:48 +00001148 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001149
Jordy Rosebd32bee2011-06-14 01:26:48 +00001150 // If the argument isn't a valid C string, there's no valid state to
1151 // transition to.
1152 if (strLength.isUndef())
1153 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001154
Jordy Rosebd32bee2011-06-14 01:26:48 +00001155 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001156
Jordy Rosebd32bee2011-06-14 01:26:48 +00001157 // If the check is for strnlen() then bind the return value to no more than
1158 // the maxlen value.
1159 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001160 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001161
Jordy Rosebd32bee2011-06-14 01:26:48 +00001162 // It's a little unfortunate to be getting this again,
1163 // but it's not that expensive...
1164 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001165 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001166
Jordy Rosebd32bee2011-06-14 01:26:48 +00001167 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1168 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001169
Jordy Rosebd32bee2011-06-14 01:26:48 +00001170 if (strLengthNL && maxlenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001171 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001172
Jordy Rosebd32bee2011-06-14 01:26:48 +00001173 // Check if the strLength is greater than the maxlen.
1174 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
1175 state->assume(cast<DefinedOrUnknownSVal>
1176 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1177 *strLengthNL,
1178 *maxlenValNL,
1179 cmpTy)));
Jordy Rose793bff32011-06-14 01:15:31 +00001180
Jordy Rosebd32bee2011-06-14 01:26:48 +00001181 if (stateStringTooLong && !stateStringNotTooLong) {
1182 // If the string is longer than maxlen, return maxlen.
1183 result = *maxlenValNL;
1184 } else if (stateStringNotTooLong && !stateStringTooLong) {
1185 // If the string is shorter than maxlen, return its length.
1186 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001187 }
1188 }
1189
Jordy Rosebd32bee2011-06-14 01:26:48 +00001190 if (result.isUnknown()) {
1191 // If we don't have enough information for a comparison, there's
1192 // no guarantee the full string length will actually be returned.
1193 // All we know is the return value is the min of the string length
1194 // and the limit. This is better than nothing.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001195 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001196 NonLoc *resultNL = cast<NonLoc>(&result);
1197
1198 if (strLengthNL) {
1199 state = state->assume(cast<DefinedOrUnknownSVal>
1200 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1201 *resultNL,
1202 *strLengthNL,
1203 cmpTy)), true);
1204 }
1205
1206 if (maxlenValNL) {
1207 state = state->assume(cast<DefinedOrUnknownSVal>
1208 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1209 *resultNL,
1210 *maxlenValNL,
1211 cmpTy)), true);
1212 }
1213 }
1214
1215 } else {
1216 // This is a plain strlen(), not strnlen().
1217 result = cast<DefinedOrUnknownSVal>(strLength);
1218
1219 // If we don't know the length of the string, conjure a return
1220 // value, so it can be used in constraints, at least.
1221 if (result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001222 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001223 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001224 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001225
1226 // Bind the return value.
1227 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek5eca4822012-01-06 22:09:28 +00001228 state = state->BindExpr(CE, LCtx, result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001229 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001230}
1231
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001232void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001233 if (CE->getNumArgs() < 2)
1234 return;
1235
Jordy Rosee64f3112010-08-16 07:51:42 +00001236 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001237 evalStrcpyCommon(C, CE,
1238 /* returnEnd = */ false,
1239 /* isBounded = */ false,
1240 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001241}
1242
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001243void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001244 if (CE->getNumArgs() < 3)
1245 return;
1246
Jordy Rosec1525862011-06-04 00:05:23 +00001247 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001248 evalStrcpyCommon(C, CE,
1249 /* returnEnd = */ false,
1250 /* isBounded = */ true,
1251 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001252}
1253
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001254void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001255 if (CE->getNumArgs() < 2)
1256 return;
1257
Jordy Rosee64f3112010-08-16 07:51:42 +00001258 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001259 evalStrcpyCommon(C, CE,
1260 /* returnEnd = */ true,
1261 /* isBounded = */ false,
1262 /* isAppending = */ false);
1263}
1264
1265void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001266 if (CE->getNumArgs() < 2)
1267 return;
1268
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001269 //char *strcat(char *restrict s1, const char *restrict s2);
1270 evalStrcpyCommon(C, CE,
1271 /* returnEnd = */ false,
1272 /* isBounded = */ false,
1273 /* isAppending = */ true);
1274}
1275
1276void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001277 if (CE->getNumArgs() < 3)
1278 return;
1279
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001280 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1281 evalStrcpyCommon(C, CE,
1282 /* returnEnd = */ false,
1283 /* isBounded = */ true,
1284 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001285}
1286
Ted Kremenek9c149532010-12-01 21:57:22 +00001287void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001288 bool returnEnd, bool isBounded,
1289 bool isAppending) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001290 CurrentFunctionDescription = "string copy function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001291 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001292 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosee64f3112010-08-16 07:51:42 +00001293
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001294 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001295 const Expr *Dst = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001296 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +00001297
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001298 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001299 if (!state)
1300 return;
1301
1302 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001303 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001304 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001305 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001306 if (!state)
1307 return;
1308
1309 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001310 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001311
1312 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001313 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001314 return;
1315
Jordy Rosed5af0e12011-06-15 05:52:56 +00001316 SValBuilder &svalBuilder = C.getSValBuilder();
1317 QualType cmpTy = svalBuilder.getConditionType();
Jordy Rose8912aae2011-06-20 21:55:40 +00001318 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001319
Jordy Rose8912aae2011-06-20 21:55:40 +00001320 // These two values allow checking two kinds of errors:
1321 // - actual overflows caused by a source that doesn't fit in the destination
1322 // - potential overflows caused by a bound that could exceed the destination
Jordy Rosed5af0e12011-06-15 05:52:56 +00001323 SVal amountCopied = UnknownVal();
Jordy Rose8912aae2011-06-20 21:55:40 +00001324 SVal maxLastElementIndex = UnknownVal();
1325 const char *boundWarning = NULL;
Jordy Rosed5af0e12011-06-15 05:52:56 +00001326
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001327 // If the function is strncpy, strncat, etc... it is bounded.
1328 if (isBounded) {
1329 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001330 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001331 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001332
Jordy Rosed5af0e12011-06-15 05:52:56 +00001333 // Protect against misdeclared strncpy().
Jordy Rose8912aae2011-06-20 21:55:40 +00001334 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001335
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001336 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1337 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1338
Jordy Rosed5af0e12011-06-15 05:52:56 +00001339 // If we know both values, we might be able to figure out how much
1340 // we're copying.
1341 if (strLengthNL && lenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001342 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001343
Jordy Rosed5af0e12011-06-15 05:52:56 +00001344 // Check if the max number to copy is less than the length of the src.
Jordy Rose8912aae2011-06-20 21:55:40 +00001345 // If the bound is equal to the source length, strncpy won't null-
1346 // terminate the result!
Jordy Rosed5af0e12011-06-15 05:52:56 +00001347 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) =
1348 state->assume(cast<DefinedOrUnknownSVal>
Jordy Rose8912aae2011-06-20 21:55:40 +00001349 (svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL,
Jordy Rosed5af0e12011-06-15 05:52:56 +00001350 *lenValNL, cmpTy)));
1351
1352 if (stateSourceTooLong && !stateSourceNotTooLong) {
1353 // Max number to copy is less than the length of the src, so the actual
1354 // strLength copied is the max number arg.
1355 state = stateSourceTooLong;
1356 amountCopied = lenVal;
1357
1358 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1359 // The source buffer entirely fits in the bound.
1360 state = stateSourceNotTooLong;
1361 amountCopied = strLength;
1362 }
1363 }
1364
Jordy Rose5e5f1502011-06-20 03:49:16 +00001365 // We still want to know if the bound is known to be too large.
Jordy Rose8912aae2011-06-20 21:55:40 +00001366 if (lenValNL) {
1367 if (isAppending) {
1368 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1369
1370 // Get the string length of the destination. If the destination is
1371 // memory that can't have a string length, we shouldn't be copying
1372 // into it anyway.
1373 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1374 if (dstStrLength.isUndef())
1375 return;
1376
1377 if (NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength)) {
1378 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1379 *lenValNL,
1380 *dstStrLengthNL,
1381 sizeTy);
1382 boundWarning = "Size argument is greater than the free space in the "
1383 "destination buffer";
1384 }
1385
1386 } else {
1387 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1388 // (Yes, strncpy and strncat differ in how they treat termination.
1389 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose6e4244e2012-05-14 17:58:35 +00001390
1391 // We need a special case for when the copy size is zero, in which
1392 // case strncpy will do no work at all. Our bounds check uses n-1
1393 // as the last element accessed, so n == 0 is problematic.
1394 ProgramStateRef StateZeroSize, StateNonZeroSize;
1395 llvm::tie(StateZeroSize, StateNonZeroSize) =
1396 assumeZero(C, state, *lenValNL, sizeTy);
1397
1398 // If the size is known to be zero, we're done.
1399 if (StateZeroSize && !StateNonZeroSize) {
1400 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1401 C.addTransition(StateZeroSize);
1402 return;
1403 }
1404
1405 // Otherwise, go ahead and figure out the last element we'll touch.
1406 // We don't record the non-zero assumption here because we can't
1407 // be sure. We won't warn on a possible zero.
Jordy Rose8912aae2011-06-20 21:55:40 +00001408 NonLoc one = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
1409 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1410 one, sizeTy);
1411 boundWarning = "Size argument is greater than the length of the "
1412 "destination buffer";
1413 }
1414 }
Jordy Rose5e5f1502011-06-20 03:49:16 +00001415
Jordy Rosed5af0e12011-06-15 05:52:56 +00001416 // If we couldn't pin down the copy length, at least bound it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001417 // FIXME: We should actually run this code path for append as well, but
1418 // right now it creates problems with constraints (since we can end up
1419 // trying to pass constraints from symbol to symbol).
1420 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001421 // Try to get a "hypothetical" string length symbol, which we can later
1422 // set as a real value if that turns out to be the case.
1423 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1424 assert(!amountCopied.isUndef());
1425
1426 if (NonLoc *amountCopiedNL = dyn_cast<NonLoc>(&amountCopied)) {
1427 if (lenValNL) {
1428 // amountCopied <= lenVal
1429 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1430 *amountCopiedNL,
1431 *lenValNL,
1432 cmpTy);
1433 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanBound),
1434 true);
1435 if (!state)
1436 return;
1437 }
1438
1439 if (strLengthNL) {
1440 // amountCopied <= strlen(source)
1441 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1442 *amountCopiedNL,
1443 *strLengthNL,
1444 cmpTy);
1445 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanSrc),
1446 true);
1447 if (!state)
1448 return;
1449 }
1450 }
1451 }
1452
1453 } else {
1454 // The function isn't bounded. The amount copied should match the length
1455 // of the source buffer.
1456 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001457 }
1458
Jordy Rosed5af0e12011-06-15 05:52:56 +00001459 assert(state);
1460
1461 // This represents the number of characters copied into the destination
1462 // buffer. (It may not actually be the strlen if the destination buffer
1463 // is not terminated.)
1464 SVal finalStrLength = UnknownVal();
1465
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001466 // If this is an appending function (strcat, strncat...) then set the
1467 // string length to strlen(src) + strlen(dst) since the buffer will
1468 // ultimately contain both.
1469 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001470 // Get the string length of the destination. If the destination is memory
1471 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001472 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1473 if (dstStrLength.isUndef())
1474 return;
1475
Jordy Rosed5af0e12011-06-15 05:52:56 +00001476 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&amountCopied);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001477 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1478
Jordy Rosed5af0e12011-06-15 05:52:56 +00001479 // If we know both string lengths, we might know the final string length.
1480 if (srcStrLengthNL && dstStrLengthNL) {
1481 // Make sure the two lengths together don't overflow a size_t.
1482 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1483 if (!state)
1484 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001485
Jordy Rosed5af0e12011-06-15 05:52:56 +00001486 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1487 *dstStrLengthNL, sizeTy);
1488 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001489
Jordy Rosed5af0e12011-06-15 05:52:56 +00001490 // If we couldn't get a single value for the final string length,
1491 // we can at least bound it by the individual lengths.
1492 if (finalStrLength.isUnknown()) {
1493 // Try to get a "hypothetical" string length symbol, which we can later
1494 // set as a real value if that turns out to be the case.
1495 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1496 assert(!finalStrLength.isUndef());
1497
1498 if (NonLoc *finalStrLengthNL = dyn_cast<NonLoc>(&finalStrLength)) {
1499 if (srcStrLengthNL) {
1500 // finalStrLength >= srcStrLength
1501 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1502 *finalStrLengthNL,
1503 *srcStrLengthNL,
1504 cmpTy);
1505 state = state->assume(cast<DefinedOrUnknownSVal>(sourceInResult),
1506 true);
1507 if (!state)
1508 return;
1509 }
1510
1511 if (dstStrLengthNL) {
1512 // finalStrLength >= dstStrLength
1513 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1514 *finalStrLengthNL,
1515 *dstStrLengthNL,
1516 cmpTy);
1517 state = state->assume(cast<DefinedOrUnknownSVal>(destInResult),
1518 true);
1519 if (!state)
1520 return;
1521 }
1522 }
1523 }
1524
1525 } else {
1526 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1527 // the final string length will match the input string length.
1528 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001529 }
1530
Jordy Rosed5af0e12011-06-15 05:52:56 +00001531 // The final result of the function will either be a pointer past the last
1532 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001533 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001534
Jordy Rosed5af0e12011-06-15 05:52:56 +00001535 assert(state);
1536
Jordy Rosee64f3112010-08-16 07:51:42 +00001537 // If the destination is a MemRegion, try to check for a buffer overflow and
1538 // record the new string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001539 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001540 QualType ptrTy = Dst->getType();
1541
1542 // If we have an exact value on a bounded copy, use that to check for
1543 // overflows, rather than our estimate about how much is actually copied.
1544 if (boundWarning) {
1545 if (NonLoc *maxLastNL = dyn_cast<NonLoc>(&maxLastElementIndex)) {
1546 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1547 *maxLastNL, ptrTy);
1548 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1549 boundWarning);
1550 if (!state)
1551 return;
1552 }
1553 }
1554
1555 // Then, if the final length is known...
Jordy Rosed5af0e12011-06-15 05:52:56 +00001556 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&finalStrLength)) {
1557 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Rose8912aae2011-06-20 21:55:40 +00001558 *knownStrLength, ptrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +00001559
Jordy Rose8912aae2011-06-20 21:55:40 +00001560 // ...and we haven't checked the bound, we'll check the actual copy.
1561 if (!boundWarning) {
1562 const char * const warningMsg =
1563 "String copy function overflows destination buffer";
1564 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1565 if (!state)
1566 return;
1567 }
Jordy Rosee64f3112010-08-16 07:51:42 +00001568
1569 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001570 if (returnEnd)
1571 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001572 }
1573
1574 // Invalidate the destination. This must happen before we set the C string
1575 // length because invalidation will clear the length.
1576 // FIXME: Even if we can't perfectly model the copy, we should see if we
1577 // can use LazyCompoundVals to copy the source values into the destination.
1578 // This would probably remove any existing bindings past the end of the
1579 // string, but that's still an improvement over blank invalidation.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001580 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001581
Jordy Rose5e5f1502011-06-20 03:49:16 +00001582 // Set the C string length of the destination, if we know it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001583 if (isBounded && !isAppending) {
1584 // strncpy is annoying in that it doesn't guarantee to null-terminate
1585 // the result string. If the original string didn't fit entirely inside
1586 // the bound (including the null-terminator), we don't know how long the
1587 // result is.
1588 if (amountCopied != strLength)
1589 finalStrLength = UnknownVal();
1590 }
1591 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001592 }
1593
Jordy Rosed5af0e12011-06-15 05:52:56 +00001594 assert(state);
1595
Jordy Rosee64f3112010-08-16 07:51:42 +00001596 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1597 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001598 if (returnEnd && Result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001599 Result = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosee64f3112010-08-16 07:51:42 +00001600 }
1601
1602 // Set the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001603 state = state->BindExpr(CE, LCtx, Result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001604 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +00001605}
1606
Lenny Maiorani318dd922011-04-12 17:08:43 +00001607void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001608 if (CE->getNumArgs() < 2)
1609 return;
1610
Jordy Roseadc42d42011-06-16 07:13:34 +00001611 //int strcmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001612 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001613}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001614
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001615void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001616 if (CE->getNumArgs() < 3)
1617 return;
1618
Jordy Roseadc42d42011-06-16 07:13:34 +00001619 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001620 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1621}
1622
1623void CStringChecker::evalStrcasecmp(CheckerContext &C,
1624 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001625 if (CE->getNumArgs() < 2)
1626 return;
1627
Jordy Roseadc42d42011-06-16 07:13:34 +00001628 //int strcasecmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001629 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001630}
1631
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001632void CStringChecker::evalStrncasecmp(CheckerContext &C,
1633 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001634 if (CE->getNumArgs() < 3)
1635 return;
1636
Jordy Roseadc42d42011-06-16 07:13:34 +00001637 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001638 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1639}
1640
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001641void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001642 bool isBounded, bool ignoreCase) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001643 CurrentFunctionDescription = "string comparison function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001644 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001645 const LocationContext *LCtx = C.getLocationContext();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001646
1647 // Check that the first string is non-null
1648 const Expr *s1 = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001649 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001650 state = checkNonNull(C, state, s1, s1Val);
1651 if (!state)
1652 return;
1653
1654 // Check that the second string is non-null.
1655 const Expr *s2 = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001656 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001657 state = checkNonNull(C, state, s2, s2Val);
1658 if (!state)
1659 return;
1660
1661 // Get the string length of the first string or give up.
1662 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1663 if (s1Length.isUndef())
1664 return;
1665
1666 // Get the string length of the second string or give up.
1667 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1668 if (s2Length.isUndef())
1669 return;
1670
Jordy Roseadc42d42011-06-16 07:13:34 +00001671 // If we know the two buffers are the same, we know the result is 0.
1672 // First, get the two buffers' addresses. Another checker will have already
1673 // made sure they're not undefined.
1674 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(s1Val);
1675 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(s2Val);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001676
Jordy Roseadc42d42011-06-16 07:13:34 +00001677 // See if they are the same.
Lenny Maiorani318dd922011-04-12 17:08:43 +00001678 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseadc42d42011-06-16 07:13:34 +00001679 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001680 ProgramStateRef StSameBuf, StNotSameBuf;
Jordy Roseadc42d42011-06-16 07:13:34 +00001681 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001682
Jordy Roseadc42d42011-06-16 07:13:34 +00001683 // If the two arguments might be the same buffer, we know the result is 0,
1684 // and we only need to check one size.
1685 if (StSameBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001686 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1687 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001688 C.addTransition(StSameBuf);
Jordy Roseadc42d42011-06-16 07:13:34 +00001689
1690 // If the two arguments are GUARANTEED to be the same, we're done!
1691 if (!StNotSameBuf)
1692 return;
1693 }
1694
1695 assert(StNotSameBuf);
1696 state = StNotSameBuf;
1697
1698 // At this point we can go about comparing the two buffers.
1699 // For now, we only do this if they're both known string literals.
1700
1701 // Attempt to extract string literals from both expressions.
1702 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1703 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1704 bool canComputeResult = false;
1705
1706 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001707 StringRef s1StrRef = s1StrLiteral->getString();
1708 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Roseadc42d42011-06-16 07:13:34 +00001709
1710 if (isBounded) {
1711 // Get the max number of characters to compare.
1712 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001713 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Roseadc42d42011-06-16 07:13:34 +00001714
1715 // If the length is known, we can get the right substrings.
1716 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1717 // Create substrings of each to compare the prefix.
1718 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1719 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1720 canComputeResult = true;
1721 }
1722 } else {
1723 // This is a normal, unbounded strcmp.
1724 canComputeResult = true;
1725 }
1726
1727 if (canComputeResult) {
1728 // Real strcmp stops at null characters.
1729 size_t s1Term = s1StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001730 if (s1Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001731 s1StrRef = s1StrRef.substr(0, s1Term);
1732
1733 size_t s2Term = s2StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001734 if (s2Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001735 s2StrRef = s2StrRef.substr(0, s2Term);
1736
1737 // Use StringRef's comparison methods to compute the actual result.
1738 int result;
1739
1740 if (ignoreCase) {
1741 // Compare string 1 to string 2 the same way strcasecmp() does.
1742 result = s1StrRef.compare_lower(s2StrRef);
1743 } else {
1744 // Compare string 1 to string 2 the same way strcmp() does.
1745 result = s1StrRef.compare(s2StrRef);
1746 }
1747
1748 // Build the SVal of the comparison and bind the return value.
1749 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001750 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001751 }
1752 }
1753
1754 if (!canComputeResult) {
1755 // Conjure a symbolic value. It's the best we can do.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001756 SVal resultVal = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001757 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001758 }
1759
1760 // Record this as a possible path.
Anna Zaks0bd6b112011-10-26 21:06:34 +00001761 C.addTransition(state);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001762}
1763
Jordy Rosed325ffb2010-07-08 23:57:29 +00001764//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001765// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001766//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001767
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001768bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks998e2752012-02-17 22:35:26 +00001769 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1770
1771 if (!FDecl)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001772 return false;
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001773
Anna Zaks998e2752012-02-17 22:35:26 +00001774 FnCheck evalFunction = 0;
1775 if (C.isCLibraryFunction(FDecl, "memcpy"))
1776 evalFunction = &CStringChecker::evalMemcpy;
1777 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1778 evalFunction = &CStringChecker::evalMempcpy;
1779 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1780 evalFunction = &CStringChecker::evalMemcmp;
1781 else if (C.isCLibraryFunction(FDecl, "memmove"))
1782 evalFunction = &CStringChecker::evalMemmove;
1783 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1784 evalFunction = &CStringChecker::evalStrcpy;
1785 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1786 evalFunction = &CStringChecker::evalStrncpy;
1787 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1788 evalFunction = &CStringChecker::evalStpcpy;
1789 else if (C.isCLibraryFunction(FDecl, "strcat"))
1790 evalFunction = &CStringChecker::evalStrcat;
1791 else if (C.isCLibraryFunction(FDecl, "strncat"))
1792 evalFunction = &CStringChecker::evalStrncat;
1793 else if (C.isCLibraryFunction(FDecl, "strlen"))
1794 evalFunction = &CStringChecker::evalstrLength;
1795 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1796 evalFunction = &CStringChecker::evalstrnLength;
1797 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1798 evalFunction = &CStringChecker::evalStrcmp;
1799 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1800 evalFunction = &CStringChecker::evalStrncmp;
1801 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1802 evalFunction = &CStringChecker::evalStrcasecmp;
1803 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1804 evalFunction = &CStringChecker::evalStrncasecmp;
1805 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1806 evalFunction = &CStringChecker::evalBcopy;
1807 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1808 evalFunction = &CStringChecker::evalMemcmp;
1809
Jordy Rosed325ffb2010-07-08 23:57:29 +00001810 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001811 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001812 return false;
1813
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001814 // Make sure each function sets its own description.
1815 // (But don't bother in a release build.)
1816 assert(!(CurrentFunctionDescription = NULL));
1817
Jordy Rosed325ffb2010-07-08 23:57:29 +00001818 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001819 (this->*evalFunction)(C, CE);
Anna Zaks57300762012-02-07 00:56:14 +00001820
1821 // If the evaluate call resulted in no change, chain to the next eval call
1822 // handler.
1823 // Note, the custom CString evaluation calls assume that basic safety
1824 // properties are held. However, if the user chooses to turn off some of these
1825 // checks, we ignore the issues and leave the call evaluation to a generic
1826 // handler.
1827 if (!C.isDifferent())
1828 return false;
1829
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001830 return true;
1831}
Jordy Rosea5261542010-08-14 21:02:52 +00001832
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001833void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001834 // Record string length for char a[] = "abc";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001835 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001836
1837 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1838 I != E; ++I) {
1839 const VarDecl *D = dyn_cast<VarDecl>(*I);
1840 if (!D)
1841 continue;
1842
1843 // FIXME: Handle array fields of structs.
1844 if (!D->getType()->isArrayType())
1845 continue;
1846
1847 const Expr *Init = D->getInit();
1848 if (!Init)
1849 continue;
1850 if (!isa<StringLiteral>(Init))
1851 continue;
1852
Anna Zaks39ac1872011-10-26 21:06:44 +00001853 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001854 const MemRegion *MR = VarLoc.getAsRegion();
1855 if (!MR)
1856 continue;
1857
Ted Kremenek5eca4822012-01-06 22:09:28 +00001858 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001859 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001860 DefinedOrUnknownSVal strLength
1861 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rosea5261542010-08-14 21:02:52 +00001862
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001863 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001864 }
1865
Anna Zaks0bd6b112011-10-26 21:06:34 +00001866 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001867}
1868
Ted Kremenek8bef8232012-01-26 21:29:00 +00001869bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001870 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001871 return !Entries.isEmpty();
1872}
1873
Ted Kremenek8bef8232012-01-26 21:29:00 +00001874ProgramStateRef
1875CStringChecker::checkRegionChanges(ProgramStateRef state,
Ted Kremenek35bdbf42011-05-02 19:42:42 +00001876 const StoreManager::InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +00001877 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001878 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001879 const CallEvent *Call) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001880 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001881 if (Entries.isEmpty())
1882 return state;
1883
1884 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1885 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1886
1887 // First build sets for the changed regions and their super-regions.
Jordy Rose537716a2011-08-27 22:51:26 +00001888 for (ArrayRef<const MemRegion *>::iterator
1889 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1890 const MemRegion *MR = *I;
Jordy Rosea5261542010-08-14 21:02:52 +00001891 Invalidated.insert(MR);
1892
1893 SuperRegions.insert(MR);
1894 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1895 MR = SR->getSuperRegion();
1896 SuperRegions.insert(MR);
1897 }
1898 }
1899
Jordan Rose166d5022012-11-02 01:54:06 +00001900 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001901
1902 // Then loop over the entries in the current state.
Jordan Rose166d5022012-11-02 01:54:06 +00001903 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rosea5261542010-08-14 21:02:52 +00001904 E = Entries.end(); I != E; ++I) {
1905 const MemRegion *MR = I.getKey();
1906
1907 // Is this entry for a super-region of a changed region?
1908 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001909 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001910 continue;
1911 }
1912
1913 // Is this entry for a sub-region of a changed region?
1914 const MemRegion *Super = MR;
1915 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1916 Super = SR->getSuperRegion();
1917 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001918 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001919 break;
1920 }
1921 }
1922 }
1923
1924 return state->set<CStringLength>(Entries);
1925}
1926
Ted Kremenek8bef8232012-01-26 21:29:00 +00001927void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001928 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001929 // Mark all symbols in our string length map as valid.
Jordan Rose166d5022012-11-02 01:54:06 +00001930 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001931
Jordan Rose166d5022012-11-02 01:54:06 +00001932 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00001933 I != E; ++I) {
1934 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001935
Anna Zaks1d1d5152011-12-06 23:12:33 +00001936 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
1937 se = Len.symbol_end(); si != se; ++si)
Jordy Rosed5af0e12011-06-15 05:52:56 +00001938 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00001939 }
1940}
1941
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001942void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1943 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001944 if (!SR.hasDeadSymbols())
1945 return;
1946
Ted Kremenek8bef8232012-01-26 21:29:00 +00001947 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00001948 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001949 if (Entries.isEmpty())
1950 return;
1951
Jordan Rose166d5022012-11-02 01:54:06 +00001952 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
1953 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00001954 I != E; ++I) {
1955 SVal Len = I.getData();
1956 if (SymbolRef Sym = Len.getAsSymbol()) {
1957 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00001958 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00001959 }
1960 }
1961
1962 state = state->set<CStringLength>(Entries);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001963 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001964}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001965
Anna Zaks57300762012-02-07 00:56:14 +00001966#define REGISTER_CHECKER(name) \
1967void ento::register##name(CheckerManager &mgr) {\
1968 static CStringChecker *TheChecker = 0; \
1969 if (TheChecker == 0) \
1970 TheChecker = mgr.registerChecker<CStringChecker>(); \
1971 TheChecker->Filter.Check##name = true; \
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001972}
Anna Zaks57300762012-02-07 00:56:14 +00001973
1974REGISTER_CHECKER(CStringNullArg)
1975REGISTER_CHECKER(CStringOutOfBounds)
1976REGISTER_CHECKER(CStringBufferOverlap)
1977REGISTER_CHECKER(CStringNotNullTerm)
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001978
1979void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
1980 registerCStringNullArg(Mgr);
1981}