blob: 9fbf97641f396aad8c11de9f0961624d51ead83f [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000018#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000019#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000022#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "llvm/ADT/SmallString.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,
Anna Zaksbf53dfa2012-12-20 00:38:25 +000067 const 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();
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000819 return state->invalidateRegions(R, E, C.blockCount(), LCtx,
820 /*ResultsInPointerEscape*/ false);
Jordy Rosee64f3112010-08-16 07:51:42 +0000821 }
822
823 // If we have a non-region value by chance, just remove the binding.
824 // FIXME: is this necessary or correct? This handles the non-Region
825 // cases. Is it ever valid to store to these?
Ted Kremenek56a46b52012-08-22 06:37:46 +0000826 return state->killBinding(*L);
Jordy Rosee64f3112010-08-16 07:51:42 +0000827}
828
Ted Kremenek9c378f72011-08-12 23:37:29 +0000829bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000830 const MemRegion *MR) {
Ted Kremenek96979342011-08-12 20:02:48 +0000831 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000832
Jordy Rose096aef92011-08-12 21:41:07 +0000833 switch (MR->getKind()) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000834 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000835 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000836 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000837 os << "the address of the function '" << *FD << '\'';
Jordy Rose19c5dd12010-07-27 01:37:31 +0000838 else
839 os << "the address of a function";
840 return true;
841 }
842 case MemRegion::BlockTextRegionKind:
843 os << "block text";
844 return true;
845 case MemRegion::BlockDataRegionKind:
846 os << "a block";
847 return true;
848 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000849 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000850 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000851 return true;
852 case MemRegion::VarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000853 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000854 return true;
855 case MemRegion::FieldRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000856 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000857 return true;
858 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000859 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000860 return true;
861 default:
862 return false;
863 }
864}
865
Jordy Rosed325ffb2010-07-08 23:57:29 +0000866//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000867// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000868//===----------------------------------------------------------------------===//
869
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000870void CStringChecker::evalCopyCommon(CheckerContext &C,
871 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000872 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000873 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000874 const Expr *Source, bool Restricted,
875 bool IsMempcpy) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000876 CurrentFunctionDescription = "memory copy function";
877
Jordy Rosed325ffb2010-07-08 23:57:29 +0000878 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000879 const LocationContext *LCtx = C.getLocationContext();
880 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000881 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000882
Ted Kremenek8bef8232012-01-26 21:29:00 +0000883 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose1e022412011-06-16 05:51:02 +0000884 llvm::tie(stateZeroSize, stateNonZeroSize) =
885 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000886
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000887 // Get the value of the Dest.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000888 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000889
890 // If the size is zero, there won't be any actual memory access, so
891 // just bind the return value to the destination buffer and return.
Anna Zaksdd160f32012-05-03 18:21:28 +0000892 if (stateZeroSize && !stateNonZeroSize) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000893 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000894 C.addTransition(stateZeroSize);
Anna Zaksdd160f32012-05-03 18:21:28 +0000895 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000896 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000897
898 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000899 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000900 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000901
902 // Ensure the destination is not null. If it is NULL there will be a
903 // NULL pointer dereference.
904 state = checkNonNull(C, state, Dest, destVal);
905 if (!state)
906 return;
907
908 // Get the value of the Src.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000909 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000910
911 // Ensure the source is not null. If it is NULL there will be a
912 // NULL pointer dereference.
913 state = checkNonNull(C, state, Source, srcVal);
914 if (!state)
915 return;
916
Jordy Rose7182b962011-06-04 01:50:25 +0000917 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000918 const char * const writeWarning =
919 "Memory copy function overflows destination buffer";
Jordy Rosee64f3112010-08-16 07:51:42 +0000920 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000921 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000922 if (Restricted)
923 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000924
Jordy Rose7182b962011-06-04 01:50:25 +0000925 if (!state)
926 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000927
Jordy Rose7182b962011-06-04 01:50:25 +0000928 // If this is mempcpy, get the byte after the last byte copied and
929 // bind the expr.
930 if (IsMempcpy) {
931 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
932 assert(destRegVal && "Destination should be a known MemRegionVal here");
933
934 // Get the length to copy.
935 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
936
937 if (lenValNonLoc) {
938 // Get the byte after the last byte copied.
939 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
940 *destRegVal,
941 *lenValNonLoc,
942 Dest->getType());
943
944 // The byte after the last byte copied is the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000945 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000946 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000947 // If we don't know how much we copied, we can at least
948 // conjure a return value for later.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000949 SVal result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx,
950 C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +0000951 state = state->BindExpr(CE, LCtx, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000952 }
953
Jordy Rose7182b962011-06-04 01:50:25 +0000954 } else {
955 // All other copies return the destination buffer.
956 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000957 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000958 }
Jordy Rose7182b962011-06-04 01:50:25 +0000959
960 // Invalidate the destination.
961 // FIXME: Even if we can't perfectly model the copy, we should see if we
962 // can use LazyCompoundVals to copy the source values into the destination.
963 // This would probably remove any existing bindings past the end of the
964 // copied region, but that's still an improvement over blank invalidation.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000965 state = InvalidateBuffer(C, state, Dest,
966 state->getSVal(Dest, C.getLocationContext()));
Anna Zaks0bd6b112011-10-26 21:06:34 +0000967 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000968 }
969}
970
971
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000972void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000973 if (CE->getNumArgs() < 3)
974 return;
975
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000976 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000977 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000978 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000979 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000980
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000981 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
982}
983
984void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000985 if (CE->getNumArgs() < 3)
986 return;
987
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000988 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
989 // The return value is a pointer to the byte following the last written byte.
990 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000991 ProgramStateRef state = C.getState();
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000992
993 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000994}
995
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000996void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000997 if (CE->getNumArgs() < 3)
998 return;
999
Jordy Rosed325ffb2010-07-08 23:57:29 +00001000 // void *memmove(void *dst, const void *src, size_t n);
1001 // The return value is the address of the destination buffer.
1002 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001003 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001004
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001005 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001006}
1007
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001008void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001009 if (CE->getNumArgs() < 3)
1010 return;
1011
Jordy Rosed325ffb2010-07-08 23:57:29 +00001012 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001013 evalCopyCommon(C, CE, C.getState(),
1014 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001015}
1016
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001017void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001018 if (CE->getNumArgs() < 3)
1019 return;
1020
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001021 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001022 CurrentFunctionDescription = "memory comparison function";
1023
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001024 const Expr *Left = CE->getArg(0);
1025 const Expr *Right = CE->getArg(1);
1026 const Expr *Size = CE->getArg(2);
1027
Ted Kremenek8bef8232012-01-26 21:29:00 +00001028 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001029 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001030
Jordy Rosed325ffb2010-07-08 23:57:29 +00001031 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001032 const LocationContext *LCtx = C.getLocationContext();
1033 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001034 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001035
Ted Kremenek8bef8232012-01-26 21:29:00 +00001036 ProgramStateRef stateZeroSize, stateNonZeroSize;
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001037 llvm::tie(stateZeroSize, stateNonZeroSize) =
1038 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001039
Jordy Rosed325ffb2010-07-08 23:57:29 +00001040 // If the size can be zero, the result will be 0 in that case, and we don't
1041 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001042 if (stateZeroSize) {
1043 state = stateZeroSize;
Ted Kremenek5eca4822012-01-06 22:09:28 +00001044 state = state->BindExpr(CE, LCtx,
1045 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001046 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001047 }
1048
Jordy Rosed325ffb2010-07-08 23:57:29 +00001049 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001050 if (stateNonZeroSize) {
1051 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +00001052 // If we know the two buffers are the same, we know the result is 0.
1053 // First, get the two buffers' addresses. Another checker will have already
1054 // made sure they're not undefined.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001055 DefinedOrUnknownSVal LV =
1056 cast<DefinedOrUnknownSVal>(state->getSVal(Left, LCtx));
1057 DefinedOrUnknownSVal RV =
1058 cast<DefinedOrUnknownSVal>(state->getSVal(Right, LCtx));
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001059
Jordy Rosed325ffb2010-07-08 23:57:29 +00001060 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001061 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001062 ProgramStateRef StSameBuf, StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +00001063 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001064
Jordy Rose1e022412011-06-16 05:51:02 +00001065 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +00001066 // and we only need to check one size.
1067 if (StSameBuf) {
1068 state = StSameBuf;
1069 state = CheckBufferAccess(C, state, Size, Left);
1070 if (state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001071 state = StSameBuf->BindExpr(CE, LCtx,
1072 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001073 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001074 }
1075 }
1076
1077 // If the two arguments might be different buffers, we have to check the
1078 // size of both of them.
1079 if (StNotSameBuf) {
1080 state = StNotSameBuf;
1081 state = CheckBufferAccess(C, state, Size, Left, Right);
1082 if (state) {
1083 // The return value is the comparison result, which we don't know.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001084 SVal CmpV = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001085 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001086 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001087 }
1088 }
1089 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001090}
1091
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001092void CStringChecker::evalstrLength(CheckerContext &C,
1093 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001094 if (CE->getNumArgs() < 1)
1095 return;
1096
Jordy Rose19c5dd12010-07-27 01:37:31 +00001097 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001098 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1099}
1100
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001101void CStringChecker::evalstrnLength(CheckerContext &C,
1102 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001103 if (CE->getNumArgs() < 2)
1104 return;
1105
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001106 // size_t strnlen(const char *s, size_t maxlen);
1107 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1108}
1109
1110void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001111 bool IsStrnlen) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001112 CurrentFunctionDescription = "string length function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001113 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001114 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose793bff32011-06-14 01:15:31 +00001115
1116 if (IsStrnlen) {
1117 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001118 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rose793bff32011-06-14 01:15:31 +00001119
Ted Kremenek8bef8232012-01-26 21:29:00 +00001120 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose793bff32011-06-14 01:15:31 +00001121 llvm::tie(stateZeroSize, stateNonZeroSize) =
1122 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1123
1124 // If the size can be zero, the result will be 0 in that case, and we don't
1125 // have to check the string itself.
1126 if (stateZeroSize) {
1127 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001128 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001129 C.addTransition(stateZeroSize);
Jordy Rose793bff32011-06-14 01:15:31 +00001130 }
1131
1132 // If the size is GUARANTEED to be zero, we're done!
1133 if (!stateNonZeroSize)
1134 return;
1135
1136 // Otherwise, record the assumption that the size is nonzero.
1137 state = stateNonZeroSize;
1138 }
1139
1140 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001141 const Expr *Arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001142 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001143
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001144 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001145
Jordy Rosebd32bee2011-06-14 01:26:48 +00001146 if (!state)
1147 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001148
Jordy Rosebd32bee2011-06-14 01:26:48 +00001149 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001150
Jordy Rosebd32bee2011-06-14 01:26:48 +00001151 // If the argument isn't a valid C string, there's no valid state to
1152 // transition to.
1153 if (strLength.isUndef())
1154 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001155
Jordy Rosebd32bee2011-06-14 01:26:48 +00001156 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001157
Jordy Rosebd32bee2011-06-14 01:26:48 +00001158 // If the check is for strnlen() then bind the return value to no more than
1159 // the maxlen value.
1160 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001161 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001162
Jordy Rosebd32bee2011-06-14 01:26:48 +00001163 // It's a little unfortunate to be getting this again,
1164 // but it's not that expensive...
1165 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001166 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001167
Jordy Rosebd32bee2011-06-14 01:26:48 +00001168 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1169 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001170
Jordy Rosebd32bee2011-06-14 01:26:48 +00001171 if (strLengthNL && maxlenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001172 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001173
Jordy Rosebd32bee2011-06-14 01:26:48 +00001174 // Check if the strLength is greater than the maxlen.
1175 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
1176 state->assume(cast<DefinedOrUnknownSVal>
1177 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1178 *strLengthNL,
1179 *maxlenValNL,
1180 cmpTy)));
Jordy Rose793bff32011-06-14 01:15:31 +00001181
Jordy Rosebd32bee2011-06-14 01:26:48 +00001182 if (stateStringTooLong && !stateStringNotTooLong) {
1183 // If the string is longer than maxlen, return maxlen.
1184 result = *maxlenValNL;
1185 } else if (stateStringNotTooLong && !stateStringTooLong) {
1186 // If the string is shorter than maxlen, return its length.
1187 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001188 }
1189 }
1190
Jordy Rosebd32bee2011-06-14 01:26:48 +00001191 if (result.isUnknown()) {
1192 // If we don't have enough information for a comparison, there's
1193 // no guarantee the full string length will actually be returned.
1194 // All we know is the return value is the min of the string length
1195 // and the limit. This is better than nothing.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001196 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001197 NonLoc *resultNL = cast<NonLoc>(&result);
1198
1199 if (strLengthNL) {
1200 state = state->assume(cast<DefinedOrUnknownSVal>
1201 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1202 *resultNL,
1203 *strLengthNL,
1204 cmpTy)), true);
1205 }
1206
1207 if (maxlenValNL) {
1208 state = state->assume(cast<DefinedOrUnknownSVal>
1209 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1210 *resultNL,
1211 *maxlenValNL,
1212 cmpTy)), true);
1213 }
1214 }
1215
1216 } else {
1217 // This is a plain strlen(), not strnlen().
1218 result = cast<DefinedOrUnknownSVal>(strLength);
1219
1220 // If we don't know the length of the string, conjure a return
1221 // value, so it can be used in constraints, at least.
1222 if (result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001223 result = C.getSValBuilder().conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosebd32bee2011-06-14 01:26:48 +00001224 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001225 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001226
1227 // Bind the return value.
1228 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek5eca4822012-01-06 22:09:28 +00001229 state = state->BindExpr(CE, LCtx, result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001230 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001231}
1232
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001233void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001234 if (CE->getNumArgs() < 2)
1235 return;
1236
Jordy Rosee64f3112010-08-16 07:51:42 +00001237 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001238 evalStrcpyCommon(C, CE,
1239 /* returnEnd = */ false,
1240 /* isBounded = */ false,
1241 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001242}
1243
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001244void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001245 if (CE->getNumArgs() < 3)
1246 return;
1247
Jordy Rosec1525862011-06-04 00:05:23 +00001248 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001249 evalStrcpyCommon(C, CE,
1250 /* returnEnd = */ false,
1251 /* isBounded = */ true,
1252 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001253}
1254
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001255void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001256 if (CE->getNumArgs() < 2)
1257 return;
1258
Jordy Rosee64f3112010-08-16 07:51:42 +00001259 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001260 evalStrcpyCommon(C, CE,
1261 /* returnEnd = */ true,
1262 /* isBounded = */ false,
1263 /* isAppending = */ false);
1264}
1265
1266void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001267 if (CE->getNumArgs() < 2)
1268 return;
1269
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001270 //char *strcat(char *restrict s1, const char *restrict s2);
1271 evalStrcpyCommon(C, CE,
1272 /* returnEnd = */ false,
1273 /* isBounded = */ false,
1274 /* isAppending = */ true);
1275}
1276
1277void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001278 if (CE->getNumArgs() < 3)
1279 return;
1280
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001281 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1282 evalStrcpyCommon(C, CE,
1283 /* returnEnd = */ false,
1284 /* isBounded = */ true,
1285 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001286}
1287
Ted Kremenek9c149532010-12-01 21:57:22 +00001288void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001289 bool returnEnd, bool isBounded,
1290 bool isAppending) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001291 CurrentFunctionDescription = "string copy function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001292 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001293 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosee64f3112010-08-16 07:51:42 +00001294
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001295 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001296 const Expr *Dst = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001297 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +00001298
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001299 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001300 if (!state)
1301 return;
1302
1303 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001304 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001305 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001306 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001307 if (!state)
1308 return;
1309
1310 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001311 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001312
1313 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001314 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001315 return;
1316
Jordy Rosed5af0e12011-06-15 05:52:56 +00001317 SValBuilder &svalBuilder = C.getSValBuilder();
1318 QualType cmpTy = svalBuilder.getConditionType();
Jordy Rose8912aae2011-06-20 21:55:40 +00001319 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001320
Jordy Rose8912aae2011-06-20 21:55:40 +00001321 // These two values allow checking two kinds of errors:
1322 // - actual overflows caused by a source that doesn't fit in the destination
1323 // - potential overflows caused by a bound that could exceed the destination
Jordy Rosed5af0e12011-06-15 05:52:56 +00001324 SVal amountCopied = UnknownVal();
Jordy Rose8912aae2011-06-20 21:55:40 +00001325 SVal maxLastElementIndex = UnknownVal();
1326 const char *boundWarning = NULL;
Jordy Rosed5af0e12011-06-15 05:52:56 +00001327
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001328 // If the function is strncpy, strncat, etc... it is bounded.
1329 if (isBounded) {
1330 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001331 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001332 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001333
Jordy Rosed5af0e12011-06-15 05:52:56 +00001334 // Protect against misdeclared strncpy().
Jordy Rose8912aae2011-06-20 21:55:40 +00001335 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001336
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001337 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1338 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1339
Jordy Rosed5af0e12011-06-15 05:52:56 +00001340 // If we know both values, we might be able to figure out how much
1341 // we're copying.
1342 if (strLengthNL && lenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001343 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001344
Jordy Rosed5af0e12011-06-15 05:52:56 +00001345 // Check if the max number to copy is less than the length of the src.
Jordy Rose8912aae2011-06-20 21:55:40 +00001346 // If the bound is equal to the source length, strncpy won't null-
1347 // terminate the result!
Jordy Rosed5af0e12011-06-15 05:52:56 +00001348 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) =
1349 state->assume(cast<DefinedOrUnknownSVal>
Jordy Rose8912aae2011-06-20 21:55:40 +00001350 (svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL,
Jordy Rosed5af0e12011-06-15 05:52:56 +00001351 *lenValNL, cmpTy)));
1352
1353 if (stateSourceTooLong && !stateSourceNotTooLong) {
1354 // Max number to copy is less than the length of the src, so the actual
1355 // strLength copied is the max number arg.
1356 state = stateSourceTooLong;
1357 amountCopied = lenVal;
1358
1359 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1360 // The source buffer entirely fits in the bound.
1361 state = stateSourceNotTooLong;
1362 amountCopied = strLength;
1363 }
1364 }
1365
Jordy Rose5e5f1502011-06-20 03:49:16 +00001366 // We still want to know if the bound is known to be too large.
Jordy Rose8912aae2011-06-20 21:55:40 +00001367 if (lenValNL) {
1368 if (isAppending) {
1369 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1370
1371 // Get the string length of the destination. If the destination is
1372 // memory that can't have a string length, we shouldn't be copying
1373 // into it anyway.
1374 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1375 if (dstStrLength.isUndef())
1376 return;
1377
1378 if (NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength)) {
1379 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1380 *lenValNL,
1381 *dstStrLengthNL,
1382 sizeTy);
1383 boundWarning = "Size argument is greater than the free space in the "
1384 "destination buffer";
1385 }
1386
1387 } else {
1388 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1389 // (Yes, strncpy and strncat differ in how they treat termination.
1390 // strncat ALWAYS terminates, but strncpy doesn't.)
Jordy Rose6e4244e2012-05-14 17:58:35 +00001391
1392 // We need a special case for when the copy size is zero, in which
1393 // case strncpy will do no work at all. Our bounds check uses n-1
1394 // as the last element accessed, so n == 0 is problematic.
1395 ProgramStateRef StateZeroSize, StateNonZeroSize;
1396 llvm::tie(StateZeroSize, StateNonZeroSize) =
1397 assumeZero(C, state, *lenValNL, sizeTy);
1398
1399 // If the size is known to be zero, we're done.
1400 if (StateZeroSize && !StateNonZeroSize) {
1401 StateZeroSize = StateZeroSize->BindExpr(CE, LCtx, DstVal);
1402 C.addTransition(StateZeroSize);
1403 return;
1404 }
1405
1406 // Otherwise, go ahead and figure out the last element we'll touch.
1407 // We don't record the non-zero assumption here because we can't
1408 // be sure. We won't warn on a possible zero.
Jordy Rose8912aae2011-06-20 21:55:40 +00001409 NonLoc one = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
1410 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1411 one, sizeTy);
1412 boundWarning = "Size argument is greater than the length of the "
1413 "destination buffer";
1414 }
1415 }
Jordy Rose5e5f1502011-06-20 03:49:16 +00001416
Jordy Rosed5af0e12011-06-15 05:52:56 +00001417 // If we couldn't pin down the copy length, at least bound it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001418 // FIXME: We should actually run this code path for append as well, but
1419 // right now it creates problems with constraints (since we can end up
1420 // trying to pass constraints from symbol to symbol).
1421 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001422 // Try to get a "hypothetical" string length symbol, which we can later
1423 // set as a real value if that turns out to be the case.
1424 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1425 assert(!amountCopied.isUndef());
1426
1427 if (NonLoc *amountCopiedNL = dyn_cast<NonLoc>(&amountCopied)) {
1428 if (lenValNL) {
1429 // amountCopied <= lenVal
1430 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1431 *amountCopiedNL,
1432 *lenValNL,
1433 cmpTy);
1434 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanBound),
1435 true);
1436 if (!state)
1437 return;
1438 }
1439
1440 if (strLengthNL) {
1441 // amountCopied <= strlen(source)
1442 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1443 *amountCopiedNL,
1444 *strLengthNL,
1445 cmpTy);
1446 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanSrc),
1447 true);
1448 if (!state)
1449 return;
1450 }
1451 }
1452 }
1453
1454 } else {
1455 // The function isn't bounded. The amount copied should match the length
1456 // of the source buffer.
1457 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001458 }
1459
Jordy Rosed5af0e12011-06-15 05:52:56 +00001460 assert(state);
1461
1462 // This represents the number of characters copied into the destination
1463 // buffer. (It may not actually be the strlen if the destination buffer
1464 // is not terminated.)
1465 SVal finalStrLength = UnknownVal();
1466
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001467 // If this is an appending function (strcat, strncat...) then set the
1468 // string length to strlen(src) + strlen(dst) since the buffer will
1469 // ultimately contain both.
1470 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001471 // Get the string length of the destination. If the destination is memory
1472 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001473 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1474 if (dstStrLength.isUndef())
1475 return;
1476
Jordy Rosed5af0e12011-06-15 05:52:56 +00001477 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&amountCopied);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001478 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1479
Jordy Rosed5af0e12011-06-15 05:52:56 +00001480 // If we know both string lengths, we might know the final string length.
1481 if (srcStrLengthNL && dstStrLengthNL) {
1482 // Make sure the two lengths together don't overflow a size_t.
1483 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1484 if (!state)
1485 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001486
Jordy Rosed5af0e12011-06-15 05:52:56 +00001487 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1488 *dstStrLengthNL, sizeTy);
1489 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001490
Jordy Rosed5af0e12011-06-15 05:52:56 +00001491 // If we couldn't get a single value for the final string length,
1492 // we can at least bound it by the individual lengths.
1493 if (finalStrLength.isUnknown()) {
1494 // Try to get a "hypothetical" string length symbol, which we can later
1495 // set as a real value if that turns out to be the case.
1496 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1497 assert(!finalStrLength.isUndef());
1498
1499 if (NonLoc *finalStrLengthNL = dyn_cast<NonLoc>(&finalStrLength)) {
1500 if (srcStrLengthNL) {
1501 // finalStrLength >= srcStrLength
1502 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1503 *finalStrLengthNL,
1504 *srcStrLengthNL,
1505 cmpTy);
1506 state = state->assume(cast<DefinedOrUnknownSVal>(sourceInResult),
1507 true);
1508 if (!state)
1509 return;
1510 }
1511
1512 if (dstStrLengthNL) {
1513 // finalStrLength >= dstStrLength
1514 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1515 *finalStrLengthNL,
1516 *dstStrLengthNL,
1517 cmpTy);
1518 state = state->assume(cast<DefinedOrUnknownSVal>(destInResult),
1519 true);
1520 if (!state)
1521 return;
1522 }
1523 }
1524 }
1525
1526 } else {
1527 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1528 // the final string length will match the input string length.
1529 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001530 }
1531
Jordy Rosed5af0e12011-06-15 05:52:56 +00001532 // The final result of the function will either be a pointer past the last
1533 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001534 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001535
Jordy Rosed5af0e12011-06-15 05:52:56 +00001536 assert(state);
1537
Jordy Rosee64f3112010-08-16 07:51:42 +00001538 // If the destination is a MemRegion, try to check for a buffer overflow and
1539 // record the new string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001540 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001541 QualType ptrTy = Dst->getType();
1542
1543 // If we have an exact value on a bounded copy, use that to check for
1544 // overflows, rather than our estimate about how much is actually copied.
1545 if (boundWarning) {
1546 if (NonLoc *maxLastNL = dyn_cast<NonLoc>(&maxLastElementIndex)) {
1547 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1548 *maxLastNL, ptrTy);
1549 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1550 boundWarning);
1551 if (!state)
1552 return;
1553 }
1554 }
1555
1556 // Then, if the final length is known...
Jordy Rosed5af0e12011-06-15 05:52:56 +00001557 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&finalStrLength)) {
1558 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Rose8912aae2011-06-20 21:55:40 +00001559 *knownStrLength, ptrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +00001560
Jordy Rose8912aae2011-06-20 21:55:40 +00001561 // ...and we haven't checked the bound, we'll check the actual copy.
1562 if (!boundWarning) {
1563 const char * const warningMsg =
1564 "String copy function overflows destination buffer";
1565 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1566 if (!state)
1567 return;
1568 }
Jordy Rosee64f3112010-08-16 07:51:42 +00001569
1570 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001571 if (returnEnd)
1572 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001573 }
1574
1575 // Invalidate the destination. This must happen before we set the C string
1576 // length because invalidation will clear the length.
1577 // FIXME: Even if we can't perfectly model the copy, we should see if we
1578 // can use LazyCompoundVals to copy the source values into the destination.
1579 // This would probably remove any existing bindings past the end of the
1580 // string, but that's still an improvement over blank invalidation.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001581 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001582
Jordy Rose5e5f1502011-06-20 03:49:16 +00001583 // Set the C string length of the destination, if we know it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001584 if (isBounded && !isAppending) {
1585 // strncpy is annoying in that it doesn't guarantee to null-terminate
1586 // the result string. If the original string didn't fit entirely inside
1587 // the bound (including the null-terminator), we don't know how long the
1588 // result is.
1589 if (amountCopied != strLength)
1590 finalStrLength = UnknownVal();
1591 }
1592 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001593 }
1594
Jordy Rosed5af0e12011-06-15 05:52:56 +00001595 assert(state);
1596
Jordy Rosee64f3112010-08-16 07:51:42 +00001597 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1598 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001599 if (returnEnd && Result.isUnknown()) {
Ted Kremenek66c486f2012-08-22 06:26:15 +00001600 Result = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Jordy Rosee64f3112010-08-16 07:51:42 +00001601 }
1602
1603 // Set the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001604 state = state->BindExpr(CE, LCtx, Result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001605 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +00001606}
1607
Lenny Maiorani318dd922011-04-12 17:08:43 +00001608void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001609 if (CE->getNumArgs() < 2)
1610 return;
1611
Jordy Roseadc42d42011-06-16 07:13:34 +00001612 //int strcmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001613 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001614}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001615
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001616void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001617 if (CE->getNumArgs() < 3)
1618 return;
1619
Jordy Roseadc42d42011-06-16 07:13:34 +00001620 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001621 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1622}
1623
1624void CStringChecker::evalStrcasecmp(CheckerContext &C,
1625 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001626 if (CE->getNumArgs() < 2)
1627 return;
1628
Jordy Roseadc42d42011-06-16 07:13:34 +00001629 //int strcasecmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001630 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001631}
1632
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001633void CStringChecker::evalStrncasecmp(CheckerContext &C,
1634 const CallExpr *CE) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001635 if (CE->getNumArgs() < 3)
1636 return;
1637
Jordy Roseadc42d42011-06-16 07:13:34 +00001638 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001639 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1640}
1641
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001642void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001643 bool isBounded, bool ignoreCase) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001644 CurrentFunctionDescription = "string comparison function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001645 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001646 const LocationContext *LCtx = C.getLocationContext();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001647
1648 // Check that the first string is non-null
1649 const Expr *s1 = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001650 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001651 state = checkNonNull(C, state, s1, s1Val);
1652 if (!state)
1653 return;
1654
1655 // Check that the second string is non-null.
1656 const Expr *s2 = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001657 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001658 state = checkNonNull(C, state, s2, s2Val);
1659 if (!state)
1660 return;
1661
1662 // Get the string length of the first string or give up.
1663 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1664 if (s1Length.isUndef())
1665 return;
1666
1667 // Get the string length of the second string or give up.
1668 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1669 if (s2Length.isUndef())
1670 return;
1671
Jordy Roseadc42d42011-06-16 07:13:34 +00001672 // If we know the two buffers are the same, we know the result is 0.
1673 // First, get the two buffers' addresses. Another checker will have already
1674 // made sure they're not undefined.
1675 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(s1Val);
1676 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(s2Val);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001677
Jordy Roseadc42d42011-06-16 07:13:34 +00001678 // See if they are the same.
Lenny Maiorani318dd922011-04-12 17:08:43 +00001679 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseadc42d42011-06-16 07:13:34 +00001680 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001681 ProgramStateRef StSameBuf, StNotSameBuf;
Jordy Roseadc42d42011-06-16 07:13:34 +00001682 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001683
Jordy Roseadc42d42011-06-16 07:13:34 +00001684 // If the two arguments might be the same buffer, we know the result is 0,
1685 // and we only need to check one size.
1686 if (StSameBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001687 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1688 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001689 C.addTransition(StSameBuf);
Jordy Roseadc42d42011-06-16 07:13:34 +00001690
1691 // If the two arguments are GUARANTEED to be the same, we're done!
1692 if (!StNotSameBuf)
1693 return;
1694 }
1695
1696 assert(StNotSameBuf);
1697 state = StNotSameBuf;
1698
1699 // At this point we can go about comparing the two buffers.
1700 // For now, we only do this if they're both known string literals.
1701
1702 // Attempt to extract string literals from both expressions.
1703 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1704 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1705 bool canComputeResult = false;
1706
1707 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001708 StringRef s1StrRef = s1StrLiteral->getString();
1709 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Roseadc42d42011-06-16 07:13:34 +00001710
1711 if (isBounded) {
1712 // Get the max number of characters to compare.
1713 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001714 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Roseadc42d42011-06-16 07:13:34 +00001715
1716 // If the length is known, we can get the right substrings.
1717 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1718 // Create substrings of each to compare the prefix.
1719 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1720 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1721 canComputeResult = true;
1722 }
1723 } else {
1724 // This is a normal, unbounded strcmp.
1725 canComputeResult = true;
1726 }
1727
1728 if (canComputeResult) {
1729 // Real strcmp stops at null characters.
1730 size_t s1Term = s1StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001731 if (s1Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001732 s1StrRef = s1StrRef.substr(0, s1Term);
1733
1734 size_t s2Term = s2StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001735 if (s2Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001736 s2StrRef = s2StrRef.substr(0, s2Term);
1737
1738 // Use StringRef's comparison methods to compute the actual result.
1739 int result;
1740
1741 if (ignoreCase) {
1742 // Compare string 1 to string 2 the same way strcasecmp() does.
1743 result = s1StrRef.compare_lower(s2StrRef);
1744 } else {
1745 // Compare string 1 to string 2 the same way strcmp() does.
1746 result = s1StrRef.compare(s2StrRef);
1747 }
1748
1749 // Build the SVal of the comparison and bind the return value.
1750 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001751 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001752 }
1753 }
1754
1755 if (!canComputeResult) {
1756 // Conjure a symbolic value. It's the best we can do.
Ted Kremenek66c486f2012-08-22 06:26:15 +00001757 SVal resultVal = svalBuilder.conjureSymbolVal(0, CE, LCtx, C.blockCount());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001758 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001759 }
1760
1761 // Record this as a possible path.
Anna Zaks0bd6b112011-10-26 21:06:34 +00001762 C.addTransition(state);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001763}
1764
Jordy Rosed325ffb2010-07-08 23:57:29 +00001765//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001766// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001767//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001768
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001769bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks998e2752012-02-17 22:35:26 +00001770 const FunctionDecl *FDecl = C.getCalleeDecl(CE);
1771
1772 if (!FDecl)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001773 return false;
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001774
Anna Zaks998e2752012-02-17 22:35:26 +00001775 FnCheck evalFunction = 0;
1776 if (C.isCLibraryFunction(FDecl, "memcpy"))
1777 evalFunction = &CStringChecker::evalMemcpy;
1778 else if (C.isCLibraryFunction(FDecl, "mempcpy"))
1779 evalFunction = &CStringChecker::evalMempcpy;
1780 else if (C.isCLibraryFunction(FDecl, "memcmp"))
1781 evalFunction = &CStringChecker::evalMemcmp;
1782 else if (C.isCLibraryFunction(FDecl, "memmove"))
1783 evalFunction = &CStringChecker::evalMemmove;
1784 else if (C.isCLibraryFunction(FDecl, "strcpy"))
1785 evalFunction = &CStringChecker::evalStrcpy;
1786 else if (C.isCLibraryFunction(FDecl, "strncpy"))
1787 evalFunction = &CStringChecker::evalStrncpy;
1788 else if (C.isCLibraryFunction(FDecl, "stpcpy"))
1789 evalFunction = &CStringChecker::evalStpcpy;
1790 else if (C.isCLibraryFunction(FDecl, "strcat"))
1791 evalFunction = &CStringChecker::evalStrcat;
1792 else if (C.isCLibraryFunction(FDecl, "strncat"))
1793 evalFunction = &CStringChecker::evalStrncat;
1794 else if (C.isCLibraryFunction(FDecl, "strlen"))
1795 evalFunction = &CStringChecker::evalstrLength;
1796 else if (C.isCLibraryFunction(FDecl, "strnlen"))
1797 evalFunction = &CStringChecker::evalstrnLength;
1798 else if (C.isCLibraryFunction(FDecl, "strcmp"))
1799 evalFunction = &CStringChecker::evalStrcmp;
1800 else if (C.isCLibraryFunction(FDecl, "strncmp"))
1801 evalFunction = &CStringChecker::evalStrncmp;
1802 else if (C.isCLibraryFunction(FDecl, "strcasecmp"))
1803 evalFunction = &CStringChecker::evalStrcasecmp;
1804 else if (C.isCLibraryFunction(FDecl, "strncasecmp"))
1805 evalFunction = &CStringChecker::evalStrncasecmp;
1806 else if (C.isCLibraryFunction(FDecl, "bcopy"))
1807 evalFunction = &CStringChecker::evalBcopy;
1808 else if (C.isCLibraryFunction(FDecl, "bcmp"))
1809 evalFunction = &CStringChecker::evalMemcmp;
1810
Jordy Rosed325ffb2010-07-08 23:57:29 +00001811 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001812 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001813 return false;
1814
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001815 // Make sure each function sets its own description.
1816 // (But don't bother in a release build.)
1817 assert(!(CurrentFunctionDescription = NULL));
1818
Jordy Rosed325ffb2010-07-08 23:57:29 +00001819 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001820 (this->*evalFunction)(C, CE);
Anna Zaks57300762012-02-07 00:56:14 +00001821
1822 // If the evaluate call resulted in no change, chain to the next eval call
1823 // handler.
1824 // Note, the custom CString evaluation calls assume that basic safety
1825 // properties are held. However, if the user chooses to turn off some of these
1826 // checks, we ignore the issues and leave the call evaluation to a generic
1827 // handler.
1828 if (!C.isDifferent())
1829 return false;
1830
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001831 return true;
1832}
Jordy Rosea5261542010-08-14 21:02:52 +00001833
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001834void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001835 // Record string length for char a[] = "abc";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001836 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001837
1838 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1839 I != E; ++I) {
1840 const VarDecl *D = dyn_cast<VarDecl>(*I);
1841 if (!D)
1842 continue;
1843
1844 // FIXME: Handle array fields of structs.
1845 if (!D->getType()->isArrayType())
1846 continue;
1847
1848 const Expr *Init = D->getInit();
1849 if (!Init)
1850 continue;
1851 if (!isa<StringLiteral>(Init))
1852 continue;
1853
Anna Zaks39ac1872011-10-26 21:06:44 +00001854 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001855 const MemRegion *MR = VarLoc.getAsRegion();
1856 if (!MR)
1857 continue;
1858
Ted Kremenek5eca4822012-01-06 22:09:28 +00001859 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001860 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001861 DefinedOrUnknownSVal strLength
1862 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rosea5261542010-08-14 21:02:52 +00001863
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001864 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001865 }
1866
Anna Zaks0bd6b112011-10-26 21:06:34 +00001867 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001868}
1869
Ted Kremenek8bef8232012-01-26 21:29:00 +00001870bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001871 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001872 return !Entries.isEmpty();
1873}
1874
Ted Kremenek8bef8232012-01-26 21:29:00 +00001875ProgramStateRef
1876CStringChecker::checkRegionChanges(ProgramStateRef state,
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001877 const InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +00001878 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001879 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001880 const CallEvent *Call) const {
Jordan Rose166d5022012-11-02 01:54:06 +00001881 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001882 if (Entries.isEmpty())
1883 return state;
1884
1885 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1886 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1887
1888 // First build sets for the changed regions and their super-regions.
Jordy Rose537716a2011-08-27 22:51:26 +00001889 for (ArrayRef<const MemRegion *>::iterator
1890 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1891 const MemRegion *MR = *I;
Jordy Rosea5261542010-08-14 21:02:52 +00001892 Invalidated.insert(MR);
1893
1894 SuperRegions.insert(MR);
1895 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1896 MR = SR->getSuperRegion();
1897 SuperRegions.insert(MR);
1898 }
1899 }
1900
Jordan Rose166d5022012-11-02 01:54:06 +00001901 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001902
1903 // Then loop over the entries in the current state.
Jordan Rose166d5022012-11-02 01:54:06 +00001904 for (CStringLengthTy::iterator I = Entries.begin(),
Jordy Rosea5261542010-08-14 21:02:52 +00001905 E = Entries.end(); I != E; ++I) {
1906 const MemRegion *MR = I.getKey();
1907
1908 // Is this entry for a super-region of a changed region?
1909 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001910 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001911 continue;
1912 }
1913
1914 // Is this entry for a sub-region of a changed region?
1915 const MemRegion *Super = MR;
1916 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1917 Super = SR->getSuperRegion();
1918 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001919 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001920 break;
1921 }
1922 }
1923 }
1924
1925 return state->set<CStringLength>(Entries);
1926}
1927
Ted Kremenek8bef8232012-01-26 21:29:00 +00001928void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001929 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001930 // Mark all symbols in our string length map as valid.
Jordan Rose166d5022012-11-02 01:54:06 +00001931 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001932
Jordan Rose166d5022012-11-02 01:54:06 +00001933 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00001934 I != E; ++I) {
1935 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001936
Anna Zaks1d1d5152011-12-06 23:12:33 +00001937 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
1938 se = Len.symbol_end(); si != se; ++si)
Jordy Rosed5af0e12011-06-15 05:52:56 +00001939 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00001940 }
1941}
1942
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001943void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1944 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001945 if (!SR.hasDeadSymbols())
1946 return;
1947
Ted Kremenek8bef8232012-01-26 21:29:00 +00001948 ProgramStateRef state = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +00001949 CStringLengthTy Entries = state->get<CStringLength>();
Jordy Rosea5261542010-08-14 21:02:52 +00001950 if (Entries.isEmpty())
1951 return;
1952
Jordan Rose166d5022012-11-02 01:54:06 +00001953 CStringLengthTy::Factory &F = state->get_context<CStringLength>();
1954 for (CStringLengthTy::iterator I = Entries.begin(), E = Entries.end();
Jordy Rosea5261542010-08-14 21:02:52 +00001955 I != E; ++I) {
1956 SVal Len = I.getData();
1957 if (SymbolRef Sym = Len.getAsSymbol()) {
1958 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00001959 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00001960 }
1961 }
1962
1963 state = state->set<CStringLength>(Entries);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001964 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001965}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001966
Anna Zaks57300762012-02-07 00:56:14 +00001967#define REGISTER_CHECKER(name) \
1968void ento::register##name(CheckerManager &mgr) {\
1969 static CStringChecker *TheChecker = 0; \
1970 if (TheChecker == 0) \
1971 TheChecker = mgr.registerChecker<CStringChecker>(); \
1972 TheChecker->Filter.Check##name = true; \
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001973}
Anna Zaks57300762012-02-07 00:56:14 +00001974
1975REGISTER_CHECKER(CStringNullArg)
1976REGISTER_CHECKER(CStringOutOfBounds)
1977REGISTER_CHECKER(CStringBufferOverlap)
1978REGISTER_CHECKER(CStringNotNullTerm)
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001979
1980void ento::registerCStringCheckerBasic(CheckerManager &Mgr) {
1981 registerCStringNullArg(Mgr);
1982}