blob: 748fc43a6770678b991990f363226318946bf852 [file] [log] [blame]
Anna Zaksc800f682011-10-11 16:49:54 +00001//= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This defines CStringChecker, which is an assortment of checks on calls
11// to functions in <string.h>.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidisa0decc92011-02-15 21:25:03 +000015#include "ClangSACheckers.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000016#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis695fb502011-02-17 21:39:17 +000017#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000018#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000019#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000021#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000022#include "llvm/ADT/STLExtras.h"
Jordy Roseccbf7ee2010-07-06 23:11:01 +000023#include "llvm/ADT/StringSwitch.h"
24
25using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000026using namespace ento;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000027
28namespace {
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000029class CStringChecker : public Checker< eval::Call,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000030 check::PreStmt<DeclStmt>,
31 check::LiveSymbols,
32 check::DeadSymbols,
33 check::RegionChanges
34 > {
Anna Zaks57300762012-02-07 00:56:14 +000035 mutable OwningPtr<BugType> BT_Null,
36 BT_Bounds,
37 BT_Overlap,
38 BT_NotCString,
39 BT_AdditionOverflow;
40
Jordy Rose9e49d9f2011-06-20 02:06:40 +000041 mutable const char *CurrentFunctionDescription;
42
Jordy Roseccbf7ee2010-07-06 23:11:01 +000043public:
Anna Zaks57300762012-02-07 00:56:14 +000044 /// The filter is used to filter out the diagnostics which are not enabled by
45 /// the user.
46 struct CStringChecksFilter {
47 DefaultBool CheckCStringNullArg;
48 DefaultBool CheckCStringOutOfBounds;
49 DefaultBool CheckCStringBufferOverlap;
50 DefaultBool CheckCStringNotNullTerm;
51 };
52
53 CStringChecksFilter Filter;
54
Jordy Roseccbf7ee2010-07-06 23:11:01 +000055 static void *getTag() { static int tag; return &tag; }
56
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000057 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
58 void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +000059 void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000060 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +000061 bool wantsRegionChangeUpdate(ProgramStateRef state) const;
Jordy Rosea5261542010-08-14 21:02:52 +000062
Ted Kremenek8bef8232012-01-26 21:29:00 +000063 ProgramStateRef
64 checkRegionChanges(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000065 const StoreManager::InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +000066 ArrayRef<const MemRegion *> ExplicitRegions,
67 ArrayRef<const MemRegion *> Regions) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000068
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000069 typedef void (CStringChecker::*FnCheck)(CheckerContext &,
70 const CallExpr *) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000071
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000072 void evalMemcpy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000073 void evalMempcpy(CheckerContext &C, const CallExpr *CE) const;
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000074 void evalMemmove(CheckerContext &C, const CallExpr *CE) const;
75 void evalBcopy(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranib8b875b2011-03-31 21:36:53 +000076 void evalCopyCommon(CheckerContext &C, const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +000077 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000078 const Expr *Size,
79 const Expr *Source,
80 const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +000081 bool Restricted = false,
82 bool IsMempcpy = false) const;
Jordy Rosed325ffb2010-07-08 23:57:29 +000083
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000084 void evalMemcmp(CheckerContext &C, const CallExpr *CE) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +000085
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000086 void evalstrLength(CheckerContext &C, const CallExpr *CE) const;
87 void evalstrnLength(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000088 void evalstrLengthCommon(CheckerContext &C,
89 const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000090 bool IsStrnlen = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +000091
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +000092 void evalStrcpy(CheckerContext &C, const CallExpr *CE) const;
93 void evalStrncpy(CheckerContext &C, const CallExpr *CE) const;
94 void evalStpcpy(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +000095 void evalStrcpyCommon(CheckerContext &C,
96 const CallExpr *CE,
97 bool returnEnd,
98 bool isBounded,
99 bool isAppending) const;
Lenny Maiorani067bbd02011-04-09 15:12:58 +0000100
101 void evalStrcat(CheckerContext &C, const CallExpr *CE) const;
102 void evalStrncat(CheckerContext &C, const CallExpr *CE) const;
Jordy Rosee64f3112010-08-16 07:51:42 +0000103
Lenny Maiorani318dd922011-04-12 17:08:43 +0000104 void evalStrcmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani357f6ee2011-04-25 22:21:00 +0000105 void evalStrncmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maioranibd1d16a2011-04-28 15:09:11 +0000106 void evalStrcasecmp(CheckerContext &C, const CallExpr *CE) const;
Lenny Maiorani454fd2d2011-05-02 19:05:49 +0000107 void evalStrncasecmp(CheckerContext &C, const CallExpr *CE) const;
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000108 void evalStrcmpCommon(CheckerContext &C,
109 const CallExpr *CE,
110 bool isBounded = false,
111 bool ignoreCase = false) const;
Lenny Maiorani318dd922011-04-12 17:08:43 +0000112
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000113 // Utility methods
Ted Kremenek8bef8232012-01-26 21:29:00 +0000114 std::pair<ProgramStateRef , ProgramStateRef >
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000115 static assumeZero(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000116 ProgramStateRef state, SVal V, QualType Ty);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000117
Ted Kremenek8bef8232012-01-26 21:29:00 +0000118 static ProgramStateRef setCStringLength(ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000119 const MemRegion *MR,
120 SVal strLength);
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000121 static SVal getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000122 ProgramStateRef &state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000123 const Expr *Ex,
124 const MemRegion *MR,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000125 bool hypothetical);
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000126 SVal getCStringLength(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000127 ProgramStateRef &state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000128 const Expr *Ex,
129 SVal Buf,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000130 bool hypothetical = false) const;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000131
Lenny Maiorani318dd922011-04-12 17:08:43 +0000132 const StringLiteral *getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000133 ProgramStateRef &state,
Lenny Maiorani318dd922011-04-12 17:08:43 +0000134 const Expr *expr,
135 SVal val) const;
136
Ted Kremenek8bef8232012-01-26 21:29:00 +0000137 static ProgramStateRef InvalidateBuffer(CheckerContext &C,
138 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000139 const Expr *Ex, SVal V);
Jordy Rosee64f3112010-08-16 07:51:42 +0000140
Ted Kremenek9c378f72011-08-12 23:37:29 +0000141 static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000142 const MemRegion *MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000143
144 // Re-usable checks
Ted Kremenek8bef8232012-01-26 21:29:00 +0000145 ProgramStateRef checkNonNull(CheckerContext &C,
146 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000147 const Expr *S,
148 SVal l) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000149 ProgramStateRef CheckLocation(CheckerContext &C,
150 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000151 const Expr *S,
152 SVal l,
153 const char *message = NULL) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000154 ProgramStateRef CheckBufferAccess(CheckerContext &C,
155 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000156 const Expr *Size,
157 const Expr *FirstBuf,
158 const Expr *SecondBuf,
159 const char *firstMessage = NULL,
160 const char *secondMessage = NULL,
161 bool WarnAboutSize = false) const;
162
Ted Kremenek8bef8232012-01-26 21:29:00 +0000163 ProgramStateRef CheckBufferAccess(CheckerContext &C,
164 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000165 const Expr *Size,
166 const Expr *Buf,
167 const char *message = NULL,
168 bool WarnAboutSize = false) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000169 // This is a convenience override.
Jordy Rose5e5f1502011-06-20 03:49:16 +0000170 return CheckBufferAccess(C, state, Size, Buf, NULL, message, NULL,
171 WarnAboutSize);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000172 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000173 ProgramStateRef CheckOverlap(CheckerContext &C,
174 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000175 const Expr *Size,
176 const Expr *First,
177 const Expr *Second) const;
178 void emitOverlapBug(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000179 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000180 const Stmt *First,
181 const Stmt *Second) const;
182
Ted Kremenek8bef8232012-01-26 21:29:00 +0000183 ProgramStateRef checkAdditionOverflow(CheckerContext &C,
184 ProgramStateRef state,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000185 NonLoc left,
186 NonLoc right) const;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000187};
Jordy Rosea5261542010-08-14 21:02:52 +0000188
189class CStringLength {
190public:
191 typedef llvm::ImmutableMap<const MemRegion *, SVal> EntryMap;
192};
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000193} //end anonymous namespace
194
Jordy Rosea5261542010-08-14 21:02:52 +0000195namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000196namespace ento {
Jordy Rosea5261542010-08-14 21:02:52 +0000197 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000198 struct ProgramStateTrait<CStringLength>
199 : public ProgramStatePartialTrait<CStringLength::EntryMap> {
Jordy Rosea5261542010-08-14 21:02:52 +0000200 static void *GDMIndex() { return CStringChecker::getTag(); }
201 };
202}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000203}
Jordy Rosea5261542010-08-14 21:02:52 +0000204
Jordy Rosed325ffb2010-07-08 23:57:29 +0000205//===----------------------------------------------------------------------===//
206// Individual checks and utility methods.
207//===----------------------------------------------------------------------===//
208
Ted Kremenek8bef8232012-01-26 21:29:00 +0000209std::pair<ProgramStateRef , ProgramStateRef >
210CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef state, SVal V,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000211 QualType Ty) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000212 DefinedSVal *val = dyn_cast<DefinedSVal>(&V);
213 if (!val)
Ted Kremenek8bef8232012-01-26 21:29:00 +0000214 return std::pair<ProgramStateRef , ProgramStateRef >(state, state);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000215
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000216 SValBuilder &svalBuilder = C.getSValBuilder();
217 DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(Ty);
218 return state->assume(svalBuilder.evalEQ(state, *val, zero));
Jordy Rosed325ffb2010-07-08 23:57:29 +0000219}
Jordy Rosea6b808c2010-07-07 07:48:06 +0000220
Ted Kremenek8bef8232012-01-26 21:29:00 +0000221ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C,
222 ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000223 const Expr *S, SVal l) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000224 // If a previous check has failed, propagate the failure.
225 if (!state)
226 return NULL;
227
Ted Kremenek8bef8232012-01-26 21:29:00 +0000228 ProgramStateRef stateNull, stateNonNull;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000229 llvm::tie(stateNull, stateNonNull) = assumeZero(C, state, l, S->getType());
Jordy Rosed325ffb2010-07-08 23:57:29 +0000230
231 if (stateNull && !stateNonNull) {
Anna Zaks57300762012-02-07 00:56:14 +0000232 if (!Filter.CheckCStringNullArg)
233 return NULL;
234
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000235 ExplodedNode *N = C.generateSink(stateNull);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000236 if (!N)
237 return NULL;
238
Jordy Rosed325ffb2010-07-08 23:57:29 +0000239 if (!BT_Null)
Anna Zaks57300762012-02-07 00:56:14 +0000240 BT_Null.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000241 "Null pointer argument in call to byte string function"));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000242
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000243 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000244 llvm::raw_svector_ostream os(buf);
245 assert(CurrentFunctionDescription);
246 os << "Null pointer argument in call to " << CurrentFunctionDescription;
247
Jordy Rosea6b808c2010-07-07 07:48:06 +0000248 // Generate a report for this bug.
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000249 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Null.get());
Anna Zakse172e8b2011-08-17 23:00:25 +0000250 BugReport *report = new BugReport(*BT, os.str(), N);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000251
252 report->addRange(S->getSourceRange());
Anna Zaks50bbc162011-08-19 22:33:38 +0000253 report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, S));
Jordy Rosea6b808c2010-07-07 07:48:06 +0000254 C.EmitReport(report);
255 return NULL;
256 }
257
258 // From here on, assume that the value is non-null.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000259 assert(stateNonNull);
260 return stateNonNull;
Jordy Rosea6b808c2010-07-07 07:48:06 +0000261}
262
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000263// FIXME: This was originally copied from ArrayBoundChecker.cpp. Refactor?
Ted Kremenek8bef8232012-01-26 21:29:00 +0000264ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C,
265 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000266 const Expr *S, SVal l,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000267 const char *warningMsg) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000268 // If a previous check has failed, propagate the failure.
269 if (!state)
270 return NULL;
271
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000272 // Check for out of bound array element access.
273 const MemRegion *R = l.getAsRegion();
274 if (!R)
275 return state;
276
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000277 const ElementRegion *ER = dyn_cast<ElementRegion>(R);
278 if (!ER)
279 return state;
280
Zhongxing Xu018220c2010-08-11 06:10:55 +0000281 assert(ER->getValueType() == C.getASTContext().CharTy &&
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000282 "CheckLocation should only be called with char* ElementRegions");
283
284 // Get the size of the array.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000285 const SubRegion *superReg = cast<SubRegion>(ER->getSuperRegion());
286 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000287 SVal Extent =
288 svalBuilder.convertToArrayIndex(superReg->getExtent(svalBuilder));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000289 DefinedOrUnknownSVal Size = cast<DefinedOrUnknownSVal>(Extent);
290
291 // Get the index of the accessed element.
Gabor Greif89b06582010-09-09 10:51:37 +0000292 DefinedOrUnknownSVal Idx = cast<DefinedOrUnknownSVal>(ER->getIndex());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000293
Ted Kremenek8bef8232012-01-26 21:29:00 +0000294 ProgramStateRef StInBound = state->assumeInBound(Idx, Size, true);
295 ProgramStateRef StOutBound = state->assumeInBound(Idx, Size, false);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000296 if (StOutBound && !StInBound) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000297 ExplodedNode *N = C.generateSink(StOutBound);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000298 if (!N)
299 return NULL;
300
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000301 if (!BT_Bounds) {
302 BT_Bounds.reset(new BuiltinBug("Out-of-bound array access",
303 "Byte string function accesses out-of-bound array element"));
304 }
305 BuiltinBug *BT = static_cast<BuiltinBug*>(BT_Bounds.get());
306
307 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000308 BugReport *report;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000309 if (warningMsg) {
Anna Zakse172e8b2011-08-17 23:00:25 +0000310 report = new BugReport(*BT, warningMsg, N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000311 } else {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000312 assert(CurrentFunctionDescription);
313 assert(CurrentFunctionDescription[0] != '\0');
314
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000315 SmallString<80> buf;
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000316 llvm::raw_svector_ostream os(buf);
317 os << (char)toupper(CurrentFunctionDescription[0])
318 << &CurrentFunctionDescription[1]
319 << " accesses out-of-bound array element";
Anna Zakse172e8b2011-08-17 23:00:25 +0000320 report = new BugReport(*BT, os.str(), N);
Jordy Rosee64f3112010-08-16 07:51:42 +0000321 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000322
323 // FIXME: It would be nice to eventually make this diagnostic more clear,
324 // e.g., by referencing the original declaration or by saying *why* this
325 // reference is outside the range.
326
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000327 report->addRange(S->getSourceRange());
328 C.EmitReport(report);
329 return NULL;
330 }
331
332 // Array bound check succeeded. From this point forward the array bound
333 // should always succeed.
334 return StInBound;
335}
336
Ted Kremenek8bef8232012-01-26 21:29:00 +0000337ProgramStateRef CStringChecker::CheckBufferAccess(CheckerContext &C,
338 ProgramStateRef state,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000339 const Expr *Size,
340 const Expr *FirstBuf,
Jordy Rosee64f3112010-08-16 07:51:42 +0000341 const Expr *SecondBuf,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000342 const char *firstMessage,
Jordy Rose5e5f1502011-06-20 03:49:16 +0000343 const char *secondMessage,
344 bool WarnAboutSize) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000345 // If a previous check has failed, propagate the failure.
346 if (!state)
347 return NULL;
348
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000349 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rose1e022412011-06-16 05:51:02 +0000350 ASTContext &Ctx = svalBuilder.getContext();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000351 const LocationContext *LCtx = C.getLocationContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000352
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000353 QualType sizeTy = Size->getType();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000354 QualType PtrTy = Ctx.getPointerType(Ctx.CharTy);
355
Jordy Rosea6b808c2010-07-07 07:48:06 +0000356 // Check that the first buffer is non-null.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000357 SVal BufVal = state->getSVal(FirstBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000358 state = checkNonNull(C, state, FirstBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000359 if (!state)
360 return NULL;
361
Anna Zaks57300762012-02-07 00:56:14 +0000362 // If out-of-bounds checking is turned off, skip the rest.
363 if (!Filter.CheckCStringOutOfBounds)
364 return state;
365
Jordy Rosed325ffb2010-07-08 23:57:29 +0000366 // Get the access length and make sure it is known.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000367 // FIXME: This assumes the caller has already checked that the access length
368 // is positive. And that it's unsigned.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000369 SVal LengthVal = state->getSVal(Size, LCtx);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000370 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
371 if (!Length)
372 return state;
373
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000374 // Compute the offset of the last element to be accessed: size-1.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000375 NonLoc One = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
376 NonLoc LastOffset = cast<NonLoc>(svalBuilder.evalBinOpNN(state, BO_Sub,
377 *Length, One, sizeTy));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000378
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000379 // Check that the first buffer is sufficiently long.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000380 SVal BufStart = svalBuilder.evalCast(BufVal, PtrTy, FirstBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000381 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000382 const Expr *warningExpr = (WarnAboutSize ? Size : FirstBuf);
383
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000384 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
385 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000386 state = CheckLocation(C, state, warningExpr, BufEnd, firstMessage);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000387
Jordy Roseb6a40262010-08-05 23:11:30 +0000388 // If the buffer isn't large enough, abort.
389 if (!state)
390 return NULL;
391 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000392
393 // If there's a second buffer, check it as well.
394 if (SecondBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000395 BufVal = state->getSVal(SecondBuf, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000396 state = checkNonNull(C, state, SecondBuf, BufVal);
Jordy Rosea6b808c2010-07-07 07:48:06 +0000397 if (!state)
398 return NULL;
399
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000400 BufStart = svalBuilder.evalCast(BufVal, PtrTy, SecondBuf->getType());
Jordy Roseb6a40262010-08-05 23:11:30 +0000401 if (Loc *BufLoc = dyn_cast<Loc>(&BufStart)) {
Jordy Rose5e5f1502011-06-20 03:49:16 +0000402 const Expr *warningExpr = (WarnAboutSize ? Size : SecondBuf);
403
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000404 SVal BufEnd = svalBuilder.evalBinOpLN(state, BO_Add, *BufLoc,
405 LastOffset, PtrTy);
Jordy Rose5e5f1502011-06-20 03:49:16 +0000406 state = CheckLocation(C, state, warningExpr, BufEnd, secondMessage);
Jordy Roseb6a40262010-08-05 23:11:30 +0000407 }
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000408 }
409
410 // Large enough or not, return this state!
411 return state;
412}
413
Ted Kremenek8bef8232012-01-26 21:29:00 +0000414ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C,
415 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000416 const Expr *Size,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000417 const Expr *First,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000418 const Expr *Second) const {
Anna Zaks57300762012-02-07 00:56:14 +0000419 if (!Filter.CheckCStringBufferOverlap)
420 return state;
421
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000422 // Do a simple check for overlap: if the two arguments are from the same
423 // buffer, see if the end of the first is greater than the start of the second
424 // or vice versa.
425
Jordy Rosed325ffb2010-07-08 23:57:29 +0000426 // If a previous check has failed, propagate the failure.
427 if (!state)
428 return NULL;
429
Ted Kremenek8bef8232012-01-26 21:29:00 +0000430 ProgramStateRef stateTrue, stateFalse;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000431
432 // Get the buffer values and make sure they're known locations.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000433 const LocationContext *LCtx = C.getLocationContext();
434 SVal firstVal = state->getSVal(First, LCtx);
435 SVal secondVal = state->getSVal(Second, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000436
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000437 Loc *firstLoc = dyn_cast<Loc>(&firstVal);
438 if (!firstLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000439 return state;
440
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000441 Loc *secondLoc = dyn_cast<Loc>(&secondVal);
442 if (!secondLoc)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000443 return state;
444
445 // Are the two values the same?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000446 SValBuilder &svalBuilder = C.getSValBuilder();
447 llvm::tie(stateTrue, stateFalse) =
448 state->assume(svalBuilder.evalEQ(state, *firstLoc, *secondLoc));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000449
450 if (stateTrue && !stateFalse) {
451 // If the values are known to be equal, that's automatically an overlap.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000452 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000453 return NULL;
454 }
455
Ted Kremenek28f47b92010-12-01 22:16:56 +0000456 // assume the two expressions are not equal.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000457 assert(stateFalse);
458 state = stateFalse;
459
460 // Which value comes first?
Jordy Roseee2fde12011-06-16 05:56:50 +0000461 QualType cmpTy = svalBuilder.getConditionType();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000462 SVal reverse = svalBuilder.evalBinOpLL(state, BO_GT,
463 *firstLoc, *secondLoc, cmpTy);
464 DefinedOrUnknownSVal *reverseTest = dyn_cast<DefinedOrUnknownSVal>(&reverse);
465 if (!reverseTest)
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000466 return state;
467
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000468 llvm::tie(stateTrue, stateFalse) = state->assume(*reverseTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000469 if (stateTrue) {
470 if (stateFalse) {
471 // If we don't know which one comes first, we can't perform this test.
472 return state;
473 } else {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000474 // Switch the values so that firstVal is before secondVal.
475 Loc *tmpLoc = firstLoc;
476 firstLoc = secondLoc;
477 secondLoc = tmpLoc;
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000478
479 // Switch the Exprs as well, so that they still correspond.
480 const Expr *tmpExpr = First;
481 First = Second;
482 Second = tmpExpr;
483 }
484 }
485
486 // Get the length, and make sure it too is known.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000487 SVal LengthVal = state->getSVal(Size, LCtx);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000488 NonLoc *Length = dyn_cast<NonLoc>(&LengthVal);
489 if (!Length)
490 return state;
491
492 // Convert the first buffer's start address to char*.
493 // Bail out if the cast fails.
Jordy Roseee2fde12011-06-16 05:56:50 +0000494 ASTContext &Ctx = svalBuilder.getContext();
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000495 QualType CharPtrTy = Ctx.getPointerType(Ctx.CharTy);
Jordy Rose1e022412011-06-16 05:51:02 +0000496 SVal FirstStart = svalBuilder.evalCast(*firstLoc, CharPtrTy,
497 First->getType());
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000498 Loc *FirstStartLoc = dyn_cast<Loc>(&FirstStart);
499 if (!FirstStartLoc)
500 return state;
501
502 // Compute the end of the first buffer. Bail out if THAT fails.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000503 SVal FirstEnd = svalBuilder.evalBinOpLN(state, BO_Add,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000504 *FirstStartLoc, *Length, CharPtrTy);
505 Loc *FirstEndLoc = dyn_cast<Loc>(&FirstEnd);
506 if (!FirstEndLoc)
507 return state;
508
509 // Is the end of the first buffer past the start of the second buffer?
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000510 SVal Overlap = svalBuilder.evalBinOpLL(state, BO_GT,
511 *FirstEndLoc, *secondLoc, cmpTy);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000512 DefinedOrUnknownSVal *OverlapTest = dyn_cast<DefinedOrUnknownSVal>(&Overlap);
513 if (!OverlapTest)
514 return state;
515
Ted Kremenek28f47b92010-12-01 22:16:56 +0000516 llvm::tie(stateTrue, stateFalse) = state->assume(*OverlapTest);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000517
518 if (stateTrue && !stateFalse) {
519 // Overlap!
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000520 emitOverlapBug(C, stateTrue, First, Second);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000521 return NULL;
522 }
523
Ted Kremenek28f47b92010-12-01 22:16:56 +0000524 // assume the two expressions don't overlap.
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000525 assert(stateFalse);
526 return stateFalse;
527}
528
Ted Kremenek8bef8232012-01-26 21:29:00 +0000529void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000530 const Stmt *First, const Stmt *Second) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000531 ExplodedNode *N = C.generateSink(state);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000532 if (!N)
533 return;
534
535 if (!BT_Overlap)
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000536 BT_Overlap.reset(new BugType("Unix API", "Improper arguments"));
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000537
538 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000539 BugReport *report =
540 new BugReport(*BT_Overlap,
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000541 "Arguments must not be overlapping buffers", N);
542 report->addRange(First->getSourceRange());
543 report->addRange(Second->getSourceRange());
544
545 C.EmitReport(report);
546}
547
Ted Kremenek8bef8232012-01-26 21:29:00 +0000548ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C,
549 ProgramStateRef state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000550 NonLoc left,
551 NonLoc right) const {
Anna Zaks57300762012-02-07 00:56:14 +0000552 // If out-of-bounds checking is turned off, skip the rest.
553 if (!Filter.CheckCStringOutOfBounds)
554 return state;
555
Jordy Rosed5af0e12011-06-15 05:52:56 +0000556 // If a previous check has failed, propagate the failure.
557 if (!state)
558 return NULL;
559
560 SValBuilder &svalBuilder = C.getSValBuilder();
561 BasicValueFactory &BVF = svalBuilder.getBasicValueFactory();
562
563 QualType sizeTy = svalBuilder.getContext().getSizeType();
564 const llvm::APSInt &maxValInt = BVF.getMaxValue(sizeTy);
565 NonLoc maxVal = svalBuilder.makeIntVal(maxValInt);
566
Anna Zakse3d250e2011-12-11 18:43:40 +0000567 SVal maxMinusRight;
568 if (isa<nonloc::ConcreteInt>(right)) {
569 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, right,
570 sizeTy);
571 } else {
Jordy Rosed5af0e12011-06-15 05:52:56 +0000572 // Try switching the operands. (The order of these two assignments is
573 // important!)
574 maxMinusRight = svalBuilder.evalBinOpNN(state, BO_Sub, maxVal, left,
575 sizeTy);
576 left = right;
577 }
578
579 if (NonLoc *maxMinusRightNL = dyn_cast<NonLoc>(&maxMinusRight)) {
580 QualType cmpTy = svalBuilder.getConditionType();
581 // If left > max - right, we have an overflow.
582 SVal willOverflow = svalBuilder.evalBinOpNN(state, BO_GT, left,
583 *maxMinusRightNL, cmpTy);
584
Ted Kremenek8bef8232012-01-26 21:29:00 +0000585 ProgramStateRef stateOverflow, stateOkay;
Jordy Rosed5af0e12011-06-15 05:52:56 +0000586 llvm::tie(stateOverflow, stateOkay) =
587 state->assume(cast<DefinedOrUnknownSVal>(willOverflow));
588
589 if (stateOverflow && !stateOkay) {
590 // We have an overflow. Emit a bug report.
591 ExplodedNode *N = C.generateSink(stateOverflow);
592 if (!N)
593 return NULL;
594
595 if (!BT_AdditionOverflow)
596 BT_AdditionOverflow.reset(new BuiltinBug("API",
597 "Sum of expressions causes overflow"));
598
Jordy Rosed5af0e12011-06-15 05:52:56 +0000599 // This isn't a great error message, but this should never occur in real
600 // code anyway -- you'd have to create a buffer longer than a size_t can
601 // represent, which is sort of a contradiction.
Jordy Rose8cc24912011-06-20 03:51:53 +0000602 const char *warning =
603 "This expression will create a string whose length is too big to "
604 "be represented as a size_t";
Jordy Rosed5af0e12011-06-15 05:52:56 +0000605
606 // Generate a report for this bug.
Jordy Rose8cc24912011-06-20 03:51:53 +0000607 BugReport *report = new BugReport(*BT_AdditionOverflow, warning, N);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000608 C.EmitReport(report);
609
610 return NULL;
611 }
612
613 // From now on, assume an overflow didn't occur.
614 assert(stateOkay);
615 state = stateOkay;
616 }
617
618 return state;
619}
620
Ted Kremenek8bef8232012-01-26 21:29:00 +0000621ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000622 const MemRegion *MR,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000623 SVal strLength) {
624 assert(!strLength.isUndef() && "Attempt to set an undefined string length");
Jordy Rosee64f3112010-08-16 07:51:42 +0000625
626 MR = MR->StripCasts();
627
628 switch (MR->getKind()) {
629 case MemRegion::StringRegionKind:
630 // FIXME: This can happen if we strcpy() into a string region. This is
631 // undefined [C99 6.4.5p6], but we should still warn about it.
632 return state;
633
634 case MemRegion::SymbolicRegionKind:
635 case MemRegion::AllocaRegionKind:
636 case MemRegion::VarRegionKind:
637 case MemRegion::FieldRegionKind:
638 case MemRegion::ObjCIvarRegionKind:
Jordy Rose210c05b2011-06-15 05:14:03 +0000639 // These are the types we can currently track string lengths for.
640 break;
Jordy Rosee64f3112010-08-16 07:51:42 +0000641
642 case MemRegion::ElementRegionKind:
643 // FIXME: Handle element regions by upper-bounding the parent region's
644 // string length.
645 return state;
646
647 default:
648 // Other regions (mostly non-data) can't have a reliable C string length.
649 // For now, just ignore the change.
650 // FIXME: These are rare but not impossible. We should output some kind of
651 // warning for things like strcpy((char[]){'a', 0}, "b");
652 return state;
653 }
Jordy Rose210c05b2011-06-15 05:14:03 +0000654
655 if (strLength.isUnknown())
656 return state->remove<CStringLength>(MR);
657
658 return state->set<CStringLength>(MR, strLength);
Jordy Rosee64f3112010-08-16 07:51:42 +0000659}
660
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000661SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000662 ProgramStateRef &state,
Jordy Rosea5261542010-08-14 21:02:52 +0000663 const Expr *Ex,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000664 const MemRegion *MR,
665 bool hypothetical) {
666 if (!hypothetical) {
667 // If there's a recorded length, go ahead and return it.
668 const SVal *Recorded = state->get<CStringLength>(MR);
669 if (Recorded)
670 return *Recorded;
671 }
Jordy Rosea5261542010-08-14 21:02:52 +0000672
673 // Otherwise, get a new symbol and update the state.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +0000674 unsigned Count = C.getCurrentBlockCount();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000675 SValBuilder &svalBuilder = C.getSValBuilder();
676 QualType sizeTy = svalBuilder.getContext().getSizeType();
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000677 SVal strLength = svalBuilder.getMetadataSymbolVal(CStringChecker::getTag(),
678 MR, Ex, sizeTy, Count);
Jordy Rosed5af0e12011-06-15 05:52:56 +0000679
680 if (!hypothetical)
681 state = state->set<CStringLength>(MR, strLength);
682
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000683 return strLength;
Jordy Rosea5261542010-08-14 21:02:52 +0000684}
685
Ted Kremenek8bef8232012-01-26 21:29:00 +0000686SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state,
Jordy Rosed5af0e12011-06-15 05:52:56 +0000687 const Expr *Ex, SVal Buf,
688 bool hypothetical) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000689 const MemRegion *MR = Buf.getAsRegion();
690 if (!MR) {
691 // If we can't get a region, see if it's something we /know/ isn't a
692 // C string. In the context of locations, the only time we can issue such
693 // a warning is for labels.
694 if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&Buf)) {
Anna Zaks57300762012-02-07 00:56:14 +0000695 if (!Filter.CheckCStringNotNullTerm)
696 return UndefinedVal();
697
Anna Zaks0bd6b112011-10-26 21:06:34 +0000698 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000699 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000700 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000701 "Argument is not a null-terminated string."));
Jordy Rose19c5dd12010-07-27 01:37:31 +0000702
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000703 SmallString<120> buf;
Jordy Rose19c5dd12010-07-27 01:37:31 +0000704 llvm::raw_svector_ostream os(buf);
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000705 assert(CurrentFunctionDescription);
706 os << "Argument to " << CurrentFunctionDescription
707 << " is the address of the label '" << Label->getLabel()->getName()
Jordy Rose19c5dd12010-07-27 01:37:31 +0000708 << "', which is not a null-terminated string";
709
710 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000711 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000712 os.str(), N);
713
714 report->addRange(Ex->getSourceRange());
715 C.EmitReport(report);
716 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000717 return UndefinedVal();
Anna Zaks57300762012-02-07 00:56:14 +0000718
Jordy Rose19c5dd12010-07-27 01:37:31 +0000719 }
720
Jordy Rosea5261542010-08-14 21:02:52 +0000721 // If it's not a region and not a label, give up.
722 return UnknownVal();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000723 }
724
Jordy Rosea5261542010-08-14 21:02:52 +0000725 // If we have a region, strip casts from it and see if we can figure out
726 // its length. For anything we can't figure out, just return UnknownVal.
727 MR = MR->StripCasts();
728
729 switch (MR->getKind()) {
730 case MemRegion::StringRegionKind: {
731 // Modifying the contents of string regions is undefined [C99 6.4.5p6],
732 // so we can assume that the byte length is the correct C string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000733 SValBuilder &svalBuilder = C.getSValBuilder();
734 QualType sizeTy = svalBuilder.getContext().getSizeType();
735 const StringLiteral *strLit = cast<StringRegion>(MR)->getStringLiteral();
736 return svalBuilder.makeIntVal(strLit->getByteLength(), sizeTy);
Jordy Rosea5261542010-08-14 21:02:52 +0000737 }
738 case MemRegion::SymbolicRegionKind:
739 case MemRegion::AllocaRegionKind:
740 case MemRegion::VarRegionKind:
741 case MemRegion::FieldRegionKind:
742 case MemRegion::ObjCIvarRegionKind:
Jordy Rosed5af0e12011-06-15 05:52:56 +0000743 return getCStringLengthForRegion(C, state, Ex, MR, hypothetical);
Jordy Rosea5261542010-08-14 21:02:52 +0000744 case MemRegion::CompoundLiteralRegionKind:
745 // FIXME: Can we track this? Is it necessary?
746 return UnknownVal();
747 case MemRegion::ElementRegionKind:
748 // FIXME: How can we handle this? It's not good enough to subtract the
749 // offset from the base string length; consider "123\x00567" and &a[5].
750 return UnknownVal();
751 default:
752 // Other regions (mostly non-data) can't have a reliable C string length.
753 // In this case, an error is emitted and UndefinedVal is returned.
754 // The caller should always be prepared to handle this case.
Anna Zaks57300762012-02-07 00:56:14 +0000755 if (!Filter.CheckCStringNotNullTerm)
756 return UndefinedVal();
757
Anna Zaks0bd6b112011-10-26 21:06:34 +0000758 if (ExplodedNode *N = C.addTransition(state)) {
Jordy Rosea5261542010-08-14 21:02:52 +0000759 if (!BT_NotCString)
Anna Zaks57300762012-02-07 00:56:14 +0000760 BT_NotCString.reset(new BuiltinBug("Unix API",
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000761 "Argument is not a null-terminated string."));
Jordy Rosea5261542010-08-14 21:02:52 +0000762
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000763 SmallString<120> buf;
Jordy Rosea5261542010-08-14 21:02:52 +0000764 llvm::raw_svector_ostream os(buf);
765
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000766 assert(CurrentFunctionDescription);
767 os << "Argument to " << CurrentFunctionDescription << " is ";
Jordy Rosea5261542010-08-14 21:02:52 +0000768
769 if (SummarizeRegion(os, C.getASTContext(), MR))
770 os << ", which is not a null-terminated string";
771 else
772 os << "not a null-terminated string";
773
774 // Generate a report for this bug.
Anna Zakse172e8b2011-08-17 23:00:25 +0000775 BugReport *report = new BugReport(*BT_NotCString,
Jordy Rosea5261542010-08-14 21:02:52 +0000776 os.str(), N);
777
778 report->addRange(Ex->getSourceRange());
779 C.EmitReport(report);
780 }
781
782 return UndefinedVal();
783 }
Jordy Rose19c5dd12010-07-27 01:37:31 +0000784}
785
Lenny Maiorani318dd922011-04-12 17:08:43 +0000786const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000787 ProgramStateRef &state, const Expr *expr, SVal val) const {
Lenny Maiorani318dd922011-04-12 17:08:43 +0000788
789 // Get the memory region pointed to by the val.
790 const MemRegion *bufRegion = val.getAsRegion();
791 if (!bufRegion)
792 return NULL;
793
794 // Strip casts off the memory region.
795 bufRegion = bufRegion->StripCasts();
796
797 // Cast the memory region to a string region.
798 const StringRegion *strRegion= dyn_cast<StringRegion>(bufRegion);
799 if (!strRegion)
800 return NULL;
801
802 // Return the actual string in the string region.
803 return strRegion->getStringLiteral();
804}
805
Ted Kremenek8bef8232012-01-26 21:29:00 +0000806ProgramStateRef CStringChecker::InvalidateBuffer(CheckerContext &C,
807 ProgramStateRef state,
Jordy Rosee64f3112010-08-16 07:51:42 +0000808 const Expr *E, SVal V) {
809 Loc *L = dyn_cast<Loc>(&V);
810 if (!L)
811 return state;
812
813 // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes
814 // some assumptions about the value that CFRefCount can't. Even so, it should
815 // probably be refactored.
816 if (loc::MemRegionVal* MR = dyn_cast<loc::MemRegionVal>(L)) {
817 const MemRegion *R = MR->getRegion()->StripCasts();
818
819 // Are we dealing with an ElementRegion? If so, we should be invalidating
820 // the super-region.
821 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
822 R = ER->getSuperRegion();
823 // FIXME: What about layers of ElementRegions?
824 }
825
826 // Invalidate this region.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +0000827 unsigned Count = C.getCurrentBlockCount();
Jordy Rose537716a2011-08-27 22:51:26 +0000828 return state->invalidateRegions(R, E, Count);
Jordy Rosee64f3112010-08-16 07:51:42 +0000829 }
830
831 // If we have a non-region value by chance, just remove the binding.
832 // FIXME: is this necessary or correct? This handles the non-Region
833 // cases. Is it ever valid to store to these?
834 return state->unbindLoc(*L);
835}
836
Ted Kremenek9c378f72011-08-12 23:37:29 +0000837bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx,
Jordy Rose19c5dd12010-07-27 01:37:31 +0000838 const MemRegion *MR) {
Ted Kremenek96979342011-08-12 20:02:48 +0000839 const TypedValueRegion *TVR = dyn_cast<TypedValueRegion>(MR);
Jordy Rose19c5dd12010-07-27 01:37:31 +0000840
Jordy Rose096aef92011-08-12 21:41:07 +0000841 switch (MR->getKind()) {
Jordy Rose19c5dd12010-07-27 01:37:31 +0000842 case MemRegion::FunctionTextRegionKind: {
Jordy Rose096aef92011-08-12 21:41:07 +0000843 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000844 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000845 os << "the address of the function '" << *FD << '\'';
Jordy Rose19c5dd12010-07-27 01:37:31 +0000846 else
847 os << "the address of a function";
848 return true;
849 }
850 case MemRegion::BlockTextRegionKind:
851 os << "block text";
852 return true;
853 case MemRegion::BlockDataRegionKind:
854 os << "a block";
855 return true;
856 case MemRegion::CXXThisRegionKind:
Zhongxing Xu02fe28c2010-11-26 08:52:48 +0000857 case MemRegion::CXXTempObjectRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000858 os << "a C++ temp object of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000859 return true;
860 case MemRegion::VarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000861 os << "a variable of type" << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000862 return true;
863 case MemRegion::FieldRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000864 os << "a field of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000865 return true;
866 case MemRegion::ObjCIvarRegionKind:
Ted Kremenek96979342011-08-12 20:02:48 +0000867 os << "an instance variable of type " << TVR->getValueType().getAsString();
Jordy Rose19c5dd12010-07-27 01:37:31 +0000868 return true;
869 default:
870 return false;
871 }
872}
873
Jordy Rosed325ffb2010-07-08 23:57:29 +0000874//===----------------------------------------------------------------------===//
Ted Kremenek9c149532010-12-01 21:57:22 +0000875// evaluation of individual function calls.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000876//===----------------------------------------------------------------------===//
877
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000878void CStringChecker::evalCopyCommon(CheckerContext &C,
879 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000880 ProgramStateRef state,
Jordy Rosed325ffb2010-07-08 23:57:29 +0000881 const Expr *Size, const Expr *Dest,
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000882 const Expr *Source, bool Restricted,
883 bool IsMempcpy) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000884 CurrentFunctionDescription = "memory copy function";
885
Jordy Rosed325ffb2010-07-08 23:57:29 +0000886 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000887 const LocationContext *LCtx = C.getLocationContext();
888 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000889 QualType sizeTy = Size->getType();
Jordy Rosed325ffb2010-07-08 23:57:29 +0000890
Ted Kremenek8bef8232012-01-26 21:29:00 +0000891 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose1e022412011-06-16 05:51:02 +0000892 llvm::tie(stateZeroSize, stateNonZeroSize) =
893 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000894
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000895 // Get the value of the Dest.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000896 SVal destVal = state->getSVal(Dest, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000897
898 // If the size is zero, there won't be any actual memory access, so
899 // just bind the return value to the destination buffer and return.
900 if (stateZeroSize) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000901 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, destVal);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000902 C.addTransition(stateZeroSize);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000903 }
Jordy Rosed325ffb2010-07-08 23:57:29 +0000904
905 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000906 if (stateNonZeroSize) {
Jordy Rose22d27172011-06-04 00:04:22 +0000907 state = stateNonZeroSize;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000908
909 // Ensure the destination is not null. If it is NULL there will be a
910 // NULL pointer dereference.
911 state = checkNonNull(C, state, Dest, destVal);
912 if (!state)
913 return;
914
915 // Get the value of the Src.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000916 SVal srcVal = state->getSVal(Source, LCtx);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000917
918 // Ensure the source is not null. If it is NULL there will be a
919 // NULL pointer dereference.
920 state = checkNonNull(C, state, Source, srcVal);
921 if (!state)
922 return;
923
Jordy Rose7182b962011-06-04 01:50:25 +0000924 // Ensure the accesses are valid and that the buffers do not overlap.
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000925 const char * const writeWarning =
926 "Memory copy function overflows destination buffer";
Jordy Rosee64f3112010-08-16 07:51:42 +0000927 state = CheckBufferAccess(C, state, Size, Dest, Source,
Jordy Rose9e49d9f2011-06-20 02:06:40 +0000928 writeWarning, /* sourceWarning = */ NULL);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000929 if (Restricted)
930 state = CheckOverlap(C, state, Size, Dest, Source);
Jordy Rosee64f3112010-08-16 07:51:42 +0000931
Jordy Rose7182b962011-06-04 01:50:25 +0000932 if (!state)
933 return;
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000934
Jordy Rose7182b962011-06-04 01:50:25 +0000935 // If this is mempcpy, get the byte after the last byte copied and
936 // bind the expr.
937 if (IsMempcpy) {
938 loc::MemRegionVal *destRegVal = dyn_cast<loc::MemRegionVal>(&destVal);
939 assert(destRegVal && "Destination should be a known MemRegionVal here");
940
941 // Get the length to copy.
942 NonLoc *lenValNonLoc = dyn_cast<NonLoc>(&sizeVal);
943
944 if (lenValNonLoc) {
945 // Get the byte after the last byte copied.
946 SVal lastElement = C.getSValBuilder().evalBinOpLN(state, BO_Add,
947 *destRegVal,
948 *lenValNonLoc,
949 Dest->getType());
950
951 // The byte after the last byte copied is the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000952 state = state->BindExpr(CE, LCtx, lastElement);
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000953 } else {
Jordy Rose7182b962011-06-04 01:50:25 +0000954 // If we don't know how much we copied, we can at least
955 // conjure a return value for later.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +0000956 unsigned Count = C.getCurrentBlockCount();
Jordy Rose7182b962011-06-04 01:50:25 +0000957 SVal result =
958 C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000959 state = state->BindExpr(CE, LCtx, result);
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000960 }
961
Jordy Rose7182b962011-06-04 01:50:25 +0000962 } else {
963 // All other copies return the destination buffer.
964 // (Well, bcopy() has a void return type, but this won't hurt.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000965 state = state->BindExpr(CE, LCtx, destVal);
Jordy Rosee64f3112010-08-16 07:51:42 +0000966 }
Jordy Rose7182b962011-06-04 01:50:25 +0000967
968 // Invalidate the destination.
969 // FIXME: Even if we can't perfectly model the copy, we should see if we
970 // can use LazyCompoundVals to copy the source values into the destination.
971 // This would probably remove any existing bindings past the end of the
972 // copied region, but that's still an improvement over blank invalidation.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000973 state = InvalidateBuffer(C, state, Dest,
974 state->getSVal(Dest, C.getLocationContext()));
Anna Zaks0bd6b112011-10-26 21:06:34 +0000975 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +0000976 }
977}
978
979
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000980void CStringChecker::evalMemcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000981 // void *memcpy(void *restrict dst, const void *restrict src, size_t n);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000982 // The return value is the address of the destination buffer.
Jordy Rosed325ffb2010-07-08 23:57:29 +0000983 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000984 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +0000985
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000986 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true);
987}
988
989void CStringChecker::evalMempcpy(CheckerContext &C, const CallExpr *CE) const {
990 // void *mempcpy(void *restrict dst, const void *restrict src, size_t n);
991 // The return value is a pointer to the byte following the last written byte.
992 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000993 ProgramStateRef state = C.getState();
Lenny Maioranib8b875b2011-03-31 21:36:53 +0000994
995 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1), true, true);
Jordy Roseccbf7ee2010-07-06 23:11:01 +0000996}
997
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +0000998void CStringChecker::evalMemmove(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +0000999 // void *memmove(void *dst, const void *src, size_t n);
1000 // The return value is the address of the destination buffer.
1001 const Expr *Dest = CE->getArg(0);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001002 ProgramStateRef state = C.getState();
Jordy Rose3f8bb2f2011-06-04 01:47:27 +00001003
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001004 evalCopyCommon(C, CE, state, CE->getArg(2), Dest, CE->getArg(1));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001005}
1006
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001007void CStringChecker::evalBcopy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosed325ffb2010-07-08 23:57:29 +00001008 // void bcopy(const void *src, void *dst, size_t n);
Lenny Maioranib8b875b2011-03-31 21:36:53 +00001009 evalCopyCommon(C, CE, C.getState(),
1010 CE->getArg(2), CE->getArg(1), CE->getArg(0));
Jordy Rosed325ffb2010-07-08 23:57:29 +00001011}
1012
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001013void CStringChecker::evalMemcmp(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001014 // int memcmp(const void *s1, const void *s2, size_t n);
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001015 CurrentFunctionDescription = "memory comparison function";
1016
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001017 const Expr *Left = CE->getArg(0);
1018 const Expr *Right = CE->getArg(1);
1019 const Expr *Size = CE->getArg(2);
1020
Ted Kremenek8bef8232012-01-26 21:29:00 +00001021 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001022 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001023
Jordy Rosed325ffb2010-07-08 23:57:29 +00001024 // See if the size argument is zero.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001025 const LocationContext *LCtx = C.getLocationContext();
1026 SVal sizeVal = state->getSVal(Size, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001027 QualType sizeTy = Size->getType();
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001028
Ted Kremenek8bef8232012-01-26 21:29:00 +00001029 ProgramStateRef stateZeroSize, stateNonZeroSize;
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001030 llvm::tie(stateZeroSize, stateNonZeroSize) =
1031 assumeZero(C, state, sizeVal, sizeTy);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001032
Jordy Rosed325ffb2010-07-08 23:57:29 +00001033 // If the size can be zero, the result will be 0 in that case, and we don't
1034 // have to check either of the buffers.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001035 if (stateZeroSize) {
1036 state = stateZeroSize;
Ted Kremenek5eca4822012-01-06 22:09:28 +00001037 state = state->BindExpr(CE, LCtx,
1038 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001039 C.addTransition(state);
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001040 }
1041
Jordy Rosed325ffb2010-07-08 23:57:29 +00001042 // If the size can be nonzero, we have to check the other arguments.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001043 if (stateNonZeroSize) {
1044 state = stateNonZeroSize;
Jordy Rosed325ffb2010-07-08 23:57:29 +00001045 // If we know the two buffers are the same, we know the result is 0.
1046 // First, get the two buffers' addresses. Another checker will have already
1047 // made sure they're not undefined.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001048 DefinedOrUnknownSVal LV =
1049 cast<DefinedOrUnknownSVal>(state->getSVal(Left, LCtx));
1050 DefinedOrUnknownSVal RV =
1051 cast<DefinedOrUnknownSVal>(state->getSVal(Right, LCtx));
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001052
Jordy Rosed325ffb2010-07-08 23:57:29 +00001053 // See if they are the same.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001054 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001055 ProgramStateRef StSameBuf, StNotSameBuf;
Ted Kremenek28f47b92010-12-01 22:16:56 +00001056 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001057
Jordy Rose1e022412011-06-16 05:51:02 +00001058 // If the two arguments might be the same buffer, we know the result is 0,
Jordy Rosed325ffb2010-07-08 23:57:29 +00001059 // and we only need to check one size.
1060 if (StSameBuf) {
1061 state = StSameBuf;
1062 state = CheckBufferAccess(C, state, Size, Left);
1063 if (state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001064 state = StSameBuf->BindExpr(CE, LCtx,
1065 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001066 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001067 }
1068 }
1069
1070 // If the two arguments might be different buffers, we have to check the
1071 // size of both of them.
1072 if (StNotSameBuf) {
1073 state = StNotSameBuf;
1074 state = CheckBufferAccess(C, state, Size, Left, Right);
1075 if (state) {
1076 // The return value is the comparison result, which we don't know.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001077 unsigned Count = C.getCurrentBlockCount();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001078 SVal CmpV = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001079 state = state->BindExpr(CE, LCtx, CmpV);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001080 C.addTransition(state);
Jordy Rosed325ffb2010-07-08 23:57:29 +00001081 }
1082 }
1083 }
Jordy Rosebc56d1f2010-07-07 08:15:01 +00001084}
1085
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001086void CStringChecker::evalstrLength(CheckerContext &C,
1087 const CallExpr *CE) const {
Jordy Rose19c5dd12010-07-27 01:37:31 +00001088 // size_t strlen(const char *s);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001089 evalstrLengthCommon(C, CE, /* IsStrnlen = */ false);
1090}
1091
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001092void CStringChecker::evalstrnLength(CheckerContext &C,
1093 const CallExpr *CE) const {
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001094 // size_t strnlen(const char *s, size_t maxlen);
1095 evalstrLengthCommon(C, CE, /* IsStrnlen = */ true);
1096}
1097
1098void CStringChecker::evalstrLengthCommon(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001099 bool IsStrnlen) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001100 CurrentFunctionDescription = "string length function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001101 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001102 const LocationContext *LCtx = C.getLocationContext();
Jordy Rose793bff32011-06-14 01:15:31 +00001103
1104 if (IsStrnlen) {
1105 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001106 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Jordy Rose793bff32011-06-14 01:15:31 +00001107
Ted Kremenek8bef8232012-01-26 21:29:00 +00001108 ProgramStateRef stateZeroSize, stateNonZeroSize;
Jordy Rose793bff32011-06-14 01:15:31 +00001109 llvm::tie(stateZeroSize, stateNonZeroSize) =
1110 assumeZero(C, state, maxlenVal, maxlenExpr->getType());
1111
1112 // If the size can be zero, the result will be 0 in that case, and we don't
1113 // have to check the string itself.
1114 if (stateZeroSize) {
1115 SVal zero = C.getSValBuilder().makeZeroVal(CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001116 stateZeroSize = stateZeroSize->BindExpr(CE, LCtx, zero);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001117 C.addTransition(stateZeroSize);
Jordy Rose793bff32011-06-14 01:15:31 +00001118 }
1119
1120 // If the size is GUARANTEED to be zero, we're done!
1121 if (!stateNonZeroSize)
1122 return;
1123
1124 // Otherwise, record the assumption that the size is nonzero.
1125 state = stateNonZeroSize;
1126 }
1127
1128 // Check that the string argument is non-null.
Jordy Rose19c5dd12010-07-27 01:37:31 +00001129 const Expr *Arg = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001130 SVal ArgVal = state->getSVal(Arg, LCtx);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001131
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001132 state = checkNonNull(C, state, Arg, ArgVal);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001133
Jordy Rosebd32bee2011-06-14 01:26:48 +00001134 if (!state)
1135 return;
Jordy Rosea5261542010-08-14 21:02:52 +00001136
Jordy Rosebd32bee2011-06-14 01:26:48 +00001137 SVal strLength = getCStringLength(C, state, Arg, ArgVal);
Jordy Rosea5261542010-08-14 21:02:52 +00001138
Jordy Rosebd32bee2011-06-14 01:26:48 +00001139 // If the argument isn't a valid C string, there's no valid state to
1140 // transition to.
1141 if (strLength.isUndef())
1142 return;
Jordy Rose793bff32011-06-14 01:15:31 +00001143
Jordy Rosebd32bee2011-06-14 01:26:48 +00001144 DefinedOrUnknownSVal result = UnknownVal();
Jordy Rose793bff32011-06-14 01:15:31 +00001145
Jordy Rosebd32bee2011-06-14 01:26:48 +00001146 // If the check is for strnlen() then bind the return value to no more than
1147 // the maxlen value.
1148 if (IsStrnlen) {
Jordy Roseee2fde12011-06-16 05:56:50 +00001149 QualType cmpTy = C.getSValBuilder().getConditionType();
Jordy Rose793bff32011-06-14 01:15:31 +00001150
Jordy Rosebd32bee2011-06-14 01:26:48 +00001151 // It's a little unfortunate to be getting this again,
1152 // but it's not that expensive...
1153 const Expr *maxlenExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001154 SVal maxlenVal = state->getSVal(maxlenExpr, LCtx);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001155
Jordy Rosebd32bee2011-06-14 01:26:48 +00001156 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1157 NonLoc *maxlenValNL = dyn_cast<NonLoc>(&maxlenVal);
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001158
Jordy Rosebd32bee2011-06-14 01:26:48 +00001159 if (strLengthNL && maxlenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001160 ProgramStateRef stateStringTooLong, stateStringNotTooLong;
Jordy Rose793bff32011-06-14 01:15:31 +00001161
Jordy Rosebd32bee2011-06-14 01:26:48 +00001162 // Check if the strLength is greater than the maxlen.
1163 llvm::tie(stateStringTooLong, stateStringNotTooLong) =
1164 state->assume(cast<DefinedOrUnknownSVal>
1165 (C.getSValBuilder().evalBinOpNN(state, BO_GT,
1166 *strLengthNL,
1167 *maxlenValNL,
1168 cmpTy)));
Jordy Rose793bff32011-06-14 01:15:31 +00001169
Jordy Rosebd32bee2011-06-14 01:26:48 +00001170 if (stateStringTooLong && !stateStringNotTooLong) {
1171 // If the string is longer than maxlen, return maxlen.
1172 result = *maxlenValNL;
1173 } else if (stateStringNotTooLong && !stateStringTooLong) {
1174 // If the string is shorter than maxlen, return its length.
1175 result = *strLengthNL;
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001176 }
1177 }
1178
Jordy Rosebd32bee2011-06-14 01:26:48 +00001179 if (result.isUnknown()) {
1180 // If we don't have enough information for a comparison, there's
1181 // no guarantee the full string length will actually be returned.
1182 // All we know is the return value is the min of the string length
1183 // and the limit. This is better than nothing.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001184 unsigned Count = C.getCurrentBlockCount();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001185 result = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
1186 NonLoc *resultNL = cast<NonLoc>(&result);
1187
1188 if (strLengthNL) {
1189 state = state->assume(cast<DefinedOrUnknownSVal>
1190 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1191 *resultNL,
1192 *strLengthNL,
1193 cmpTy)), true);
1194 }
1195
1196 if (maxlenValNL) {
1197 state = state->assume(cast<DefinedOrUnknownSVal>
1198 (C.getSValBuilder().evalBinOpNN(state, BO_LE,
1199 *resultNL,
1200 *maxlenValNL,
1201 cmpTy)), true);
1202 }
1203 }
1204
1205 } else {
1206 // This is a plain strlen(), not strnlen().
1207 result = cast<DefinedOrUnknownSVal>(strLength);
1208
1209 // If we don't know the length of the string, conjure a return
1210 // value, so it can be used in constraints, at least.
1211 if (result.isUnknown()) {
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001212 unsigned Count = C.getCurrentBlockCount();
Jordy Rosebd32bee2011-06-14 01:26:48 +00001213 result = C.getSValBuilder().getConjuredSymbolVal(NULL, CE, Count);
1214 }
Jordy Rose19c5dd12010-07-27 01:37:31 +00001215 }
Jordy Rosebd32bee2011-06-14 01:26:48 +00001216
1217 // Bind the return value.
1218 assert(!result.isUnknown() && "Should have conjured a value by now");
Ted Kremenek5eca4822012-01-06 22:09:28 +00001219 state = state->BindExpr(CE, LCtx, result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001220 C.addTransition(state);
Jordy Rose19c5dd12010-07-27 01:37:31 +00001221}
1222
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001223void CStringChecker::evalStrcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosee64f3112010-08-16 07:51:42 +00001224 // char *strcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001225 evalStrcpyCommon(C, CE,
1226 /* returnEnd = */ false,
1227 /* isBounded = */ false,
1228 /* isAppending = */ false);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001229}
1230
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001231void CStringChecker::evalStrncpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosec1525862011-06-04 00:05:23 +00001232 // char *strncpy(char *restrict dst, const char *restrict src, size_t n);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001233 evalStrcpyCommon(C, CE,
1234 /* returnEnd = */ false,
1235 /* isBounded = */ true,
1236 /* isAppending = */ false);
Jordy Rosee64f3112010-08-16 07:51:42 +00001237}
1238
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001239void CStringChecker::evalStpcpy(CheckerContext &C, const CallExpr *CE) const {
Jordy Rosee64f3112010-08-16 07:51:42 +00001240 // char *stpcpy(char *restrict dst, const char *restrict src);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001241 evalStrcpyCommon(C, CE,
1242 /* returnEnd = */ true,
1243 /* isBounded = */ false,
1244 /* isAppending = */ false);
1245}
1246
1247void CStringChecker::evalStrcat(CheckerContext &C, const CallExpr *CE) const {
1248 //char *strcat(char *restrict s1, const char *restrict s2);
1249 evalStrcpyCommon(C, CE,
1250 /* returnEnd = */ false,
1251 /* isBounded = */ false,
1252 /* isAppending = */ true);
1253}
1254
1255void CStringChecker::evalStrncat(CheckerContext &C, const CallExpr *CE) const {
1256 //char *strncat(char *restrict s1, const char *restrict s2, size_t n);
1257 evalStrcpyCommon(C, CE,
1258 /* returnEnd = */ false,
1259 /* isBounded = */ true,
1260 /* isAppending = */ true);
Jordy Rosee64f3112010-08-16 07:51:42 +00001261}
1262
Ted Kremenek9c149532010-12-01 21:57:22 +00001263void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001264 bool returnEnd, bool isBounded,
1265 bool isAppending) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001266 CurrentFunctionDescription = "string copy function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001267 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001268 const LocationContext *LCtx = C.getLocationContext();
Jordy Rosee64f3112010-08-16 07:51:42 +00001269
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001270 // Check that the destination is non-null.
Jordy Rosee64f3112010-08-16 07:51:42 +00001271 const Expr *Dst = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001272 SVal DstVal = state->getSVal(Dst, LCtx);
Jordy Rosee64f3112010-08-16 07:51:42 +00001273
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001274 state = checkNonNull(C, state, Dst, DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001275 if (!state)
1276 return;
1277
1278 // Check that the source is non-null.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001279 const Expr *srcExpr = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001280 SVal srcVal = state->getSVal(srcExpr, LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001281 state = checkNonNull(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001282 if (!state)
1283 return;
1284
1285 // Get the string length of the source.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001286 SVal strLength = getCStringLength(C, state, srcExpr, srcVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001287
1288 // If the source isn't a valid C string, give up.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001289 if (strLength.isUndef())
Jordy Rosee64f3112010-08-16 07:51:42 +00001290 return;
1291
Jordy Rosed5af0e12011-06-15 05:52:56 +00001292 SValBuilder &svalBuilder = C.getSValBuilder();
1293 QualType cmpTy = svalBuilder.getConditionType();
Jordy Rose8912aae2011-06-20 21:55:40 +00001294 QualType sizeTy = svalBuilder.getContext().getSizeType();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001295
Jordy Rose8912aae2011-06-20 21:55:40 +00001296 // These two values allow checking two kinds of errors:
1297 // - actual overflows caused by a source that doesn't fit in the destination
1298 // - potential overflows caused by a bound that could exceed the destination
Jordy Rosed5af0e12011-06-15 05:52:56 +00001299 SVal amountCopied = UnknownVal();
Jordy Rose8912aae2011-06-20 21:55:40 +00001300 SVal maxLastElementIndex = UnknownVal();
1301 const char *boundWarning = NULL;
Jordy Rosed5af0e12011-06-15 05:52:56 +00001302
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001303 // If the function is strncpy, strncat, etc... it is bounded.
1304 if (isBounded) {
1305 // Get the max number of characters to copy.
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001306 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001307 SVal lenVal = state->getSVal(lenExpr, LCtx);
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001308
Jordy Rosed5af0e12011-06-15 05:52:56 +00001309 // Protect against misdeclared strncpy().
Jordy Rose8912aae2011-06-20 21:55:40 +00001310 lenVal = svalBuilder.evalCast(lenVal, sizeTy, lenExpr->getType());
Jordy Rosed5af0e12011-06-15 05:52:56 +00001311
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001312 NonLoc *strLengthNL = dyn_cast<NonLoc>(&strLength);
1313 NonLoc *lenValNL = dyn_cast<NonLoc>(&lenVal);
1314
Jordy Rosed5af0e12011-06-15 05:52:56 +00001315 // If we know both values, we might be able to figure out how much
1316 // we're copying.
1317 if (strLengthNL && lenValNL) {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001318 ProgramStateRef stateSourceTooLong, stateSourceNotTooLong;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001319
Jordy Rosed5af0e12011-06-15 05:52:56 +00001320 // Check if the max number to copy is less than the length of the src.
Jordy Rose8912aae2011-06-20 21:55:40 +00001321 // If the bound is equal to the source length, strncpy won't null-
1322 // terminate the result!
Jordy Rosed5af0e12011-06-15 05:52:56 +00001323 llvm::tie(stateSourceTooLong, stateSourceNotTooLong) =
1324 state->assume(cast<DefinedOrUnknownSVal>
Jordy Rose8912aae2011-06-20 21:55:40 +00001325 (svalBuilder.evalBinOpNN(state, BO_GE, *strLengthNL,
Jordy Rosed5af0e12011-06-15 05:52:56 +00001326 *lenValNL, cmpTy)));
1327
1328 if (stateSourceTooLong && !stateSourceNotTooLong) {
1329 // Max number to copy is less than the length of the src, so the actual
1330 // strLength copied is the max number arg.
1331 state = stateSourceTooLong;
1332 amountCopied = lenVal;
1333
1334 } else if (!stateSourceTooLong && stateSourceNotTooLong) {
1335 // The source buffer entirely fits in the bound.
1336 state = stateSourceNotTooLong;
1337 amountCopied = strLength;
1338 }
1339 }
1340
Jordy Rose5e5f1502011-06-20 03:49:16 +00001341 // We still want to know if the bound is known to be too large.
Jordy Rose8912aae2011-06-20 21:55:40 +00001342 if (lenValNL) {
1343 if (isAppending) {
1344 // For strncat, the check is strlen(dst) + lenVal < sizeof(dst)
1345
1346 // Get the string length of the destination. If the destination is
1347 // memory that can't have a string length, we shouldn't be copying
1348 // into it anyway.
1349 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1350 if (dstStrLength.isUndef())
1351 return;
1352
1353 if (NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength)) {
1354 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Add,
1355 *lenValNL,
1356 *dstStrLengthNL,
1357 sizeTy);
1358 boundWarning = "Size argument is greater than the free space in the "
1359 "destination buffer";
1360 }
1361
1362 } else {
1363 // For strncpy, this is just checking that lenVal <= sizeof(dst)
1364 // (Yes, strncpy and strncat differ in how they treat termination.
1365 // strncat ALWAYS terminates, but strncpy doesn't.)
1366 NonLoc one = cast<NonLoc>(svalBuilder.makeIntVal(1, sizeTy));
1367 maxLastElementIndex = svalBuilder.evalBinOpNN(state, BO_Sub, *lenValNL,
1368 one, sizeTy);
1369 boundWarning = "Size argument is greater than the length of the "
1370 "destination buffer";
1371 }
1372 }
Jordy Rose5e5f1502011-06-20 03:49:16 +00001373
Jordy Rosed5af0e12011-06-15 05:52:56 +00001374 // If we couldn't pin down the copy length, at least bound it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001375 // FIXME: We should actually run this code path for append as well, but
1376 // right now it creates problems with constraints (since we can end up
1377 // trying to pass constraints from symbol to symbol).
1378 if (amountCopied.isUnknown() && !isAppending) {
Jordy Rosed5af0e12011-06-15 05:52:56 +00001379 // Try to get a "hypothetical" string length symbol, which we can later
1380 // set as a real value if that turns out to be the case.
1381 amountCopied = getCStringLength(C, state, lenExpr, srcVal, true);
1382 assert(!amountCopied.isUndef());
1383
1384 if (NonLoc *amountCopiedNL = dyn_cast<NonLoc>(&amountCopied)) {
1385 if (lenValNL) {
1386 // amountCopied <= lenVal
1387 SVal copiedLessThanBound = svalBuilder.evalBinOpNN(state, BO_LE,
1388 *amountCopiedNL,
1389 *lenValNL,
1390 cmpTy);
1391 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanBound),
1392 true);
1393 if (!state)
1394 return;
1395 }
1396
1397 if (strLengthNL) {
1398 // amountCopied <= strlen(source)
1399 SVal copiedLessThanSrc = svalBuilder.evalBinOpNN(state, BO_LE,
1400 *amountCopiedNL,
1401 *strLengthNL,
1402 cmpTy);
1403 state = state->assume(cast<DefinedOrUnknownSVal>(copiedLessThanSrc),
1404 true);
1405 if (!state)
1406 return;
1407 }
1408 }
1409 }
1410
1411 } else {
1412 // The function isn't bounded. The amount copied should match the length
1413 // of the source buffer.
1414 amountCopied = strLength;
Ted Kremenek0ef473f2011-02-22 04:58:34 +00001415 }
1416
Jordy Rosed5af0e12011-06-15 05:52:56 +00001417 assert(state);
1418
1419 // This represents the number of characters copied into the destination
1420 // buffer. (It may not actually be the strlen if the destination buffer
1421 // is not terminated.)
1422 SVal finalStrLength = UnknownVal();
1423
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001424 // If this is an appending function (strcat, strncat...) then set the
1425 // string length to strlen(src) + strlen(dst) since the buffer will
1426 // ultimately contain both.
1427 if (isAppending) {
Jordy Rose1e022412011-06-16 05:51:02 +00001428 // Get the string length of the destination. If the destination is memory
1429 // that can't have a string length, we shouldn't be copying into it anyway.
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001430 SVal dstStrLength = getCStringLength(C, state, Dst, DstVal);
1431 if (dstStrLength.isUndef())
1432 return;
1433
Jordy Rosed5af0e12011-06-15 05:52:56 +00001434 NonLoc *srcStrLengthNL = dyn_cast<NonLoc>(&amountCopied);
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001435 NonLoc *dstStrLengthNL = dyn_cast<NonLoc>(&dstStrLength);
1436
Jordy Rosed5af0e12011-06-15 05:52:56 +00001437 // If we know both string lengths, we might know the final string length.
1438 if (srcStrLengthNL && dstStrLengthNL) {
1439 // Make sure the two lengths together don't overflow a size_t.
1440 state = checkAdditionOverflow(C, state, *srcStrLengthNL, *dstStrLengthNL);
1441 if (!state)
1442 return;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001443
Jordy Rosed5af0e12011-06-15 05:52:56 +00001444 finalStrLength = svalBuilder.evalBinOpNN(state, BO_Add, *srcStrLengthNL,
1445 *dstStrLengthNL, sizeTy);
1446 }
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001447
Jordy Rosed5af0e12011-06-15 05:52:56 +00001448 // If we couldn't get a single value for the final string length,
1449 // we can at least bound it by the individual lengths.
1450 if (finalStrLength.isUnknown()) {
1451 // Try to get a "hypothetical" string length symbol, which we can later
1452 // set as a real value if that turns out to be the case.
1453 finalStrLength = getCStringLength(C, state, CE, DstVal, true);
1454 assert(!finalStrLength.isUndef());
1455
1456 if (NonLoc *finalStrLengthNL = dyn_cast<NonLoc>(&finalStrLength)) {
1457 if (srcStrLengthNL) {
1458 // finalStrLength >= srcStrLength
1459 SVal sourceInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1460 *finalStrLengthNL,
1461 *srcStrLengthNL,
1462 cmpTy);
1463 state = state->assume(cast<DefinedOrUnknownSVal>(sourceInResult),
1464 true);
1465 if (!state)
1466 return;
1467 }
1468
1469 if (dstStrLengthNL) {
1470 // finalStrLength >= dstStrLength
1471 SVal destInResult = svalBuilder.evalBinOpNN(state, BO_GE,
1472 *finalStrLengthNL,
1473 *dstStrLengthNL,
1474 cmpTy);
1475 state = state->assume(cast<DefinedOrUnknownSVal>(destInResult),
1476 true);
1477 if (!state)
1478 return;
1479 }
1480 }
1481 }
1482
1483 } else {
1484 // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and
1485 // the final string length will match the input string length.
1486 finalStrLength = amountCopied;
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001487 }
1488
Jordy Rosed5af0e12011-06-15 05:52:56 +00001489 // The final result of the function will either be a pointer past the last
1490 // copied element, or a pointer to the start of the destination buffer.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001491 SVal Result = (returnEnd ? UnknownVal() : DstVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001492
Jordy Rosed5af0e12011-06-15 05:52:56 +00001493 assert(state);
1494
Jordy Rosee64f3112010-08-16 07:51:42 +00001495 // If the destination is a MemRegion, try to check for a buffer overflow and
1496 // record the new string length.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001497 if (loc::MemRegionVal *dstRegVal = dyn_cast<loc::MemRegionVal>(&DstVal)) {
Jordy Rose8912aae2011-06-20 21:55:40 +00001498 QualType ptrTy = Dst->getType();
1499
1500 // If we have an exact value on a bounded copy, use that to check for
1501 // overflows, rather than our estimate about how much is actually copied.
1502 if (boundWarning) {
1503 if (NonLoc *maxLastNL = dyn_cast<NonLoc>(&maxLastElementIndex)) {
1504 SVal maxLastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
1505 *maxLastNL, ptrTy);
1506 state = CheckLocation(C, state, CE->getArg(2), maxLastElement,
1507 boundWarning);
1508 if (!state)
1509 return;
1510 }
1511 }
1512
1513 // Then, if the final length is known...
Jordy Rosed5af0e12011-06-15 05:52:56 +00001514 if (NonLoc *knownStrLength = dyn_cast<NonLoc>(&finalStrLength)) {
1515 SVal lastElement = svalBuilder.evalBinOpLN(state, BO_Add, *dstRegVal,
Jordy Rose8912aae2011-06-20 21:55:40 +00001516 *knownStrLength, ptrTy);
Jordy Rosee64f3112010-08-16 07:51:42 +00001517
Jordy Rose8912aae2011-06-20 21:55:40 +00001518 // ...and we haven't checked the bound, we'll check the actual copy.
1519 if (!boundWarning) {
1520 const char * const warningMsg =
1521 "String copy function overflows destination buffer";
1522 state = CheckLocation(C, state, Dst, lastElement, warningMsg);
1523 if (!state)
1524 return;
1525 }
Jordy Rosee64f3112010-08-16 07:51:42 +00001526
1527 // If this is a stpcpy-style copy, the last element is the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001528 if (returnEnd)
1529 Result = lastElement;
Jordy Rosee64f3112010-08-16 07:51:42 +00001530 }
1531
1532 // Invalidate the destination. This must happen before we set the C string
1533 // length because invalidation will clear the length.
1534 // FIXME: Even if we can't perfectly model the copy, we should see if we
1535 // can use LazyCompoundVals to copy the source values into the destination.
1536 // This would probably remove any existing bindings past the end of the
1537 // string, but that's still an improvement over blank invalidation.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001538 state = InvalidateBuffer(C, state, Dst, *dstRegVal);
Jordy Rosee64f3112010-08-16 07:51:42 +00001539
Jordy Rose5e5f1502011-06-20 03:49:16 +00001540 // Set the C string length of the destination, if we know it.
Jordy Rose8912aae2011-06-20 21:55:40 +00001541 if (isBounded && !isAppending) {
1542 // strncpy is annoying in that it doesn't guarantee to null-terminate
1543 // the result string. If the original string didn't fit entirely inside
1544 // the bound (including the null-terminator), we don't know how long the
1545 // result is.
1546 if (amountCopied != strLength)
1547 finalStrLength = UnknownVal();
1548 }
1549 state = setCStringLength(state, dstRegVal->getRegion(), finalStrLength);
Jordy Rosee64f3112010-08-16 07:51:42 +00001550 }
1551
Jordy Rosed5af0e12011-06-15 05:52:56 +00001552 assert(state);
1553
Jordy Rosee64f3112010-08-16 07:51:42 +00001554 // If this is a stpcpy-style copy, but we were unable to check for a buffer
1555 // overflow, we still need a result. Conjure a return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001556 if (returnEnd && Result.isUnknown()) {
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001557 unsigned Count = C.getCurrentBlockCount();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001558 Result = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Jordy Rosee64f3112010-08-16 07:51:42 +00001559 }
1560
1561 // Set the return value.
Ted Kremenek5eca4822012-01-06 22:09:28 +00001562 state = state->BindExpr(CE, LCtx, Result);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001563 C.addTransition(state);
Jordy Rosee64f3112010-08-16 07:51:42 +00001564}
1565
Lenny Maiorani318dd922011-04-12 17:08:43 +00001566void CStringChecker::evalStrcmp(CheckerContext &C, const CallExpr *CE) const {
Jordy Roseadc42d42011-06-16 07:13:34 +00001567 //int strcmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001568 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ false);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001569}
Lenny Maiorani318dd922011-04-12 17:08:43 +00001570
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001571void CStringChecker::evalStrncmp(CheckerContext &C, const CallExpr *CE) const {
Jordy Roseadc42d42011-06-16 07:13:34 +00001572 //int strncmp(const char *s1, const char *s2, size_t n);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001573 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ false);
1574}
1575
1576void CStringChecker::evalStrcasecmp(CheckerContext &C,
1577 const CallExpr *CE) const {
Jordy Roseadc42d42011-06-16 07:13:34 +00001578 //int strcasecmp(const char *s1, const char *s2);
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001579 evalStrcmpCommon(C, CE, /* isBounded = */ false, /* ignoreCase = */ true);
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001580}
1581
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001582void CStringChecker::evalStrncasecmp(CheckerContext &C,
1583 const CallExpr *CE) const {
Jordy Roseadc42d42011-06-16 07:13:34 +00001584 //int strncasecmp(const char *s1, const char *s2, size_t n);
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001585 evalStrcmpCommon(C, CE, /* isBounded = */ true, /* ignoreCase = */ true);
1586}
1587
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001588void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallExpr *CE,
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001589 bool isBounded, bool ignoreCase) const {
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001590 CurrentFunctionDescription = "string comparison function";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001591 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001592 const LocationContext *LCtx = C.getLocationContext();
Lenny Maiorani318dd922011-04-12 17:08:43 +00001593
1594 // Check that the first string is non-null
1595 const Expr *s1 = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001596 SVal s1Val = state->getSVal(s1, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001597 state = checkNonNull(C, state, s1, s1Val);
1598 if (!state)
1599 return;
1600
1601 // Check that the second string is non-null.
1602 const Expr *s2 = CE->getArg(1);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001603 SVal s2Val = state->getSVal(s2, LCtx);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001604 state = checkNonNull(C, state, s2, s2Val);
1605 if (!state)
1606 return;
1607
1608 // Get the string length of the first string or give up.
1609 SVal s1Length = getCStringLength(C, state, s1, s1Val);
1610 if (s1Length.isUndef())
1611 return;
1612
1613 // Get the string length of the second string or give up.
1614 SVal s2Length = getCStringLength(C, state, s2, s2Val);
1615 if (s2Length.isUndef())
1616 return;
1617
Jordy Roseadc42d42011-06-16 07:13:34 +00001618 // If we know the two buffers are the same, we know the result is 0.
1619 // First, get the two buffers' addresses. Another checker will have already
1620 // made sure they're not undefined.
1621 DefinedOrUnknownSVal LV = cast<DefinedOrUnknownSVal>(s1Val);
1622 DefinedOrUnknownSVal RV = cast<DefinedOrUnknownSVal>(s2Val);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001623
Jordy Roseadc42d42011-06-16 07:13:34 +00001624 // See if they are the same.
Lenny Maiorani318dd922011-04-12 17:08:43 +00001625 SValBuilder &svalBuilder = C.getSValBuilder();
Jordy Roseadc42d42011-06-16 07:13:34 +00001626 DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, LV, RV);
Ted Kremenek8bef8232012-01-26 21:29:00 +00001627 ProgramStateRef StSameBuf, StNotSameBuf;
Jordy Roseadc42d42011-06-16 07:13:34 +00001628 llvm::tie(StSameBuf, StNotSameBuf) = state->assume(SameBuf);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001629
Jordy Roseadc42d42011-06-16 07:13:34 +00001630 // If the two arguments might be the same buffer, we know the result is 0,
1631 // and we only need to check one size.
1632 if (StSameBuf) {
Ted Kremenek5eca4822012-01-06 22:09:28 +00001633 StSameBuf = StSameBuf->BindExpr(CE, LCtx,
1634 svalBuilder.makeZeroVal(CE->getType()));
Anna Zaks0bd6b112011-10-26 21:06:34 +00001635 C.addTransition(StSameBuf);
Jordy Roseadc42d42011-06-16 07:13:34 +00001636
1637 // If the two arguments are GUARANTEED to be the same, we're done!
1638 if (!StNotSameBuf)
1639 return;
1640 }
1641
1642 assert(StNotSameBuf);
1643 state = StNotSameBuf;
1644
1645 // At this point we can go about comparing the two buffers.
1646 // For now, we only do this if they're both known string literals.
1647
1648 // Attempt to extract string literals from both expressions.
1649 const StringLiteral *s1StrLiteral = getCStringLiteral(C, state, s1, s1Val);
1650 const StringLiteral *s2StrLiteral = getCStringLiteral(C, state, s2, s2Val);
1651 bool canComputeResult = false;
1652
1653 if (s1StrLiteral && s2StrLiteral) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001654 StringRef s1StrRef = s1StrLiteral->getString();
1655 StringRef s2StrRef = s2StrLiteral->getString();
Jordy Roseadc42d42011-06-16 07:13:34 +00001656
1657 if (isBounded) {
1658 // Get the max number of characters to compare.
1659 const Expr *lenExpr = CE->getArg(2);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001660 SVal lenVal = state->getSVal(lenExpr, LCtx);
Jordy Roseadc42d42011-06-16 07:13:34 +00001661
1662 // If the length is known, we can get the right substrings.
1663 if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, lenVal)) {
1664 // Create substrings of each to compare the prefix.
1665 s1StrRef = s1StrRef.substr(0, (size_t)len->getZExtValue());
1666 s2StrRef = s2StrRef.substr(0, (size_t)len->getZExtValue());
1667 canComputeResult = true;
1668 }
1669 } else {
1670 // This is a normal, unbounded strcmp.
1671 canComputeResult = true;
1672 }
1673
1674 if (canComputeResult) {
1675 // Real strcmp stops at null characters.
1676 size_t s1Term = s1StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001677 if (s1Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001678 s1StrRef = s1StrRef.substr(0, s1Term);
1679
1680 size_t s2Term = s2StrRef.find('\0');
Chris Lattner5f9e2722011-07-23 10:55:15 +00001681 if (s2Term != StringRef::npos)
Jordy Roseadc42d42011-06-16 07:13:34 +00001682 s2StrRef = s2StrRef.substr(0, s2Term);
1683
1684 // Use StringRef's comparison methods to compute the actual result.
1685 int result;
1686
1687 if (ignoreCase) {
1688 // Compare string 1 to string 2 the same way strcasecmp() does.
1689 result = s1StrRef.compare_lower(s2StrRef);
1690 } else {
1691 // Compare string 1 to string 2 the same way strcmp() does.
1692 result = s1StrRef.compare(s2StrRef);
1693 }
1694
1695 // Build the SVal of the comparison and bind the return value.
1696 SVal resultVal = svalBuilder.makeIntVal(result, CE->getType());
Ted Kremenek5eca4822012-01-06 22:09:28 +00001697 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001698 }
1699 }
1700
1701 if (!canComputeResult) {
1702 // Conjure a symbolic value. It's the best we can do.
Anna Zaks5d0ea6d2011-10-04 20:43:05 +00001703 unsigned Count = C.getCurrentBlockCount();
Jordy Roseadc42d42011-06-16 07:13:34 +00001704 SVal resultVal = svalBuilder.getConjuredSymbolVal(NULL, CE, Count);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001705 state = state->BindExpr(CE, LCtx, resultVal);
Jordy Roseadc42d42011-06-16 07:13:34 +00001706 }
1707
1708 // Record this as a possible path.
Anna Zaks0bd6b112011-10-26 21:06:34 +00001709 C.addTransition(state);
Lenny Maiorani318dd922011-04-12 17:08:43 +00001710}
1711
Jordy Rosed325ffb2010-07-08 23:57:29 +00001712//===----------------------------------------------------------------------===//
Jordy Rosea5261542010-08-14 21:02:52 +00001713// The driver method, and other Checker callbacks.
Jordy Rosed325ffb2010-07-08 23:57:29 +00001714//===----------------------------------------------------------------------===//
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001715
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001716bool CStringChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
Anna Zaksb805c8f2011-12-01 05:57:37 +00001717 StringRef Name = C.getCalleeName(CE);
1718 if (Name.empty())
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001719 return false;
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001720 if (Name.startswith("__builtin_"))
1721 Name = Name.substr(10);
1722
Ted Kremenek9c149532010-12-01 21:57:22 +00001723 FnCheck evalFunction = llvm::StringSwitch<FnCheck>(Name)
1724 .Cases("memcpy", "__memcpy_chk", &CStringChecker::evalMemcpy)
Jordy Rosebe460d82011-06-03 23:42:56 +00001725 .Cases("mempcpy", "__mempcpy_chk", &CStringChecker::evalMempcpy)
Ted Kremenek9c149532010-12-01 21:57:22 +00001726 .Cases("memcmp", "bcmp", &CStringChecker::evalMemcmp)
1727 .Cases("memmove", "__memmove_chk", &CStringChecker::evalMemmove)
1728 .Cases("strcpy", "__strcpy_chk", &CStringChecker::evalStrcpy)
Jordy Rose5e5f1502011-06-20 03:49:16 +00001729 .Cases("strncpy", "__strncpy_chk", &CStringChecker::evalStrncpy)
Ted Kremenek9c149532010-12-01 21:57:22 +00001730 .Cases("stpcpy", "__stpcpy_chk", &CStringChecker::evalStpcpy)
Lenny Maiorani067bbd02011-04-09 15:12:58 +00001731 .Cases("strcat", "__strcat_chk", &CStringChecker::evalStrcat)
1732 .Cases("strncat", "__strncat_chk", &CStringChecker::evalStrncat)
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001733 .Case("strlen", &CStringChecker::evalstrLength)
Ted Kremenekbe4242c2011-02-22 04:55:05 +00001734 .Case("strnlen", &CStringChecker::evalstrnLength)
Lenny Maiorani318dd922011-04-12 17:08:43 +00001735 .Case("strcmp", &CStringChecker::evalStrcmp)
Lenny Maiorani357f6ee2011-04-25 22:21:00 +00001736 .Case("strncmp", &CStringChecker::evalStrncmp)
Lenny Maioranibd1d16a2011-04-28 15:09:11 +00001737 .Case("strcasecmp", &CStringChecker::evalStrcasecmp)
Lenny Maiorani454fd2d2011-05-02 19:05:49 +00001738 .Case("strncasecmp", &CStringChecker::evalStrncasecmp)
Ted Kremenek9c149532010-12-01 21:57:22 +00001739 .Case("bcopy", &CStringChecker::evalBcopy)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001740 .Default(NULL);
1741
Jordy Rosed325ffb2010-07-08 23:57:29 +00001742 // If the callee isn't a string function, let another checker handle it.
Ted Kremenek9c149532010-12-01 21:57:22 +00001743 if (!evalFunction)
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001744 return false;
1745
Jordy Rose9e49d9f2011-06-20 02:06:40 +00001746 // Make sure each function sets its own description.
1747 // (But don't bother in a release build.)
1748 assert(!(CurrentFunctionDescription = NULL));
1749
Jordy Rosed325ffb2010-07-08 23:57:29 +00001750 // Check and evaluate the call.
Ted Kremenek9c149532010-12-01 21:57:22 +00001751 (this->*evalFunction)(C, CE);
Anna Zaks57300762012-02-07 00:56:14 +00001752
1753 // If the evaluate call resulted in no change, chain to the next eval call
1754 // handler.
1755 // Note, the custom CString evaluation calls assume that basic safety
1756 // properties are held. However, if the user chooses to turn off some of these
1757 // checks, we ignore the issues and leave the call evaluation to a generic
1758 // handler.
1759 if (!C.isDifferent())
1760 return false;
1761
Jordy Roseccbf7ee2010-07-06 23:11:01 +00001762 return true;
1763}
Jordy Rosea5261542010-08-14 21:02:52 +00001764
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001765void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001766 // Record string length for char a[] = "abc";
Ted Kremenek8bef8232012-01-26 21:29:00 +00001767 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001768
1769 for (DeclStmt::const_decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1770 I != E; ++I) {
1771 const VarDecl *D = dyn_cast<VarDecl>(*I);
1772 if (!D)
1773 continue;
1774
1775 // FIXME: Handle array fields of structs.
1776 if (!D->getType()->isArrayType())
1777 continue;
1778
1779 const Expr *Init = D->getInit();
1780 if (!Init)
1781 continue;
1782 if (!isa<StringLiteral>(Init))
1783 continue;
1784
Anna Zaks39ac1872011-10-26 21:06:44 +00001785 Loc VarLoc = state->getLValue(D, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001786 const MemRegion *MR = VarLoc.getAsRegion();
1787 if (!MR)
1788 continue;
1789
Ted Kremenek5eca4822012-01-06 22:09:28 +00001790 SVal StrVal = state->getSVal(Init, C.getLocationContext());
Jordy Rosea5261542010-08-14 21:02:52 +00001791 assert(StrVal.isValid() && "Initializer string is unknown or undefined");
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001792 DefinedOrUnknownSVal strLength
1793 = cast<DefinedOrUnknownSVal>(getCStringLength(C, state, Init, StrVal));
Jordy Rosea5261542010-08-14 21:02:52 +00001794
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001795 state = state->set<CStringLength>(MR, strLength);
Jordy Rosea5261542010-08-14 21:02:52 +00001796 }
1797
Anna Zaks0bd6b112011-10-26 21:06:34 +00001798 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001799}
1800
Ted Kremenek8bef8232012-01-26 21:29:00 +00001801bool CStringChecker::wantsRegionChangeUpdate(ProgramStateRef state) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001802 CStringLength::EntryMap Entries = state->get<CStringLength>();
1803 return !Entries.isEmpty();
1804}
1805
Ted Kremenek8bef8232012-01-26 21:29:00 +00001806ProgramStateRef
1807CStringChecker::checkRegionChanges(ProgramStateRef state,
Ted Kremenek35bdbf42011-05-02 19:42:42 +00001808 const StoreManager::InvalidatedSymbols *,
Jordy Rose537716a2011-08-27 22:51:26 +00001809 ArrayRef<const MemRegion *> ExplicitRegions,
1810 ArrayRef<const MemRegion *> Regions) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001811 CStringLength::EntryMap Entries = state->get<CStringLength>();
1812 if (Entries.isEmpty())
1813 return state;
1814
1815 llvm::SmallPtrSet<const MemRegion *, 8> Invalidated;
1816 llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions;
1817
1818 // First build sets for the changed regions and their super-regions.
Jordy Rose537716a2011-08-27 22:51:26 +00001819 for (ArrayRef<const MemRegion *>::iterator
1820 I = Regions.begin(), E = Regions.end(); I != E; ++I) {
1821 const MemRegion *MR = *I;
Jordy Rosea5261542010-08-14 21:02:52 +00001822 Invalidated.insert(MR);
1823
1824 SuperRegions.insert(MR);
1825 while (const SubRegion *SR = dyn_cast<SubRegion>(MR)) {
1826 MR = SR->getSuperRegion();
1827 SuperRegions.insert(MR);
1828 }
1829 }
1830
1831 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1832
1833 // Then loop over the entries in the current state.
1834 for (CStringLength::EntryMap::iterator I = Entries.begin(),
1835 E = Entries.end(); I != E; ++I) {
1836 const MemRegion *MR = I.getKey();
1837
1838 // Is this entry for a super-region of a changed region?
1839 if (SuperRegions.count(MR)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001840 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001841 continue;
1842 }
1843
1844 // Is this entry for a sub-region of a changed region?
1845 const MemRegion *Super = MR;
1846 while (const SubRegion *SR = dyn_cast<SubRegion>(Super)) {
1847 Super = SR->getSuperRegion();
1848 if (Invalidated.count(Super)) {
Ted Kremenek3baf6722010-11-24 00:54:37 +00001849 Entries = F.remove(Entries, MR);
Jordy Rosea5261542010-08-14 21:02:52 +00001850 break;
1851 }
1852 }
1853 }
1854
1855 return state->set<CStringLength>(Entries);
1856}
1857
Ted Kremenek8bef8232012-01-26 21:29:00 +00001858void CStringChecker::checkLiveSymbols(ProgramStateRef state,
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001859 SymbolReaper &SR) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001860 // Mark all symbols in our string length map as valid.
1861 CStringLength::EntryMap Entries = state->get<CStringLength>();
1862
1863 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1864 I != E; ++I) {
1865 SVal Len = I.getData();
Jordy Rosed5af0e12011-06-15 05:52:56 +00001866
Anna Zaks1d1d5152011-12-06 23:12:33 +00001867 for (SymExpr::symbol_iterator si = Len.symbol_begin(),
1868 se = Len.symbol_end(); si != se; ++si)
Jordy Rosed5af0e12011-06-15 05:52:56 +00001869 SR.markInUse(*si);
Jordy Rosea5261542010-08-14 21:02:52 +00001870 }
1871}
1872
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001873void CStringChecker::checkDeadSymbols(SymbolReaper &SR,
1874 CheckerContext &C) const {
Jordy Rosea5261542010-08-14 21:02:52 +00001875 if (!SR.hasDeadSymbols())
1876 return;
1877
Ted Kremenek8bef8232012-01-26 21:29:00 +00001878 ProgramStateRef state = C.getState();
Jordy Rosea5261542010-08-14 21:02:52 +00001879 CStringLength::EntryMap Entries = state->get<CStringLength>();
1880 if (Entries.isEmpty())
1881 return;
1882
1883 CStringLength::EntryMap::Factory &F = state->get_context<CStringLength>();
1884 for (CStringLength::EntryMap::iterator I = Entries.begin(), E = Entries.end();
1885 I != E; ++I) {
1886 SVal Len = I.getData();
1887 if (SymbolRef Sym = Len.getAsSymbol()) {
1888 if (SR.isDead(Sym))
Ted Kremenek3baf6722010-11-24 00:54:37 +00001889 Entries = F.remove(Entries, I.getKey());
Jordy Rosea5261542010-08-14 21:02:52 +00001890 }
1891 }
1892
1893 state = state->set<CStringLength>(Entries);
Anna Zaks0bd6b112011-10-26 21:06:34 +00001894 C.addTransition(state);
Jordy Rosea5261542010-08-14 21:02:52 +00001895}
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001896
Anna Zaks57300762012-02-07 00:56:14 +00001897#define REGISTER_CHECKER(name) \
1898void ento::register##name(CheckerManager &mgr) {\
1899 static CStringChecker *TheChecker = 0; \
1900 if (TheChecker == 0) \
1901 TheChecker = mgr.registerChecker<CStringChecker>(); \
1902 TheChecker->Filter.Check##name = true; \
Argyrios Kyrtzidis183ff982011-02-24 01:05:30 +00001903}
Anna Zaks57300762012-02-07 00:56:14 +00001904
1905REGISTER_CHECKER(CStringNullArg)
1906REGISTER_CHECKER(CStringOutOfBounds)
1907REGISTER_CHECKER(CStringBufferOverlap)
1908REGISTER_CHECKER(CStringNotNullTerm)