1 | //= CStringChecker.cpp - Checks calls to C string functions --------*- C++ -*-// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This defines CStringChecker, which is an assortment of checks on calls |
10 | // to functions in <string.h>. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #include "InterCheckerAPI.h" |
15 | #include "clang/AST/OperationKinds.h" |
16 | #include "clang/Basic/CharInfo.h" |
17 | #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" |
18 | #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h" |
19 | #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" |
20 | #include "clang/StaticAnalyzer/Core/Checker.h" |
21 | #include "clang/StaticAnalyzer/Core/CheckerManager.h" |
22 | #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h" |
23 | #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" |
24 | #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" |
25 | #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h" |
26 | #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" |
27 | #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" |
28 | #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" |
29 | #include "llvm/ADT/APSInt.h" |
30 | #include "llvm/ADT/STLExtras.h" |
31 | #include "llvm/ADT/StringExtras.h" |
32 | #include "llvm/Support/raw_ostream.h" |
33 | #include <functional> |
34 | #include <optional> |
35 | |
36 | using namespace clang; |
37 | using namespace ento; |
38 | using namespace std::placeholders; |
39 | |
40 | namespace { |
41 | struct AnyArgExpr { |
42 | const Expr *Expression; |
43 | unsigned ArgumentIndex; |
44 | }; |
45 | struct SourceArgExpr : AnyArgExpr {}; |
46 | struct DestinationArgExpr : AnyArgExpr {}; |
47 | struct SizeArgExpr : AnyArgExpr {}; |
48 | |
49 | using ErrorMessage = SmallString<128>; |
50 | enum class AccessKind { write, read }; |
51 | |
52 | static ErrorMessage createOutOfBoundErrorMsg(StringRef FunctionDescription, |
53 | AccessKind Access) { |
54 | ErrorMessage Message; |
55 | llvm::raw_svector_ostream Os(Message); |
56 | |
57 | // Function classification like: Memory copy function |
58 | Os << toUppercase(c: FunctionDescription.front()) |
59 | << &FunctionDescription.data()[1]; |
60 | |
61 | if (Access == AccessKind::write) { |
62 | Os << " overflows the destination buffer" ; |
63 | } else { // read access |
64 | Os << " accesses out-of-bound array element" ; |
65 | } |
66 | |
67 | return Message; |
68 | } |
69 | |
70 | enum class ConcatFnKind { none = 0, strcat = 1, strlcat = 2 }; |
71 | |
72 | enum class CharKind { Regular = 0, Wide }; |
73 | constexpr CharKind CK_Regular = CharKind::Regular; |
74 | constexpr CharKind CK_Wide = CharKind::Wide; |
75 | |
76 | static QualType getCharPtrType(ASTContext &Ctx, CharKind CK) { |
77 | return Ctx.getPointerType(T: CK == CharKind::Regular ? Ctx.CharTy |
78 | : Ctx.WideCharTy); |
79 | } |
80 | |
81 | class CStringChecker : public Checker< eval::Call, |
82 | check::PreStmt<DeclStmt>, |
83 | check::LiveSymbols, |
84 | check::DeadSymbols, |
85 | check::RegionChanges |
86 | > { |
87 | mutable std::unique_ptr<BugType> BT_Null, BT_Bounds, BT_Overlap, |
88 | BT_NotCString, BT_AdditionOverflow, BT_UninitRead; |
89 | |
90 | mutable const char *CurrentFunctionDescription = nullptr; |
91 | |
92 | public: |
93 | /// The filter is used to filter out the diagnostics which are not enabled by |
94 | /// the user. |
95 | struct CStringChecksFilter { |
96 | bool CheckCStringNullArg = false; |
97 | bool CheckCStringOutOfBounds = false; |
98 | bool CheckCStringBufferOverlap = false; |
99 | bool CheckCStringNotNullTerm = false; |
100 | bool CheckCStringUninitializedRead = false; |
101 | |
102 | CheckerNameRef CheckNameCStringNullArg; |
103 | CheckerNameRef CheckNameCStringOutOfBounds; |
104 | CheckerNameRef CheckNameCStringBufferOverlap; |
105 | CheckerNameRef CheckNameCStringNotNullTerm; |
106 | CheckerNameRef CheckNameCStringUninitializedRead; |
107 | }; |
108 | |
109 | CStringChecksFilter Filter; |
110 | |
111 | static void *getTag() { static int tag; return &tag; } |
112 | |
113 | bool evalCall(const CallEvent &Call, CheckerContext &C) const; |
114 | void checkPreStmt(const DeclStmt *DS, CheckerContext &C) const; |
115 | void checkLiveSymbols(ProgramStateRef state, SymbolReaper &SR) const; |
116 | void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const; |
117 | |
118 | ProgramStateRef |
119 | checkRegionChanges(ProgramStateRef state, |
120 | const InvalidatedSymbols *, |
121 | ArrayRef<const MemRegion *> ExplicitRegions, |
122 | ArrayRef<const MemRegion *> Regions, |
123 | const LocationContext *LCtx, |
124 | const CallEvent *Call) const; |
125 | |
126 | using FnCheck = std::function<void(const CStringChecker *, CheckerContext &, |
127 | const CallEvent &)>; |
128 | |
129 | CallDescriptionMap<FnCheck> Callbacks = { |
130 | {{CDM::CLibraryMaybeHardened, {"memcpy" }, 3}, |
131 | std::bind(f: &CStringChecker::evalMemcpy, args: _1, args: _2, args: _3, args: CK_Regular)}, |
132 | {{CDM::CLibraryMaybeHardened, {"wmemcpy" }, 3}, |
133 | std::bind(f: &CStringChecker::evalMemcpy, args: _1, args: _2, args: _3, args: CK_Wide)}, |
134 | {{CDM::CLibraryMaybeHardened, {"mempcpy" }, 3}, |
135 | std::bind(f: &CStringChecker::evalMempcpy, args: _1, args: _2, args: _3, args: CK_Regular)}, |
136 | {{CDM::CLibraryMaybeHardened, {"wmempcpy" }, 3}, |
137 | std::bind(f: &CStringChecker::evalMempcpy, args: _1, args: _2, args: _3, args: CK_Wide)}, |
138 | {{CDM::CLibrary, {"memcmp" }, 3}, |
139 | std::bind(f: &CStringChecker::evalMemcmp, args: _1, args: _2, args: _3, args: CK_Regular)}, |
140 | {{CDM::CLibrary, {"wmemcmp" }, 3}, |
141 | std::bind(f: &CStringChecker::evalMemcmp, args: _1, args: _2, args: _3, args: CK_Wide)}, |
142 | {{CDM::CLibraryMaybeHardened, {"memmove" }, 3}, |
143 | std::bind(f: &CStringChecker::evalMemmove, args: _1, args: _2, args: _3, args: CK_Regular)}, |
144 | {{CDM::CLibraryMaybeHardened, {"wmemmove" }, 3}, |
145 | std::bind(f: &CStringChecker::evalMemmove, args: _1, args: _2, args: _3, args: CK_Wide)}, |
146 | {{CDM::CLibraryMaybeHardened, {"memset" }, 3}, |
147 | &CStringChecker::evalMemset}, |
148 | {{CDM::CLibrary, {"explicit_memset" }, 3}, &CStringChecker::evalMemset}, |
149 | // FIXME: C23 introduces 'memset_explicit', maybe also model that |
150 | {{CDM::CLibraryMaybeHardened, {"strcpy" }, 2}, |
151 | &CStringChecker::evalStrcpy}, |
152 | {{CDM::CLibraryMaybeHardened, {"strncpy" }, 3}, |
153 | &CStringChecker::evalStrncpy}, |
154 | {{CDM::CLibraryMaybeHardened, {"stpcpy" }, 2}, |
155 | &CStringChecker::evalStpcpy}, |
156 | {{CDM::CLibraryMaybeHardened, {"strlcpy" }, 3}, |
157 | &CStringChecker::evalStrlcpy}, |
158 | {{CDM::CLibraryMaybeHardened, {"strcat" }, 2}, |
159 | &CStringChecker::evalStrcat}, |
160 | {{CDM::CLibraryMaybeHardened, {"strncat" }, 3}, |
161 | &CStringChecker::evalStrncat}, |
162 | {{CDM::CLibraryMaybeHardened, {"strlcat" }, 3}, |
163 | &CStringChecker::evalStrlcat}, |
164 | {{CDM::CLibraryMaybeHardened, {"strlen" }, 1}, |
165 | &CStringChecker::evalstrLength}, |
166 | {{CDM::CLibrary, {"wcslen" }, 1}, &CStringChecker::evalstrLength}, |
167 | {{CDM::CLibraryMaybeHardened, {"strnlen" }, 2}, |
168 | &CStringChecker::evalstrnLength}, |
169 | {{CDM::CLibrary, {"wcsnlen" }, 2}, &CStringChecker::evalstrnLength}, |
170 | {{CDM::CLibrary, {"strcmp" }, 2}, &CStringChecker::evalStrcmp}, |
171 | {{CDM::CLibrary, {"strncmp" }, 3}, &CStringChecker::evalStrncmp}, |
172 | {{CDM::CLibrary, {"strcasecmp" }, 2}, &CStringChecker::evalStrcasecmp}, |
173 | {{CDM::CLibrary, {"strncasecmp" }, 3}, &CStringChecker::evalStrncasecmp}, |
174 | {{CDM::CLibrary, {"strsep" }, 2}, &CStringChecker::evalStrsep}, |
175 | {{CDM::CLibrary, {"bcopy" }, 3}, &CStringChecker::evalBcopy}, |
176 | {{CDM::CLibrary, {"bcmp" }, 3}, |
177 | std::bind(f: &CStringChecker::evalMemcmp, args: _1, args: _2, args: _3, args: CK_Regular)}, |
178 | {{CDM::CLibrary, {"bzero" }, 2}, &CStringChecker::evalBzero}, |
179 | {{CDM::CLibraryMaybeHardened, {"explicit_bzero" }, 2}, |
180 | &CStringChecker::evalBzero}, |
181 | |
182 | // When recognizing calls to the following variadic functions, we accept |
183 | // any number of arguments in the call (std::nullopt = accept any |
184 | // number), but check that in the declaration there are 2 and 3 |
185 | // parameters respectively. (Note that the parameter count does not |
186 | // include the "...". Calls where the number of arguments is too small |
187 | // will be discarded by the callback.) |
188 | {{CDM::CLibraryMaybeHardened, {"sprintf" }, std::nullopt, 2}, |
189 | &CStringChecker::evalSprintf}, |
190 | {{CDM::CLibraryMaybeHardened, {"snprintf" }, std::nullopt, 3}, |
191 | &CStringChecker::evalSnprintf}, |
192 | }; |
193 | |
194 | // These require a bit of special handling. |
195 | CallDescription StdCopy{CDM::SimpleFunc, {"std" , "copy" }, 3}, |
196 | StdCopyBackward{CDM::SimpleFunc, {"std" , "copy_backward" }, 3}; |
197 | |
198 | FnCheck identifyCall(const CallEvent &Call, CheckerContext &C) const; |
199 | void evalMemcpy(CheckerContext &C, const CallEvent &Call, CharKind CK) const; |
200 | void evalMempcpy(CheckerContext &C, const CallEvent &Call, CharKind CK) const; |
201 | void evalMemmove(CheckerContext &C, const CallEvent &Call, CharKind CK) const; |
202 | void evalBcopy(CheckerContext &C, const CallEvent &Call) const; |
203 | void evalCopyCommon(CheckerContext &C, const CallEvent &Call, |
204 | ProgramStateRef state, SizeArgExpr Size, |
205 | DestinationArgExpr Dest, SourceArgExpr Source, |
206 | bool Restricted, bool IsMempcpy, CharKind CK) const; |
207 | |
208 | void evalMemcmp(CheckerContext &C, const CallEvent &Call, CharKind CK) const; |
209 | |
210 | void evalstrLength(CheckerContext &C, const CallEvent &Call) const; |
211 | void evalstrnLength(CheckerContext &C, const CallEvent &Call) const; |
212 | void evalstrLengthCommon(CheckerContext &C, const CallEvent &Call, |
213 | bool IsStrnlen = false) const; |
214 | |
215 | void evalStrcpy(CheckerContext &C, const CallEvent &Call) const; |
216 | void evalStrncpy(CheckerContext &C, const CallEvent &Call) const; |
217 | void evalStpcpy(CheckerContext &C, const CallEvent &Call) const; |
218 | void evalStrlcpy(CheckerContext &C, const CallEvent &Call) const; |
219 | void evalStrcpyCommon(CheckerContext &C, const CallEvent &Call, |
220 | bool ReturnEnd, bool IsBounded, ConcatFnKind appendK, |
221 | bool returnPtr = true) const; |
222 | |
223 | void evalStrcat(CheckerContext &C, const CallEvent &Call) const; |
224 | void evalStrncat(CheckerContext &C, const CallEvent &Call) const; |
225 | void evalStrlcat(CheckerContext &C, const CallEvent &Call) const; |
226 | |
227 | void evalStrcmp(CheckerContext &C, const CallEvent &Call) const; |
228 | void evalStrncmp(CheckerContext &C, const CallEvent &Call) const; |
229 | void evalStrcasecmp(CheckerContext &C, const CallEvent &Call) const; |
230 | void evalStrncasecmp(CheckerContext &C, const CallEvent &Call) const; |
231 | void evalStrcmpCommon(CheckerContext &C, const CallEvent &Call, |
232 | bool IsBounded = false, bool IgnoreCase = false) const; |
233 | |
234 | void evalStrsep(CheckerContext &C, const CallEvent &Call) const; |
235 | |
236 | void evalStdCopy(CheckerContext &C, const CallEvent &Call) const; |
237 | void evalStdCopyBackward(CheckerContext &C, const CallEvent &Call) const; |
238 | void evalStdCopyCommon(CheckerContext &C, const CallEvent &Call) const; |
239 | void evalMemset(CheckerContext &C, const CallEvent &Call) const; |
240 | void evalBzero(CheckerContext &C, const CallEvent &Call) const; |
241 | |
242 | void evalSprintf(CheckerContext &C, const CallEvent &Call) const; |
243 | void evalSnprintf(CheckerContext &C, const CallEvent &Call) const; |
244 | void evalSprintfCommon(CheckerContext &C, const CallEvent &Call, |
245 | bool IsBounded) const; |
246 | |
247 | // Utility methods |
248 | std::pair<ProgramStateRef , ProgramStateRef > |
249 | static assumeZero(CheckerContext &C, |
250 | ProgramStateRef state, SVal V, QualType Ty); |
251 | |
252 | static ProgramStateRef setCStringLength(ProgramStateRef state, |
253 | const MemRegion *MR, |
254 | SVal strLength); |
255 | static SVal getCStringLengthForRegion(CheckerContext &C, |
256 | ProgramStateRef &state, |
257 | const Expr *Ex, |
258 | const MemRegion *MR, |
259 | bool hypothetical); |
260 | SVal getCStringLength(CheckerContext &C, |
261 | ProgramStateRef &state, |
262 | const Expr *Ex, |
263 | SVal Buf, |
264 | bool hypothetical = false) const; |
265 | |
266 | const StringLiteral *getCStringLiteral(CheckerContext &C, |
267 | ProgramStateRef &state, |
268 | const Expr *expr, |
269 | SVal val) const; |
270 | |
271 | /// Invalidate the destination buffer determined by characters copied. |
272 | static ProgramStateRef |
273 | invalidateDestinationBufferBySize(CheckerContext &C, ProgramStateRef S, |
274 | const Expr *BufE, ConstCFGElementRef Elem, |
275 | SVal BufV, SVal SizeV, QualType SizeTy); |
276 | |
277 | /// Operation never overflows, do not invalidate the super region. |
278 | static ProgramStateRef invalidateDestinationBufferNeverOverflows( |
279 | CheckerContext &C, ProgramStateRef S, ConstCFGElementRef Elem, SVal BufV); |
280 | |
281 | /// We do not know whether the operation can overflow (e.g. size is unknown), |
282 | /// invalidate the super region and escape related pointers. |
283 | static ProgramStateRef invalidateDestinationBufferAlwaysEscapeSuperRegion( |
284 | CheckerContext &C, ProgramStateRef S, ConstCFGElementRef Elem, SVal BufV); |
285 | |
286 | /// Invalidate the source buffer for escaping pointers. |
287 | static ProgramStateRef invalidateSourceBuffer(CheckerContext &C, |
288 | ProgramStateRef S, |
289 | ConstCFGElementRef Elem, |
290 | SVal BufV); |
291 | |
292 | /// @param InvalidationTraitOperations Determine how to invlidate the |
293 | /// MemRegion by setting the invalidation traits. Return true to cause pointer |
294 | /// escape, or false otherwise. |
295 | static ProgramStateRef invalidateBufferAux( |
296 | CheckerContext &C, ProgramStateRef State, ConstCFGElementRef Elem, SVal V, |
297 | llvm::function_ref<bool(RegionAndSymbolInvalidationTraits &, |
298 | const MemRegion *)> |
299 | InvalidationTraitOperations); |
300 | |
301 | static bool SummarizeRegion(raw_ostream &os, ASTContext &Ctx, |
302 | const MemRegion *MR); |
303 | |
304 | static bool memsetAux(const Expr *DstBuffer, ConstCFGElementRef Elem, |
305 | SVal CharE, const Expr *Size, CheckerContext &C, |
306 | ProgramStateRef &State); |
307 | |
308 | // Re-usable checks |
309 | ProgramStateRef checkNonNull(CheckerContext &C, ProgramStateRef State, |
310 | AnyArgExpr Arg, SVal l) const; |
311 | // Check whether the origin region behind \p Element (like the actual array |
312 | // region \p Element is from) is initialized. |
313 | ProgramStateRef checkInit(CheckerContext &C, ProgramStateRef state, |
314 | AnyArgExpr Buffer, SVal Element, SVal Size) const; |
315 | ProgramStateRef CheckLocation(CheckerContext &C, ProgramStateRef state, |
316 | AnyArgExpr Buffer, SVal Element, |
317 | AccessKind Access, |
318 | CharKind CK = CharKind::Regular) const; |
319 | ProgramStateRef CheckBufferAccess(CheckerContext &C, ProgramStateRef State, |
320 | AnyArgExpr Buffer, SizeArgExpr Size, |
321 | AccessKind Access, |
322 | CharKind CK = CharKind::Regular) const; |
323 | ProgramStateRef CheckOverlap(CheckerContext &C, ProgramStateRef state, |
324 | SizeArgExpr Size, AnyArgExpr First, |
325 | AnyArgExpr Second, |
326 | CharKind CK = CharKind::Regular) const; |
327 | void emitOverlapBug(CheckerContext &C, |
328 | ProgramStateRef state, |
329 | const Stmt *First, |
330 | const Stmt *Second) const; |
331 | |
332 | void emitNullArgBug(CheckerContext &C, ProgramStateRef State, const Stmt *S, |
333 | StringRef WarningMsg) const; |
334 | void emitOutOfBoundsBug(CheckerContext &C, ProgramStateRef State, |
335 | const Stmt *S, StringRef WarningMsg) const; |
336 | void emitNotCStringBug(CheckerContext &C, ProgramStateRef State, |
337 | const Stmt *S, StringRef WarningMsg) const; |
338 | void emitAdditionOverflowBug(CheckerContext &C, ProgramStateRef State) const; |
339 | void emitUninitializedReadBug(CheckerContext &C, ProgramStateRef State, |
340 | const Expr *E, const MemRegion *R, |
341 | StringRef Msg) const; |
342 | ProgramStateRef checkAdditionOverflow(CheckerContext &C, |
343 | ProgramStateRef state, |
344 | NonLoc left, |
345 | NonLoc right) const; |
346 | |
347 | // Return true if the destination buffer of the copy function may be in bound. |
348 | // Expects SVal of Size to be positive and unsigned. |
349 | // Expects SVal of FirstBuf to be a FieldRegion. |
350 | static bool isFirstBufInBound(CheckerContext &C, ProgramStateRef State, |
351 | SVal BufVal, QualType BufTy, SVal LengthVal, |
352 | QualType LengthTy); |
353 | }; |
354 | |
355 | } //end anonymous namespace |
356 | |
357 | REGISTER_MAP_WITH_PROGRAMSTATE(CStringLength, const MemRegion *, SVal) |
358 | |
359 | //===----------------------------------------------------------------------===// |
360 | // Individual checks and utility methods. |
361 | //===----------------------------------------------------------------------===// |
362 | |
363 | std::pair<ProgramStateRef, ProgramStateRef> |
364 | CStringChecker::assumeZero(CheckerContext &C, ProgramStateRef State, SVal V, |
365 | QualType Ty) { |
366 | std::optional<DefinedSVal> val = V.getAs<DefinedSVal>(); |
367 | if (!val) |
368 | return std::pair<ProgramStateRef, ProgramStateRef>(State, State); |
369 | |
370 | SValBuilder &svalBuilder = C.getSValBuilder(); |
371 | DefinedOrUnknownSVal zero = svalBuilder.makeZeroVal(type: Ty); |
372 | return State->assume(Cond: svalBuilder.evalEQ(state: State, lhs: *val, rhs: zero)); |
373 | } |
374 | |
375 | ProgramStateRef CStringChecker::checkNonNull(CheckerContext &C, |
376 | ProgramStateRef State, |
377 | AnyArgExpr Arg, SVal l) const { |
378 | // If a previous check has failed, propagate the failure. |
379 | if (!State) |
380 | return nullptr; |
381 | |
382 | ProgramStateRef stateNull, stateNonNull; |
383 | std::tie(args&: stateNull, args&: stateNonNull) = |
384 | assumeZero(C, State, V: l, Ty: Arg.Expression->getType()); |
385 | |
386 | if (stateNull && !stateNonNull) { |
387 | if (Filter.CheckCStringNullArg) { |
388 | SmallString<80> buf; |
389 | llvm::raw_svector_ostream OS(buf); |
390 | assert(CurrentFunctionDescription); |
391 | OS << "Null pointer passed as " << (Arg.ArgumentIndex + 1) |
392 | << llvm::getOrdinalSuffix(Val: Arg.ArgumentIndex + 1) << " argument to " |
393 | << CurrentFunctionDescription; |
394 | |
395 | emitNullArgBug(C, State: stateNull, S: Arg.Expression, WarningMsg: OS.str()); |
396 | } |
397 | return nullptr; |
398 | } |
399 | |
400 | // From here on, assume that the value is non-null. |
401 | assert(stateNonNull); |
402 | return stateNonNull; |
403 | } |
404 | |
405 | static std::optional<NonLoc> getIndex(ProgramStateRef State, |
406 | const ElementRegion *ER, CharKind CK) { |
407 | SValBuilder &SVB = State->getStateManager().getSValBuilder(); |
408 | ASTContext &Ctx = SVB.getContext(); |
409 | |
410 | if (CK == CharKind::Regular) { |
411 | if (ER->getValueType() != Ctx.CharTy) |
412 | return {}; |
413 | return ER->getIndex(); |
414 | } |
415 | |
416 | if (ER->getValueType() != Ctx.WideCharTy) |
417 | return {}; |
418 | |
419 | QualType SizeTy = Ctx.getSizeType(); |
420 | NonLoc WideSize = |
421 | SVB.makeIntVal(integer: Ctx.getTypeSizeInChars(T: Ctx.WideCharTy).getQuantity(), |
422 | type: SizeTy) |
423 | .castAs<NonLoc>(); |
424 | SVal Offset = |
425 | SVB.evalBinOpNN(state: State, op: BO_Mul, lhs: ER->getIndex(), rhs: WideSize, resultTy: SizeTy); |
426 | if (Offset.isUnknown()) |
427 | return {}; |
428 | return Offset.castAs<NonLoc>(); |
429 | } |
430 | |
431 | // Basically 1 -> 1st, 12 -> 12th, etc. |
432 | static void printIdxWithOrdinalSuffix(llvm::raw_ostream &Os, unsigned Idx) { |
433 | Os << Idx << llvm::getOrdinalSuffix(Val: Idx); |
434 | } |
435 | |
436 | ProgramStateRef CStringChecker::checkInit(CheckerContext &C, |
437 | ProgramStateRef State, |
438 | AnyArgExpr Buffer, SVal Element, |
439 | SVal Size) const { |
440 | |
441 | // If a previous check has failed, propagate the failure. |
442 | if (!State) |
443 | return nullptr; |
444 | |
445 | const MemRegion *R = Element.getAsRegion(); |
446 | const auto *ER = dyn_cast_or_null<ElementRegion>(Val: R); |
447 | if (!ER) |
448 | return State; |
449 | |
450 | const auto *SuperR = ER->getSuperRegion()->getAs<TypedValueRegion>(); |
451 | if (!SuperR) |
452 | return State; |
453 | |
454 | // FIXME: We ought to able to check objects as well. Maybe |
455 | // UninitializedObjectChecker could help? |
456 | if (!SuperR->getValueType()->isArrayType()) |
457 | return State; |
458 | |
459 | SValBuilder &SVB = C.getSValBuilder(); |
460 | ASTContext &Ctx = SVB.getContext(); |
461 | |
462 | const QualType ElemTy = Ctx.getBaseElementType(QT: SuperR->getValueType()); |
463 | const NonLoc Zero = SVB.makeZeroArrayIndex(); |
464 | |
465 | std::optional<Loc> FirstElementVal = |
466 | State->getLValue(ElementType: ElemTy, Idx: Zero, Base: loc::MemRegionVal(SuperR)).getAs<Loc>(); |
467 | if (!FirstElementVal) |
468 | return State; |
469 | |
470 | // Ensure that we wouldn't read uninitialized value. |
471 | if (Filter.CheckCStringUninitializedRead && |
472 | State->getSVal(LV: *FirstElementVal).isUndef()) { |
473 | llvm::SmallString<258> Buf; |
474 | llvm::raw_svector_ostream OS(Buf); |
475 | OS << "The first element of the " ; |
476 | printIdxWithOrdinalSuffix(Os&: OS, Idx: Buffer.ArgumentIndex + 1); |
477 | OS << " argument is undefined" ; |
478 | emitUninitializedReadBug(C, State, E: Buffer.Expression, |
479 | R: FirstElementVal->getAsRegion(), Msg: OS.str()); |
480 | return nullptr; |
481 | } |
482 | |
483 | // We won't check whether the entire region is fully initialized -- lets just |
484 | // check that the first and the last element is. So, onto checking the last |
485 | // element: |
486 | const QualType IdxTy = SVB.getArrayIndexType(); |
487 | |
488 | NonLoc ElemSize = |
489 | SVB.makeIntVal(integer: Ctx.getTypeSizeInChars(T: ElemTy).getQuantity(), type: IdxTy) |
490 | .castAs<NonLoc>(); |
491 | |
492 | // FIXME: Check that the size arg to the cstring function is divisible by |
493 | // size of the actual element type? |
494 | |
495 | // The type of the argument to the cstring function is either char or wchar, |
496 | // but thats not the type of the original array (or memory region). |
497 | // Suppose the following: |
498 | // int t[5]; |
499 | // memcpy(dst, t, sizeof(t) / sizeof(t[0])); |
500 | // When checking whether t is fully initialized, we see it as char array of |
501 | // size sizeof(int)*5. If we check the last element as a character, we read |
502 | // the last byte of an integer, which will be undefined. But just because |
503 | // that value is undefined, it doesn't mean that the element is uninitialized! |
504 | // For this reason, we need to retrieve the actual last element with the |
505 | // correct type. |
506 | |
507 | // Divide the size argument to the cstring function by the actual element |
508 | // type. This value will be size of the array, or the index to the |
509 | // past-the-end element. |
510 | std::optional<NonLoc> Offset = |
511 | SVB.evalBinOpNN(state: State, op: clang::BO_Div, lhs: Size.castAs<NonLoc>(), rhs: ElemSize, |
512 | resultTy: IdxTy) |
513 | .getAs<NonLoc>(); |
514 | |
515 | // Retrieve the index of the last element. |
516 | const NonLoc One = SVB.makeIntVal(integer: 1, type: IdxTy).castAs<NonLoc>(); |
517 | SVal LastIdx = SVB.evalBinOpNN(state: State, op: BO_Sub, lhs: *Offset, rhs: One, resultTy: IdxTy); |
518 | |
519 | if (!Offset) |
520 | return State; |
521 | |
522 | SVal LastElementVal = |
523 | State->getLValue(ElementType: ElemTy, Idx: LastIdx, Base: loc::MemRegionVal(SuperR)); |
524 | if (!isa<Loc>(Val: LastElementVal)) |
525 | return State; |
526 | |
527 | if (Filter.CheckCStringUninitializedRead && |
528 | State->getSVal(LV: LastElementVal.castAs<Loc>()).isUndef()) { |
529 | const llvm::APSInt *IdxInt = LastIdx.getAsInteger(); |
530 | // If we can't get emit a sensible last element index, just bail out -- |
531 | // prefer to emit nothing in favour of emitting garbage quality reports. |
532 | if (!IdxInt) { |
533 | C.addSink(); |
534 | return nullptr; |
535 | } |
536 | llvm::SmallString<258> Buf; |
537 | llvm::raw_svector_ostream OS(Buf); |
538 | OS << "The last accessed element (at index " ; |
539 | OS << IdxInt->getExtValue(); |
540 | OS << ") in the " ; |
541 | printIdxWithOrdinalSuffix(Os&: OS, Idx: Buffer.ArgumentIndex + 1); |
542 | OS << " argument is undefined" ; |
543 | emitUninitializedReadBug(C, State, E: Buffer.Expression, |
544 | R: LastElementVal.getAsRegion(), Msg: OS.str()); |
545 | return nullptr; |
546 | } |
547 | return State; |
548 | } |
549 | // FIXME: The root of this logic was copied from the old checker |
550 | // alpha.security.ArrayBound (which is removed within this commit). |
551 | // It should be refactored to use the different, more sophisticated bounds |
552 | // checking logic used by the new checker ``security.ArrayBound``. |
553 | ProgramStateRef CStringChecker::CheckLocation(CheckerContext &C, |
554 | ProgramStateRef state, |
555 | AnyArgExpr Buffer, SVal Element, |
556 | AccessKind Access, |
557 | CharKind CK) const { |
558 | |
559 | // If a previous check has failed, propagate the failure. |
560 | if (!state) |
561 | return nullptr; |
562 | |
563 | // Check for out of bound array element access. |
564 | const MemRegion *R = Element.getAsRegion(); |
565 | if (!R) |
566 | return state; |
567 | |
568 | const auto *ER = dyn_cast<ElementRegion>(Val: R); |
569 | if (!ER) |
570 | return state; |
571 | |
572 | // Get the index of the accessed element. |
573 | std::optional<NonLoc> Idx = getIndex(State: state, ER, CK); |
574 | if (!Idx) |
575 | return state; |
576 | |
577 | // Get the size of the array. |
578 | const auto *superReg = cast<SubRegion>(Val: ER->getSuperRegion()); |
579 | DefinedOrUnknownSVal Size = |
580 | getDynamicExtent(State: state, MR: superReg, SVB&: C.getSValBuilder()); |
581 | |
582 | auto [StInBound, StOutBound] = state->assumeInBoundDual(idx: *Idx, upperBound: Size); |
583 | if (StOutBound && !StInBound) { |
584 | // These checks are either enabled by the CString out-of-bounds checker |
585 | // explicitly or implicitly by the Malloc checker. |
586 | // In the latter case we only do modeling but do not emit warning. |
587 | if (!Filter.CheckCStringOutOfBounds) |
588 | return nullptr; |
589 | |
590 | // Emit a bug report. |
591 | ErrorMessage Message = |
592 | createOutOfBoundErrorMsg(FunctionDescription: CurrentFunctionDescription, Access); |
593 | emitOutOfBoundsBug(C, State: StOutBound, S: Buffer.Expression, WarningMsg: Message); |
594 | return nullptr; |
595 | } |
596 | |
597 | // Array bound check succeeded. From this point forward the array bound |
598 | // should always succeed. |
599 | return StInBound; |
600 | } |
601 | |
602 | ProgramStateRef |
603 | CStringChecker::CheckBufferAccess(CheckerContext &C, ProgramStateRef State, |
604 | AnyArgExpr Buffer, SizeArgExpr Size, |
605 | AccessKind Access, CharKind CK) const { |
606 | // If a previous check has failed, propagate the failure. |
607 | if (!State) |
608 | return nullptr; |
609 | |
610 | SValBuilder &svalBuilder = C.getSValBuilder(); |
611 | ASTContext &Ctx = svalBuilder.getContext(); |
612 | |
613 | QualType SizeTy = Size.Expression->getType(); |
614 | QualType PtrTy = getCharPtrType(Ctx, CK); |
615 | |
616 | // Check that the first buffer is non-null. |
617 | SVal BufVal = C.getSVal(S: Buffer.Expression); |
618 | State = checkNonNull(C, State, Arg: Buffer, l: BufVal); |
619 | if (!State) |
620 | return nullptr; |
621 | |
622 | // If out-of-bounds checking is turned off, skip the rest. |
623 | if (!Filter.CheckCStringOutOfBounds) |
624 | return State; |
625 | |
626 | SVal BufStart = |
627 | svalBuilder.evalCast(V: BufVal, CastTy: PtrTy, OriginalTy: Buffer.Expression->getType()); |
628 | |
629 | // Check if the first byte of the buffer is accessible. |
630 | State = CheckLocation(C, state: State, Buffer, Element: BufStart, Access, CK); |
631 | |
632 | if (!State) |
633 | return nullptr; |
634 | |
635 | // Get the access length and make sure it is known. |
636 | // FIXME: This assumes the caller has already checked that the access length |
637 | // is positive. And that it's unsigned. |
638 | SVal LengthVal = C.getSVal(S: Size.Expression); |
639 | std::optional<NonLoc> Length = LengthVal.getAs<NonLoc>(); |
640 | if (!Length) |
641 | return State; |
642 | |
643 | // Compute the offset of the last element to be accessed: size-1. |
644 | NonLoc One = svalBuilder.makeIntVal(integer: 1, type: SizeTy).castAs<NonLoc>(); |
645 | SVal Offset = svalBuilder.evalBinOpNN(state: State, op: BO_Sub, lhs: *Length, rhs: One, resultTy: SizeTy); |
646 | if (Offset.isUnknown()) |
647 | return nullptr; |
648 | NonLoc LastOffset = Offset.castAs<NonLoc>(); |
649 | |
650 | // Check that the first buffer is sufficiently long. |
651 | if (std::optional<Loc> BufLoc = BufStart.getAs<Loc>()) { |
652 | |
653 | SVal BufEnd = |
654 | svalBuilder.evalBinOpLN(state: State, op: BO_Add, lhs: *BufLoc, rhs: LastOffset, resultTy: PtrTy); |
655 | State = CheckLocation(C, state: State, Buffer, Element: BufEnd, Access, CK); |
656 | if (Access == AccessKind::read) |
657 | State = checkInit(C, State, Buffer, Element: BufEnd, Size: *Length); |
658 | |
659 | // If the buffer isn't large enough, abort. |
660 | if (!State) |
661 | return nullptr; |
662 | } |
663 | |
664 | // Large enough or not, return this state! |
665 | return State; |
666 | } |
667 | |
668 | ProgramStateRef CStringChecker::CheckOverlap(CheckerContext &C, |
669 | ProgramStateRef state, |
670 | SizeArgExpr Size, AnyArgExpr First, |
671 | AnyArgExpr Second, |
672 | CharKind CK) const { |
673 | if (!Filter.CheckCStringBufferOverlap) |
674 | return state; |
675 | |
676 | // Do a simple check for overlap: if the two arguments are from the same |
677 | // buffer, see if the end of the first is greater than the start of the second |
678 | // or vice versa. |
679 | |
680 | // If a previous check has failed, propagate the failure. |
681 | if (!state) |
682 | return nullptr; |
683 | |
684 | ProgramStateRef stateTrue, stateFalse; |
685 | |
686 | // Assume different address spaces cannot overlap. |
687 | if (First.Expression->getType()->getPointeeType().getAddressSpace() != |
688 | Second.Expression->getType()->getPointeeType().getAddressSpace()) |
689 | return state; |
690 | |
691 | // Get the buffer values and make sure they're known locations. |
692 | const LocationContext *LCtx = C.getLocationContext(); |
693 | SVal firstVal = state->getSVal(Ex: First.Expression, LCtx); |
694 | SVal secondVal = state->getSVal(Ex: Second.Expression, LCtx); |
695 | |
696 | std::optional<Loc> firstLoc = firstVal.getAs<Loc>(); |
697 | if (!firstLoc) |
698 | return state; |
699 | |
700 | std::optional<Loc> secondLoc = secondVal.getAs<Loc>(); |
701 | if (!secondLoc) |
702 | return state; |
703 | |
704 | // Are the two values the same? |
705 | SValBuilder &svalBuilder = C.getSValBuilder(); |
706 | std::tie(args&: stateTrue, args&: stateFalse) = |
707 | state->assume(Cond: svalBuilder.evalEQ(state, lhs: *firstLoc, rhs: *secondLoc)); |
708 | |
709 | if (stateTrue && !stateFalse) { |
710 | // If the values are known to be equal, that's automatically an overlap. |
711 | emitOverlapBug(C, state: stateTrue, First: First.Expression, Second: Second.Expression); |
712 | return nullptr; |
713 | } |
714 | |
715 | // assume the two expressions are not equal. |
716 | assert(stateFalse); |
717 | state = stateFalse; |
718 | |
719 | // Which value comes first? |
720 | QualType cmpTy = svalBuilder.getConditionType(); |
721 | SVal reverse = |
722 | svalBuilder.evalBinOpLL(state, op: BO_GT, lhs: *firstLoc, rhs: *secondLoc, resultTy: cmpTy); |
723 | std::optional<DefinedOrUnknownSVal> reverseTest = |
724 | reverse.getAs<DefinedOrUnknownSVal>(); |
725 | if (!reverseTest) |
726 | return state; |
727 | |
728 | std::tie(args&: stateTrue, args&: stateFalse) = state->assume(Cond: *reverseTest); |
729 | if (stateTrue) { |
730 | if (stateFalse) { |
731 | // If we don't know which one comes first, we can't perform this test. |
732 | return state; |
733 | } else { |
734 | // Switch the values so that firstVal is before secondVal. |
735 | std::swap(lhs&: firstLoc, rhs&: secondLoc); |
736 | |
737 | // Switch the Exprs as well, so that they still correspond. |
738 | std::swap(a&: First, b&: Second); |
739 | } |
740 | } |
741 | |
742 | // Get the length, and make sure it too is known. |
743 | SVal LengthVal = state->getSVal(Ex: Size.Expression, LCtx); |
744 | std::optional<NonLoc> Length = LengthVal.getAs<NonLoc>(); |
745 | if (!Length) |
746 | return state; |
747 | |
748 | // Convert the first buffer's start address to char*. |
749 | // Bail out if the cast fails. |
750 | ASTContext &Ctx = svalBuilder.getContext(); |
751 | QualType CharPtrTy = getCharPtrType(Ctx, CK); |
752 | SVal FirstStart = |
753 | svalBuilder.evalCast(V: *firstLoc, CastTy: CharPtrTy, OriginalTy: First.Expression->getType()); |
754 | std::optional<Loc> FirstStartLoc = FirstStart.getAs<Loc>(); |
755 | if (!FirstStartLoc) |
756 | return state; |
757 | |
758 | // Compute the end of the first buffer. Bail out if THAT fails. |
759 | SVal FirstEnd = svalBuilder.evalBinOpLN(state, op: BO_Add, lhs: *FirstStartLoc, |
760 | rhs: *Length, resultTy: CharPtrTy); |
761 | std::optional<Loc> FirstEndLoc = FirstEnd.getAs<Loc>(); |
762 | if (!FirstEndLoc) |
763 | return state; |
764 | |
765 | // Is the end of the first buffer past the start of the second buffer? |
766 | SVal Overlap = |
767 | svalBuilder.evalBinOpLL(state, op: BO_GT, lhs: *FirstEndLoc, rhs: *secondLoc, resultTy: cmpTy); |
768 | std::optional<DefinedOrUnknownSVal> OverlapTest = |
769 | Overlap.getAs<DefinedOrUnknownSVal>(); |
770 | if (!OverlapTest) |
771 | return state; |
772 | |
773 | std::tie(args&: stateTrue, args&: stateFalse) = state->assume(Cond: *OverlapTest); |
774 | |
775 | if (stateTrue && !stateFalse) { |
776 | // Overlap! |
777 | emitOverlapBug(C, state: stateTrue, First: First.Expression, Second: Second.Expression); |
778 | return nullptr; |
779 | } |
780 | |
781 | // assume the two expressions don't overlap. |
782 | assert(stateFalse); |
783 | return stateFalse; |
784 | } |
785 | |
786 | void CStringChecker::emitOverlapBug(CheckerContext &C, ProgramStateRef state, |
787 | const Stmt *First, const Stmt *Second) const { |
788 | ExplodedNode *N = C.generateErrorNode(State: state); |
789 | if (!N) |
790 | return; |
791 | |
792 | if (!BT_Overlap) |
793 | BT_Overlap.reset(p: new BugType(Filter.CheckNameCStringBufferOverlap, |
794 | categories::UnixAPI, "Improper arguments" )); |
795 | |
796 | // Generate a report for this bug. |
797 | auto report = std::make_unique<PathSensitiveBugReport>( |
798 | args&: *BT_Overlap, args: "Arguments must not be overlapping buffers" , args&: N); |
799 | report->addRange(R: First->getSourceRange()); |
800 | report->addRange(R: Second->getSourceRange()); |
801 | |
802 | C.emitReport(R: std::move(report)); |
803 | } |
804 | |
805 | void CStringChecker::emitNullArgBug(CheckerContext &C, ProgramStateRef State, |
806 | const Stmt *S, StringRef WarningMsg) const { |
807 | if (ExplodedNode *N = C.generateErrorNode(State)) { |
808 | if (!BT_Null) { |
809 | // FIXME: This call uses the string constant 'categories::UnixAPI' as the |
810 | // description of the bug; it should be replaced by a real description. |
811 | BT_Null.reset( |
812 | p: new BugType(Filter.CheckNameCStringNullArg, categories::UnixAPI)); |
813 | } |
814 | |
815 | auto Report = |
816 | std::make_unique<PathSensitiveBugReport>(args&: *BT_Null, args&: WarningMsg, args&: N); |
817 | Report->addRange(R: S->getSourceRange()); |
818 | if (const auto *Ex = dyn_cast<Expr>(Val: S)) |
819 | bugreporter::trackExpressionValue(N, E: Ex, R&: *Report); |
820 | C.emitReport(R: std::move(Report)); |
821 | } |
822 | } |
823 | |
824 | void CStringChecker::emitUninitializedReadBug(CheckerContext &C, |
825 | ProgramStateRef State, |
826 | const Expr *E, const MemRegion *R, |
827 | StringRef Msg) const { |
828 | if (ExplodedNode *N = C.generateErrorNode(State)) { |
829 | if (!BT_UninitRead) |
830 | BT_UninitRead.reset(p: new BugType(Filter.CheckNameCStringUninitializedRead, |
831 | "Accessing unitialized/garbage values" )); |
832 | |
833 | auto Report = |
834 | std::make_unique<PathSensitiveBugReport>(args&: *BT_UninitRead, args&: Msg, args&: N); |
835 | Report->addNote(Msg: "Other elements might also be undefined" , |
836 | Pos: Report->getLocation()); |
837 | Report->addRange(R: E->getSourceRange()); |
838 | bugreporter::trackExpressionValue(N, E, R&: *Report); |
839 | Report->addVisitor<NoStoreFuncVisitor>(ConstructorArgs: R->castAs<SubRegion>()); |
840 | C.emitReport(R: std::move(Report)); |
841 | } |
842 | } |
843 | |
844 | void CStringChecker::emitOutOfBoundsBug(CheckerContext &C, |
845 | ProgramStateRef State, const Stmt *S, |
846 | StringRef WarningMsg) const { |
847 | if (ExplodedNode *N = C.generateErrorNode(State)) { |
848 | if (!BT_Bounds) |
849 | BT_Bounds.reset(p: new BugType(Filter.CheckCStringOutOfBounds |
850 | ? Filter.CheckNameCStringOutOfBounds |
851 | : Filter.CheckNameCStringNullArg, |
852 | "Out-of-bound array access" )); |
853 | |
854 | // FIXME: It would be nice to eventually make this diagnostic more clear, |
855 | // e.g., by referencing the original declaration or by saying *why* this |
856 | // reference is outside the range. |
857 | auto Report = |
858 | std::make_unique<PathSensitiveBugReport>(args&: *BT_Bounds, args&: WarningMsg, args&: N); |
859 | Report->addRange(R: S->getSourceRange()); |
860 | C.emitReport(R: std::move(Report)); |
861 | } |
862 | } |
863 | |
864 | void CStringChecker::emitNotCStringBug(CheckerContext &C, ProgramStateRef State, |
865 | const Stmt *S, |
866 | StringRef WarningMsg) const { |
867 | if (ExplodedNode *N = C.generateNonFatalErrorNode(State)) { |
868 | if (!BT_NotCString) { |
869 | // FIXME: This call uses the string constant 'categories::UnixAPI' as the |
870 | // description of the bug; it should be replaced by a real description. |
871 | BT_NotCString.reset( |
872 | p: new BugType(Filter.CheckNameCStringNotNullTerm, categories::UnixAPI)); |
873 | } |
874 | |
875 | auto Report = |
876 | std::make_unique<PathSensitiveBugReport>(args&: *BT_NotCString, args&: WarningMsg, args&: N); |
877 | |
878 | Report->addRange(R: S->getSourceRange()); |
879 | C.emitReport(R: std::move(Report)); |
880 | } |
881 | } |
882 | |
883 | void CStringChecker::emitAdditionOverflowBug(CheckerContext &C, |
884 | ProgramStateRef State) const { |
885 | if (ExplodedNode *N = C.generateErrorNode(State)) { |
886 | if (!BT_AdditionOverflow) { |
887 | // FIXME: This call uses the word "API" as the description of the bug; |
888 | // it should be replaced by a better error message (if this unlikely |
889 | // situation continues to exist as a separate bug type). |
890 | BT_AdditionOverflow.reset( |
891 | p: new BugType(Filter.CheckNameCStringOutOfBounds, "API" )); |
892 | } |
893 | |
894 | // This isn't a great error message, but this should never occur in real |
895 | // code anyway -- you'd have to create a buffer longer than a size_t can |
896 | // represent, which is sort of a contradiction. |
897 | const char *WarningMsg = |
898 | "This expression will create a string whose length is too big to " |
899 | "be represented as a size_t" ; |
900 | |
901 | auto Report = std::make_unique<PathSensitiveBugReport>(args&: *BT_AdditionOverflow, |
902 | args&: WarningMsg, args&: N); |
903 | C.emitReport(R: std::move(Report)); |
904 | } |
905 | } |
906 | |
907 | ProgramStateRef CStringChecker::checkAdditionOverflow(CheckerContext &C, |
908 | ProgramStateRef state, |
909 | NonLoc left, |
910 | NonLoc right) const { |
911 | // If out-of-bounds checking is turned off, skip the rest. |
912 | if (!Filter.CheckCStringOutOfBounds) |
913 | return state; |
914 | |
915 | // If a previous check has failed, propagate the failure. |
916 | if (!state) |
917 | return nullptr; |
918 | |
919 | SValBuilder &svalBuilder = C.getSValBuilder(); |
920 | BasicValueFactory &BVF = svalBuilder.getBasicValueFactory(); |
921 | |
922 | QualType sizeTy = svalBuilder.getContext().getSizeType(); |
923 | const llvm::APSInt &maxValInt = BVF.getMaxValue(T: sizeTy); |
924 | NonLoc maxVal = svalBuilder.makeIntVal(integer: maxValInt); |
925 | |
926 | SVal maxMinusRight; |
927 | if (isa<nonloc::ConcreteInt>(Val: right)) { |
928 | maxMinusRight = svalBuilder.evalBinOpNN(state, op: BO_Sub, lhs: maxVal, rhs: right, |
929 | resultTy: sizeTy); |
930 | } else { |
931 | // Try switching the operands. (The order of these two assignments is |
932 | // important!) |
933 | maxMinusRight = svalBuilder.evalBinOpNN(state, op: BO_Sub, lhs: maxVal, rhs: left, |
934 | resultTy: sizeTy); |
935 | left = right; |
936 | } |
937 | |
938 | if (std::optional<NonLoc> maxMinusRightNL = maxMinusRight.getAs<NonLoc>()) { |
939 | QualType cmpTy = svalBuilder.getConditionType(); |
940 | // If left > max - right, we have an overflow. |
941 | SVal willOverflow = svalBuilder.evalBinOpNN(state, op: BO_GT, lhs: left, |
942 | rhs: *maxMinusRightNL, resultTy: cmpTy); |
943 | |
944 | ProgramStateRef stateOverflow, stateOkay; |
945 | std::tie(args&: stateOverflow, args&: stateOkay) = |
946 | state->assume(Cond: willOverflow.castAs<DefinedOrUnknownSVal>()); |
947 | |
948 | if (stateOverflow && !stateOkay) { |
949 | // We have an overflow. Emit a bug report. |
950 | emitAdditionOverflowBug(C, State: stateOverflow); |
951 | return nullptr; |
952 | } |
953 | |
954 | // From now on, assume an overflow didn't occur. |
955 | assert(stateOkay); |
956 | state = stateOkay; |
957 | } |
958 | |
959 | return state; |
960 | } |
961 | |
962 | ProgramStateRef CStringChecker::setCStringLength(ProgramStateRef state, |
963 | const MemRegion *MR, |
964 | SVal strLength) { |
965 | assert(!strLength.isUndef() && "Attempt to set an undefined string length" ); |
966 | |
967 | MR = MR->StripCasts(); |
968 | |
969 | switch (MR->getKind()) { |
970 | case MemRegion::StringRegionKind: |
971 | // FIXME: This can happen if we strcpy() into a string region. This is |
972 | // undefined [C99 6.4.5p6], but we should still warn about it. |
973 | return state; |
974 | |
975 | case MemRegion::SymbolicRegionKind: |
976 | case MemRegion::AllocaRegionKind: |
977 | case MemRegion::NonParamVarRegionKind: |
978 | case MemRegion::ParamVarRegionKind: |
979 | case MemRegion::FieldRegionKind: |
980 | case MemRegion::ObjCIvarRegionKind: |
981 | // These are the types we can currently track string lengths for. |
982 | break; |
983 | |
984 | case MemRegion::ElementRegionKind: |
985 | // FIXME: Handle element regions by upper-bounding the parent region's |
986 | // string length. |
987 | return state; |
988 | |
989 | default: |
990 | // Other regions (mostly non-data) can't have a reliable C string length. |
991 | // For now, just ignore the change. |
992 | // FIXME: These are rare but not impossible. We should output some kind of |
993 | // warning for things like strcpy((char[]){'a', 0}, "b"); |
994 | return state; |
995 | } |
996 | |
997 | if (strLength.isUnknown()) |
998 | return state->remove<CStringLength>(K: MR); |
999 | |
1000 | return state->set<CStringLength>(K: MR, E: strLength); |
1001 | } |
1002 | |
1003 | SVal CStringChecker::getCStringLengthForRegion(CheckerContext &C, |
1004 | ProgramStateRef &state, |
1005 | const Expr *Ex, |
1006 | const MemRegion *MR, |
1007 | bool hypothetical) { |
1008 | if (!hypothetical) { |
1009 | // If there's a recorded length, go ahead and return it. |
1010 | const SVal *Recorded = state->get<CStringLength>(key: MR); |
1011 | if (Recorded) |
1012 | return *Recorded; |
1013 | } |
1014 | |
1015 | // Otherwise, get a new symbol and update the state. |
1016 | SValBuilder &svalBuilder = C.getSValBuilder(); |
1017 | QualType sizeTy = svalBuilder.getContext().getSizeType(); |
1018 | SVal strLength = svalBuilder.getMetadataSymbolVal(symbolTag: CStringChecker::getTag(), |
1019 | region: MR, expr: Ex, type: sizeTy, |
1020 | LCtx: C.getLocationContext(), |
1021 | count: C.blockCount()); |
1022 | |
1023 | if (!hypothetical) { |
1024 | if (std::optional<NonLoc> strLn = strLength.getAs<NonLoc>()) { |
1025 | // In case of unbounded calls strlen etc bound the range to SIZE_MAX/4 |
1026 | BasicValueFactory &BVF = svalBuilder.getBasicValueFactory(); |
1027 | const llvm::APSInt &maxValInt = BVF.getMaxValue(T: sizeTy); |
1028 | llvm::APSInt fourInt = APSIntType(maxValInt).getValue(RawValue: 4); |
1029 | std::optional<APSIntPtr> maxLengthInt = |
1030 | BVF.evalAPSInt(Op: BO_Div, V1: maxValInt, V2: fourInt); |
1031 | NonLoc maxLength = svalBuilder.makeIntVal(integer: *maxLengthInt); |
1032 | SVal evalLength = svalBuilder.evalBinOpNN(state, op: BO_LE, lhs: *strLn, rhs: maxLength, |
1033 | resultTy: svalBuilder.getConditionType()); |
1034 | state = state->assume(Cond: evalLength.castAs<DefinedOrUnknownSVal>(), Assumption: true); |
1035 | } |
1036 | state = state->set<CStringLength>(K: MR, E: strLength); |
1037 | } |
1038 | |
1039 | return strLength; |
1040 | } |
1041 | |
1042 | SVal CStringChecker::getCStringLength(CheckerContext &C, ProgramStateRef &state, |
1043 | const Expr *Ex, SVal Buf, |
1044 | bool hypothetical) const { |
1045 | const MemRegion *MR = Buf.getAsRegion(); |
1046 | if (!MR) { |
1047 | // If we can't get a region, see if it's something we /know/ isn't a |
1048 | // C string. In the context of locations, the only time we can issue such |
1049 | // a warning is for labels. |
1050 | if (std::optional<loc::GotoLabel> Label = Buf.getAs<loc::GotoLabel>()) { |
1051 | if (Filter.CheckCStringNotNullTerm) { |
1052 | SmallString<120> buf; |
1053 | llvm::raw_svector_ostream os(buf); |
1054 | assert(CurrentFunctionDescription); |
1055 | os << "Argument to " << CurrentFunctionDescription |
1056 | << " is the address of the label '" << Label->getLabel()->getName() |
1057 | << "', which is not a null-terminated string" ; |
1058 | |
1059 | emitNotCStringBug(C, State: state, S: Ex, WarningMsg: os.str()); |
1060 | } |
1061 | return UndefinedVal(); |
1062 | } |
1063 | |
1064 | // If it's not a region and not a label, give up. |
1065 | return UnknownVal(); |
1066 | } |
1067 | |
1068 | // If we have a region, strip casts from it and see if we can figure out |
1069 | // its length. For anything we can't figure out, just return UnknownVal. |
1070 | MR = MR->StripCasts(); |
1071 | |
1072 | switch (MR->getKind()) { |
1073 | case MemRegion::StringRegionKind: { |
1074 | // Modifying the contents of string regions is undefined [C99 6.4.5p6], |
1075 | // so we can assume that the byte length is the correct C string length. |
1076 | SValBuilder &svalBuilder = C.getSValBuilder(); |
1077 | QualType sizeTy = svalBuilder.getContext().getSizeType(); |
1078 | const StringLiteral *strLit = cast<StringRegion>(Val: MR)->getStringLiteral(); |
1079 | return svalBuilder.makeIntVal(integer: strLit->getLength(), type: sizeTy); |
1080 | } |
1081 | case MemRegion::NonParamVarRegionKind: { |
1082 | // If we have a global constant with a string literal initializer, |
1083 | // compute the initializer's length. |
1084 | const VarDecl *Decl = cast<NonParamVarRegion>(Val: MR)->getDecl(); |
1085 | if (Decl->getType().isConstQualified() && Decl->hasGlobalStorage()) { |
1086 | if (const Expr *Init = Decl->getInit()) { |
1087 | if (auto *StrLit = dyn_cast<StringLiteral>(Val: Init)) { |
1088 | SValBuilder &SvalBuilder = C.getSValBuilder(); |
1089 | QualType SizeTy = SvalBuilder.getContext().getSizeType(); |
1090 | return SvalBuilder.makeIntVal(integer: StrLit->getLength(), type: SizeTy); |
1091 | } |
1092 | } |
1093 | } |
1094 | [[fallthrough]]; |
1095 | } |
1096 | case MemRegion::SymbolicRegionKind: |
1097 | case MemRegion::AllocaRegionKind: |
1098 | case MemRegion::ParamVarRegionKind: |
1099 | case MemRegion::FieldRegionKind: |
1100 | case MemRegion::ObjCIvarRegionKind: |
1101 | return getCStringLengthForRegion(C, state, Ex, MR, hypothetical); |
1102 | case MemRegion::CompoundLiteralRegionKind: |
1103 | // FIXME: Can we track this? Is it necessary? |
1104 | return UnknownVal(); |
1105 | case MemRegion::ElementRegionKind: |
1106 | // FIXME: How can we handle this? It's not good enough to subtract the |
1107 | // offset from the base string length; consider "123\x00567" and &a[5]. |
1108 | return UnknownVal(); |
1109 | default: |
1110 | // Other regions (mostly non-data) can't have a reliable C string length. |
1111 | // In this case, an error is emitted and UndefinedVal is returned. |
1112 | // The caller should always be prepared to handle this case. |
1113 | if (Filter.CheckCStringNotNullTerm) { |
1114 | SmallString<120> buf; |
1115 | llvm::raw_svector_ostream os(buf); |
1116 | |
1117 | assert(CurrentFunctionDescription); |
1118 | os << "Argument to " << CurrentFunctionDescription << " is " ; |
1119 | |
1120 | if (SummarizeRegion(os, Ctx&: C.getASTContext(), MR)) |
1121 | os << ", which is not a null-terminated string" ; |
1122 | else |
1123 | os << "not a null-terminated string" ; |
1124 | |
1125 | emitNotCStringBug(C, State: state, S: Ex, WarningMsg: os.str()); |
1126 | } |
1127 | return UndefinedVal(); |
1128 | } |
1129 | } |
1130 | |
1131 | const StringLiteral *CStringChecker::getCStringLiteral(CheckerContext &C, |
1132 | ProgramStateRef &state, const Expr *expr, SVal val) const { |
1133 | |
1134 | // Get the memory region pointed to by the val. |
1135 | const MemRegion *bufRegion = val.getAsRegion(); |
1136 | if (!bufRegion) |
1137 | return nullptr; |
1138 | |
1139 | // Strip casts off the memory region. |
1140 | bufRegion = bufRegion->StripCasts(); |
1141 | |
1142 | // Cast the memory region to a string region. |
1143 | const StringRegion *strRegion= dyn_cast<StringRegion>(Val: bufRegion); |
1144 | if (!strRegion) |
1145 | return nullptr; |
1146 | |
1147 | // Return the actual string in the string region. |
1148 | return strRegion->getStringLiteral(); |
1149 | } |
1150 | |
1151 | bool CStringChecker::isFirstBufInBound(CheckerContext &C, ProgramStateRef State, |
1152 | SVal BufVal, QualType BufTy, |
1153 | SVal LengthVal, QualType LengthTy) { |
1154 | // If we do not know that the buffer is long enough we return 'true'. |
1155 | // Otherwise the parent region of this field region would also get |
1156 | // invalidated, which would lead to warnings based on an unknown state. |
1157 | |
1158 | if (LengthVal.isUnknown()) |
1159 | return false; |
1160 | |
1161 | // Originally copied from CheckBufferAccess and CheckLocation. |
1162 | SValBuilder &SB = C.getSValBuilder(); |
1163 | ASTContext &Ctx = C.getASTContext(); |
1164 | |
1165 | QualType PtrTy = Ctx.getPointerType(T: Ctx.CharTy); |
1166 | |
1167 | std::optional<NonLoc> Length = LengthVal.getAs<NonLoc>(); |
1168 | if (!Length) |
1169 | return true; // cf top comment. |
1170 | |
1171 | // Compute the offset of the last element to be accessed: size-1. |
1172 | NonLoc One = SB.makeIntVal(integer: 1, type: LengthTy).castAs<NonLoc>(); |
1173 | SVal Offset = SB.evalBinOpNN(state: State, op: BO_Sub, lhs: *Length, rhs: One, resultTy: LengthTy); |
1174 | if (Offset.isUnknown()) |
1175 | return true; // cf top comment |
1176 | NonLoc LastOffset = Offset.castAs<NonLoc>(); |
1177 | |
1178 | // Check that the first buffer is sufficiently long. |
1179 | SVal BufStart = SB.evalCast(V: BufVal, CastTy: PtrTy, OriginalTy: BufTy); |
1180 | std::optional<Loc> BufLoc = BufStart.getAs<Loc>(); |
1181 | if (!BufLoc) |
1182 | return true; // cf top comment. |
1183 | |
1184 | SVal BufEnd = SB.evalBinOpLN(state: State, op: BO_Add, lhs: *BufLoc, rhs: LastOffset, resultTy: PtrTy); |
1185 | |
1186 | // Check for out of bound array element access. |
1187 | const MemRegion *R = BufEnd.getAsRegion(); |
1188 | if (!R) |
1189 | return true; // cf top comment. |
1190 | |
1191 | const ElementRegion *ER = dyn_cast<ElementRegion>(Val: R); |
1192 | if (!ER) |
1193 | return true; // cf top comment. |
1194 | |
1195 | // FIXME: Does this crash when a non-standard definition |
1196 | // of a library function is encountered? |
1197 | assert(ER->getValueType() == C.getASTContext().CharTy && |
1198 | "isFirstBufInBound should only be called with char* ElementRegions" ); |
1199 | |
1200 | // Get the size of the array. |
1201 | const SubRegion *superReg = cast<SubRegion>(Val: ER->getSuperRegion()); |
1202 | DefinedOrUnknownSVal SizeDV = getDynamicExtent(State, MR: superReg, SVB&: SB); |
1203 | |
1204 | // Get the index of the accessed element. |
1205 | DefinedOrUnknownSVal Idx = ER->getIndex().castAs<DefinedOrUnknownSVal>(); |
1206 | |
1207 | ProgramStateRef StInBound = State->assumeInBound(idx: Idx, upperBound: SizeDV, assumption: true); |
1208 | |
1209 | return static_cast<bool>(StInBound); |
1210 | } |
1211 | |
1212 | ProgramStateRef CStringChecker::invalidateDestinationBufferBySize( |
1213 | CheckerContext &C, ProgramStateRef S, const Expr *BufE, |
1214 | ConstCFGElementRef Elem, SVal BufV, SVal SizeV, QualType SizeTy) { |
1215 | auto InvalidationTraitOperations = |
1216 | [&C, S, BufTy = BufE->getType(), BufV, SizeV, |
1217 | SizeTy](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) { |
1218 | // If destination buffer is a field region and access is in bound, do |
1219 | // not invalidate its super region. |
1220 | if (MemRegion::FieldRegionKind == R->getKind() && |
1221 | isFirstBufInBound(C, State: S, BufVal: BufV, BufTy, LengthVal: SizeV, LengthTy: SizeTy)) { |
1222 | ITraits.setTrait( |
1223 | MR: R, |
1224 | IK: RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); |
1225 | } |
1226 | return false; |
1227 | }; |
1228 | |
1229 | return invalidateBufferAux(C, State: S, Elem, V: BufV, InvalidationTraitOperations); |
1230 | } |
1231 | |
1232 | ProgramStateRef |
1233 | CStringChecker::invalidateDestinationBufferAlwaysEscapeSuperRegion( |
1234 | CheckerContext &C, ProgramStateRef S, ConstCFGElementRef Elem, SVal BufV) { |
1235 | auto InvalidationTraitOperations = [](RegionAndSymbolInvalidationTraits &, |
1236 | const MemRegion *R) { |
1237 | return isa<FieldRegion>(Val: R); |
1238 | }; |
1239 | |
1240 | return invalidateBufferAux(C, State: S, Elem, V: BufV, InvalidationTraitOperations); |
1241 | } |
1242 | |
1243 | ProgramStateRef CStringChecker::invalidateDestinationBufferNeverOverflows( |
1244 | CheckerContext &C, ProgramStateRef S, ConstCFGElementRef Elem, SVal BufV) { |
1245 | auto InvalidationTraitOperations = |
1246 | [](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) { |
1247 | if (MemRegion::FieldRegionKind == R->getKind()) |
1248 | ITraits.setTrait( |
1249 | MR: R, |
1250 | IK: RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); |
1251 | return false; |
1252 | }; |
1253 | |
1254 | return invalidateBufferAux(C, State: S, Elem, V: BufV, InvalidationTraitOperations); |
1255 | } |
1256 | |
1257 | ProgramStateRef CStringChecker::invalidateSourceBuffer(CheckerContext &C, |
1258 | ProgramStateRef S, |
1259 | ConstCFGElementRef Elem, |
1260 | SVal BufV) { |
1261 | auto InvalidationTraitOperations = |
1262 | [](RegionAndSymbolInvalidationTraits &ITraits, const MemRegion *R) { |
1263 | ITraits.setTrait( |
1264 | MR: R->getBaseRegion(), |
1265 | IK: RegionAndSymbolInvalidationTraits::TK_PreserveContents); |
1266 | ITraits.setTrait(MR: R, |
1267 | IK: RegionAndSymbolInvalidationTraits::TK_SuppressEscape); |
1268 | return true; |
1269 | }; |
1270 | |
1271 | return invalidateBufferAux(C, State: S, Elem, V: BufV, InvalidationTraitOperations); |
1272 | } |
1273 | |
1274 | ProgramStateRef CStringChecker::invalidateBufferAux( |
1275 | CheckerContext &C, ProgramStateRef State, ConstCFGElementRef Elem, SVal V, |
1276 | llvm::function_ref<bool(RegionAndSymbolInvalidationTraits &, |
1277 | const MemRegion *)> |
1278 | InvalidationTraitOperations) { |
1279 | std::optional<Loc> L = V.getAs<Loc>(); |
1280 | if (!L) |
1281 | return State; |
1282 | |
1283 | // FIXME: This is a simplified version of what's in CFRefCount.cpp -- it makes |
1284 | // some assumptions about the value that CFRefCount can't. Even so, it should |
1285 | // probably be refactored. |
1286 | if (std::optional<loc::MemRegionVal> MR = L->getAs<loc::MemRegionVal>()) { |
1287 | const MemRegion *R = MR->getRegion()->StripCasts(); |
1288 | |
1289 | // Are we dealing with an ElementRegion? If so, we should be invalidating |
1290 | // the super-region. |
1291 | if (const ElementRegion *ER = dyn_cast<ElementRegion>(Val: R)) { |
1292 | R = ER->getSuperRegion(); |
1293 | // FIXME: What about layers of ElementRegions? |
1294 | } |
1295 | |
1296 | // Invalidate this region. |
1297 | const LocationContext *LCtx = C.getPredecessor()->getLocationContext(); |
1298 | RegionAndSymbolInvalidationTraits ITraits; |
1299 | bool CausesPointerEscape = InvalidationTraitOperations(ITraits, R); |
1300 | |
1301 | return State->invalidateRegions(Regions: R, Elem, BlockCount: C.blockCount(), LCtx, |
1302 | CausesPointerEscape, IS: nullptr, Call: nullptr, |
1303 | ITraits: &ITraits); |
1304 | } |
1305 | |
1306 | // If we have a non-region value by chance, just remove the binding. |
1307 | // FIXME: is this necessary or correct? This handles the non-Region |
1308 | // cases. Is it ever valid to store to these? |
1309 | return State->killBinding(LV: *L); |
1310 | } |
1311 | |
1312 | bool CStringChecker::SummarizeRegion(raw_ostream &os, ASTContext &Ctx, |
1313 | const MemRegion *MR) { |
1314 | switch (MR->getKind()) { |
1315 | case MemRegion::FunctionCodeRegionKind: { |
1316 | if (const auto *FD = cast<FunctionCodeRegion>(Val: MR)->getDecl()) |
1317 | os << "the address of the function '" << *FD << '\''; |
1318 | else |
1319 | os << "the address of a function" ; |
1320 | return true; |
1321 | } |
1322 | case MemRegion::BlockCodeRegionKind: |
1323 | os << "block text" ; |
1324 | return true; |
1325 | case MemRegion::BlockDataRegionKind: |
1326 | os << "a block" ; |
1327 | return true; |
1328 | case MemRegion::CXXThisRegionKind: |
1329 | case MemRegion::CXXTempObjectRegionKind: |
1330 | os << "a C++ temp object of type " |
1331 | << cast<TypedValueRegion>(Val: MR)->getValueType(); |
1332 | return true; |
1333 | case MemRegion::NonParamVarRegionKind: |
1334 | os << "a variable of type" << cast<TypedValueRegion>(Val: MR)->getValueType(); |
1335 | return true; |
1336 | case MemRegion::ParamVarRegionKind: |
1337 | os << "a parameter of type" << cast<TypedValueRegion>(Val: MR)->getValueType(); |
1338 | return true; |
1339 | case MemRegion::FieldRegionKind: |
1340 | os << "a field of type " << cast<TypedValueRegion>(Val: MR)->getValueType(); |
1341 | return true; |
1342 | case MemRegion::ObjCIvarRegionKind: |
1343 | os << "an instance variable of type " |
1344 | << cast<TypedValueRegion>(Val: MR)->getValueType(); |
1345 | return true; |
1346 | default: |
1347 | return false; |
1348 | } |
1349 | } |
1350 | |
1351 | bool CStringChecker::memsetAux(const Expr *DstBuffer, ConstCFGElementRef Elem, |
1352 | SVal CharVal, const Expr *Size, |
1353 | CheckerContext &C, ProgramStateRef &State) { |
1354 | SVal MemVal = C.getSVal(S: DstBuffer); |
1355 | SVal SizeVal = C.getSVal(S: Size); |
1356 | const MemRegion *MR = MemVal.getAsRegion(); |
1357 | if (!MR) |
1358 | return false; |
1359 | |
1360 | // We're about to model memset by producing a "default binding" in the Store. |
1361 | // Our current implementation - RegionStore - doesn't support default bindings |
1362 | // that don't cover the whole base region. So we should first get the offset |
1363 | // and the base region to figure out whether the offset of buffer is 0. |
1364 | RegionOffset Offset = MR->getAsOffset(); |
1365 | const MemRegion *BR = Offset.getRegion(); |
1366 | |
1367 | std::optional<NonLoc> SizeNL = SizeVal.getAs<NonLoc>(); |
1368 | if (!SizeNL) |
1369 | return false; |
1370 | |
1371 | SValBuilder &svalBuilder = C.getSValBuilder(); |
1372 | ASTContext &Ctx = C.getASTContext(); |
1373 | |
1374 | // void *memset(void *dest, int ch, size_t count); |
1375 | // For now we can only handle the case of offset is 0 and concrete char value. |
1376 | if (Offset.isValid() && !Offset.hasSymbolicOffset() && |
1377 | Offset.getOffset() == 0) { |
1378 | // Get the base region's size. |
1379 | DefinedOrUnknownSVal SizeDV = getDynamicExtent(State, MR: BR, SVB&: svalBuilder); |
1380 | |
1381 | ProgramStateRef StateWholeReg, StateNotWholeReg; |
1382 | std::tie(args&: StateWholeReg, args&: StateNotWholeReg) = |
1383 | State->assume(Cond: svalBuilder.evalEQ(state: State, lhs: SizeDV, rhs: *SizeNL)); |
1384 | |
1385 | // With the semantic of 'memset()', we should convert the CharVal to |
1386 | // unsigned char. |
1387 | CharVal = svalBuilder.evalCast(V: CharVal, CastTy: Ctx.UnsignedCharTy, OriginalTy: Ctx.IntTy); |
1388 | |
1389 | ProgramStateRef StateNullChar, StateNonNullChar; |
1390 | std::tie(args&: StateNullChar, args&: StateNonNullChar) = |
1391 | assumeZero(C, State, V: CharVal, Ty: Ctx.UnsignedCharTy); |
1392 | |
1393 | if (StateWholeReg && !StateNotWholeReg && StateNullChar && |
1394 | !StateNonNullChar) { |
1395 | // If the 'memset()' acts on the whole region of destination buffer and |
1396 | // the value of the second argument of 'memset()' is zero, bind the second |
1397 | // argument's value to the destination buffer with 'default binding'. |
1398 | // FIXME: Since there is no perfect way to bind the non-zero character, we |
1399 | // can only deal with zero value here. In the future, we need to deal with |
1400 | // the binding of non-zero value in the case of whole region. |
1401 | State = State->bindDefaultZero(loc: svalBuilder.makeLoc(region: BR), |
1402 | LCtx: C.getLocationContext()); |
1403 | } else { |
1404 | // If the destination buffer's extent is not equal to the value of |
1405 | // third argument, just invalidate buffer. |
1406 | State = invalidateDestinationBufferBySize( |
1407 | C, S: State, BufE: DstBuffer, Elem, BufV: MemVal, SizeV: SizeVal, SizeTy: Size->getType()); |
1408 | } |
1409 | |
1410 | if (StateNullChar && !StateNonNullChar) { |
1411 | // If the value of the second argument of 'memset()' is zero, set the |
1412 | // string length of destination buffer to 0 directly. |
1413 | State = setCStringLength(state: State, MR, |
1414 | strLength: svalBuilder.makeZeroVal(type: Ctx.getSizeType())); |
1415 | } else if (!StateNullChar && StateNonNullChar) { |
1416 | SVal NewStrLen = svalBuilder.getMetadataSymbolVal( |
1417 | symbolTag: CStringChecker::getTag(), region: MR, expr: DstBuffer, type: Ctx.getSizeType(), |
1418 | LCtx: C.getLocationContext(), count: C.blockCount()); |
1419 | |
1420 | // If the value of second argument is not zero, then the string length |
1421 | // is at least the size argument. |
1422 | SVal NewStrLenGESize = svalBuilder.evalBinOp( |
1423 | state: State, op: BO_GE, lhs: NewStrLen, rhs: SizeVal, type: svalBuilder.getConditionType()); |
1424 | |
1425 | State = setCStringLength( |
1426 | state: State->assume(Cond: NewStrLenGESize.castAs<DefinedOrUnknownSVal>(), Assumption: true), |
1427 | MR, strLength: NewStrLen); |
1428 | } |
1429 | } else { |
1430 | // If the offset is not zero and char value is not concrete, we can do |
1431 | // nothing but invalidate the buffer. |
1432 | State = invalidateDestinationBufferBySize(C, S: State, BufE: DstBuffer, Elem, BufV: MemVal, |
1433 | SizeV: SizeVal, SizeTy: Size->getType()); |
1434 | } |
1435 | return true; |
1436 | } |
1437 | |
1438 | //===----------------------------------------------------------------------===// |
1439 | // evaluation of individual function calls. |
1440 | //===----------------------------------------------------------------------===// |
1441 | |
1442 | void CStringChecker::evalCopyCommon(CheckerContext &C, const CallEvent &Call, |
1443 | ProgramStateRef state, SizeArgExpr Size, |
1444 | DestinationArgExpr Dest, |
1445 | SourceArgExpr Source, bool Restricted, |
1446 | bool IsMempcpy, CharKind CK) const { |
1447 | CurrentFunctionDescription = "memory copy function" ; |
1448 | |
1449 | // See if the size argument is zero. |
1450 | const LocationContext *LCtx = C.getLocationContext(); |
1451 | SVal sizeVal = state->getSVal(Ex: Size.Expression, LCtx); |
1452 | QualType sizeTy = Size.Expression->getType(); |
1453 | |
1454 | ProgramStateRef stateZeroSize, stateNonZeroSize; |
1455 | std::tie(args&: stateZeroSize, args&: stateNonZeroSize) = |
1456 | assumeZero(C, State: state, V: sizeVal, Ty: sizeTy); |
1457 | |
1458 | // Get the value of the Dest. |
1459 | SVal destVal = state->getSVal(Ex: Dest.Expression, LCtx); |
1460 | |
1461 | // If the size is zero, there won't be any actual memory access, so |
1462 | // just bind the return value to the destination buffer and return. |
1463 | if (stateZeroSize && !stateNonZeroSize) { |
1464 | stateZeroSize = |
1465 | stateZeroSize->BindExpr(S: Call.getOriginExpr(), LCtx, V: destVal); |
1466 | C.addTransition(State: stateZeroSize); |
1467 | return; |
1468 | } |
1469 | |
1470 | // If the size can be nonzero, we have to check the other arguments. |
1471 | if (stateNonZeroSize) { |
1472 | // TODO: If Size is tainted and we cannot prove that it is smaller or equal |
1473 | // to the size of the destination buffer, then emit a warning |
1474 | // that an attacker may provoke a buffer overflow error. |
1475 | state = stateNonZeroSize; |
1476 | |
1477 | // Ensure the destination is not null. If it is NULL there will be a |
1478 | // NULL pointer dereference. |
1479 | state = checkNonNull(C, State: state, Arg: Dest, l: destVal); |
1480 | if (!state) |
1481 | return; |
1482 | |
1483 | // Get the value of the Src. |
1484 | SVal srcVal = state->getSVal(Ex: Source.Expression, LCtx); |
1485 | |
1486 | // Ensure the source is not null. If it is NULL there will be a |
1487 | // NULL pointer dereference. |
1488 | state = checkNonNull(C, State: state, Arg: Source, l: srcVal); |
1489 | if (!state) |
1490 | return; |
1491 | |
1492 | // Ensure the accesses are valid and that the buffers do not overlap. |
1493 | state = CheckBufferAccess(C, State: state, Buffer: Dest, Size, Access: AccessKind::write, CK); |
1494 | state = CheckBufferAccess(C, State: state, Buffer: Source, Size, Access: AccessKind::read, CK); |
1495 | |
1496 | if (Restricted) |
1497 | state = CheckOverlap(C, state, Size, First: Dest, Second: Source, CK); |
1498 | |
1499 | if (!state) |
1500 | return; |
1501 | |
1502 | // If this is mempcpy, get the byte after the last byte copied and |
1503 | // bind the expr. |
1504 | if (IsMempcpy) { |
1505 | // Get the byte after the last byte copied. |
1506 | SValBuilder &SvalBuilder = C.getSValBuilder(); |
1507 | ASTContext &Ctx = SvalBuilder.getContext(); |
1508 | QualType CharPtrTy = getCharPtrType(Ctx, CK); |
1509 | SVal DestRegCharVal = |
1510 | SvalBuilder.evalCast(V: destVal, CastTy: CharPtrTy, OriginalTy: Dest.Expression->getType()); |
1511 | SVal lastElement = C.getSValBuilder().evalBinOp( |
1512 | state, op: BO_Add, lhs: DestRegCharVal, rhs: sizeVal, type: Dest.Expression->getType()); |
1513 | // If we don't know how much we copied, we can at least |
1514 | // conjure a return value for later. |
1515 | if (lastElement.isUnknown()) |
1516 | lastElement = C.getSValBuilder().conjureSymbolVal(call: Call, visitCount: C.blockCount()); |
1517 | |
1518 | // The byte after the last byte copied is the return value. |
1519 | state = state->BindExpr(S: Call.getOriginExpr(), LCtx, V: lastElement); |
1520 | } else { |
1521 | // All other copies return the destination buffer. |
1522 | // (Well, bcopy() has a void return type, but this won't hurt.) |
1523 | state = state->BindExpr(S: Call.getOriginExpr(), LCtx, V: destVal); |
1524 | } |
1525 | |
1526 | // Invalidate the destination (regular invalidation without pointer-escaping |
1527 | // the address of the top-level region). |
1528 | // FIXME: Even if we can't perfectly model the copy, we should see if we |
1529 | // can use LazyCompoundVals to copy the source values into the destination. |
1530 | // This would probably remove any existing bindings past the end of the |
1531 | // copied region, but that's still an improvement over blank invalidation. |
1532 | state = invalidateDestinationBufferBySize( |
1533 | C, S: state, BufE: Dest.Expression, Elem: Call.getCFGElementRef(), |
1534 | BufV: C.getSVal(S: Dest.Expression), SizeV: sizeVal, SizeTy: Size.Expression->getType()); |
1535 | |
1536 | // Invalidate the source (const-invalidation without const-pointer-escaping |
1537 | // the address of the top-level region). |
1538 | state = invalidateSourceBuffer(C, S: state, Elem: Call.getCFGElementRef(), |
1539 | BufV: C.getSVal(S: Source.Expression)); |
1540 | |
1541 | C.addTransition(State: state); |
1542 | } |
1543 | } |
1544 | |
1545 | void CStringChecker::evalMemcpy(CheckerContext &C, const CallEvent &Call, |
1546 | CharKind CK) const { |
1547 | // void *memcpy(void *restrict dst, const void *restrict src, size_t n); |
1548 | // The return value is the address of the destination buffer. |
1549 | DestinationArgExpr Dest = {{.Expression: Call.getArgExpr(Index: 0), .ArgumentIndex: 0}}; |
1550 | SourceArgExpr Src = {{.Expression: Call.getArgExpr(Index: 1), .ArgumentIndex: 1}}; |
1551 | SizeArgExpr Size = {{.Expression: Call.getArgExpr(Index: 2), .ArgumentIndex: 2}}; |
1552 | |
1553 | ProgramStateRef State = C.getState(); |
1554 | |
1555 | constexpr bool IsRestricted = true; |
1556 | constexpr bool IsMempcpy = false; |
1557 | evalCopyCommon(C, Call, state: State, Size, Dest, Source: Src, Restricted: IsRestricted, IsMempcpy, CK); |
1558 | } |
1559 | |
1560 | void CStringChecker::evalMempcpy(CheckerContext &C, const CallEvent &Call, |
1561 | CharKind CK) const { |
1562 | // void *mempcpy(void *restrict dst, const void *restrict src, size_t n); |
1563 | // The return value is a pointer to the byte following the last written byte. |
1564 | DestinationArgExpr Dest = {{.Expression: Call.getArgExpr(Index: 0), .ArgumentIndex: 0}}; |
1565 | SourceArgExpr Src = {{.Expression: Call.getArgExpr(Index: 1), .ArgumentIndex: 1}}; |
1566 | SizeArgExpr Size = {{.Expression: Call.getArgExpr(Index: 2), .ArgumentIndex: 2}}; |
1567 | |
1568 | constexpr bool IsRestricted = true; |
1569 | constexpr bool IsMempcpy = true; |
1570 | evalCopyCommon(C, Call, state: C.getState(), Size, Dest, Source: Src, Restricted: IsRestricted, |
1571 | IsMempcpy, CK); |
1572 | } |
1573 | |
1574 | void CStringChecker::evalMemmove(CheckerContext &C, const CallEvent &Call, |
1575 | CharKind CK) const { |
1576 | // void *memmove(void *dst, const void *src, size_t n); |
1577 | // The return value is the address of the destination buffer. |
1578 | DestinationArgExpr Dest = {{.Expression: Call.getArgExpr(Index: 0), .ArgumentIndex: 0}}; |
1579 | SourceArgExpr Src = {{.Expression: Call.getArgExpr(Index: 1), .ArgumentIndex: 1}}; |
1580 | SizeArgExpr Size = {{.Expression: Call.getArgExpr(Index: 2), .ArgumentIndex: 2}}; |
1581 | |
1582 | constexpr bool IsRestricted = false; |
1583 | constexpr bool IsMempcpy = false; |
1584 | evalCopyCommon(C, Call, state: C.getState(), Size, Dest, Source: Src, Restricted: IsRestricted, |
1585 | IsMempcpy, CK); |
1586 | } |
1587 | |
1588 | void CStringChecker::evalBcopy(CheckerContext &C, const CallEvent &Call) const { |
1589 | // void bcopy(const void *src, void *dst, size_t n); |
1590 | SourceArgExpr Src{{.Expression: Call.getArgExpr(Index: 0), .ArgumentIndex: 0}}; |
1591 | DestinationArgExpr Dest = {{.Expression: Call.getArgExpr(Index: 1), .ArgumentIndex: 1}}; |
1592 | SizeArgExpr Size = {{.Expression: Call.getArgExpr(Index: 2), .ArgumentIndex: 2}}; |
1593 | |
1594 | constexpr bool IsRestricted = false; |
1595 | constexpr bool IsMempcpy = false; |
1596 | evalCopyCommon(C, Call, state: C.getState(), Size, Dest, Source: Src, Restricted: IsRestricted, |
1597 | IsMempcpy, CK: CharKind::Regular); |
1598 | } |
1599 | |
1600 | void CStringChecker::evalMemcmp(CheckerContext &C, const CallEvent &Call, |
1601 | CharKind CK) const { |
1602 | // int memcmp(const void *s1, const void *s2, size_t n); |
1603 | CurrentFunctionDescription = "memory comparison function" ; |
1604 | |
1605 | AnyArgExpr Left = {.Expression: Call.getArgExpr(Index: 0), .ArgumentIndex: 0}; |
1606 | AnyArgExpr Right = {.Expression: Call.getArgExpr(Index: 1), .ArgumentIndex: 1}; |
1607 | SizeArgExpr Size = {{.Expression: Call.getArgExpr(Index: 2), .ArgumentIndex: 2}}; |
1608 | |
1609 | ProgramStateRef State = C.getState(); |
1610 | SValBuilder &Builder = C.getSValBuilder(); |
1611 | const LocationContext *LCtx = C.getLocationContext(); |
1612 | |
1613 | // See if the size argument is zero. |
1614 | SVal sizeVal = State->getSVal(Ex: Size.Expression, LCtx); |
1615 | QualType sizeTy = Size.Expression->getType(); |
1616 | |
1617 | ProgramStateRef stateZeroSize, stateNonZeroSize; |
1618 | std::tie(args&: stateZeroSize, args&: stateNonZeroSize) = |
1619 | assumeZero(C, State, V: sizeVal, Ty: sizeTy); |
1620 | |
1621 | // If the size can be zero, the result will be 0 in that case, and we don't |
1622 | // have to check either of the buffers. |
1623 | if (stateZeroSize) { |
1624 | State = stateZeroSize; |
1625 | State = State->BindExpr(S: Call.getOriginExpr(), LCtx, |
1626 | V: Builder.makeZeroVal(type: Call.getResultType())); |
1627 | C.addTransition(State); |
1628 | } |
1629 | |
1630 | // If the size can be nonzero, we have to check the other arguments. |
1631 | if (stateNonZeroSize) { |
1632 | State = stateNonZeroSize; |
1633 | // If we know the two buffers are the same, we know the result is 0. |
1634 | // First, get the two buffers' addresses. Another checker will have already |
1635 | // made sure they're not undefined. |
1636 | DefinedOrUnknownSVal LV = |
1637 | State->getSVal(Ex: Left.Expression, LCtx).castAs<DefinedOrUnknownSVal>(); |
1638 | DefinedOrUnknownSVal RV = |
1639 | State->getSVal(Ex: Right.Expression, LCtx).castAs<DefinedOrUnknownSVal>(); |
1640 | |
1641 | // See if they are the same. |
1642 | ProgramStateRef SameBuffer, NotSameBuffer; |
1643 | std::tie(args&: SameBuffer, args&: NotSameBuffer) = |
1644 | State->assume(Cond: Builder.evalEQ(state: State, lhs: LV, rhs: RV)); |
1645 | |
1646 | // If the two arguments are the same buffer, we know the result is 0, |
1647 | // and we only need to check one size. |
1648 | if (SameBuffer && !NotSameBuffer) { |
1649 | State = SameBuffer; |
1650 | State = CheckBufferAccess(C, State, Buffer: Left, Size, Access: AccessKind::read); |
1651 | if (State) { |
1652 | State = SameBuffer->BindExpr(S: Call.getOriginExpr(), LCtx, |
1653 | V: Builder.makeZeroVal(type: Call.getResultType())); |
1654 | C.addTransition(State); |
1655 | } |
1656 | return; |
1657 | } |
1658 | |
1659 | // If the two arguments might be different buffers, we have to check |
1660 | // the size of both of them. |
1661 | assert(NotSameBuffer); |
1662 | State = CheckBufferAccess(C, State, Buffer: Right, Size, Access: AccessKind::read, CK); |
1663 | State = CheckBufferAccess(C, State, Buffer: Left, Size, Access: AccessKind::read, CK); |
1664 | if (State) { |
1665 | // The return value is the comparison result, which we don't know. |
1666 | SVal CmpV = Builder.conjureSymbolVal(call: Call, visitCount: C.blockCount()); |
1667 | State = State->BindExpr(S: Call.getOriginExpr(), LCtx, V: CmpV); |
1668 | C.addTransition(State); |
1669 | } |
1670 | } |
1671 | } |
1672 | |
1673 | void CStringChecker::evalstrLength(CheckerContext &C, |
1674 | const CallEvent &Call) const { |
1675 | // size_t strlen(const char *s); |
1676 | evalstrLengthCommon(C, Call, /* IsStrnlen = */ false); |
1677 | } |
1678 | |
1679 | void CStringChecker::evalstrnLength(CheckerContext &C, |
1680 | const CallEvent &Call) const { |
1681 | // size_t strnlen(const char *s, size_t maxlen); |
1682 | evalstrLengthCommon(C, Call, /* IsStrnlen = */ true); |
1683 | } |
1684 | |
1685 | void CStringChecker::evalstrLengthCommon(CheckerContext &C, |
1686 | const CallEvent &Call, |
1687 | bool IsStrnlen) const { |
1688 | CurrentFunctionDescription = "string length function" ; |
1689 | ProgramStateRef state = C.getState(); |
1690 | const LocationContext *LCtx = C.getLocationContext(); |
1691 | |
1692 | if (IsStrnlen) { |
1693 | const Expr *maxlenExpr = Call.getArgExpr(Index: 1); |
1694 | SVal maxlenVal = state->getSVal(Ex: maxlenExpr, LCtx); |
1695 | |
1696 | ProgramStateRef stateZeroSize, stateNonZeroSize; |
1697 | std::tie(args&: stateZeroSize, args&: stateNonZeroSize) = |
1698 | assumeZero(C, State: state, V: maxlenVal, Ty: maxlenExpr->getType()); |
1699 | |
1700 | // If the size can be zero, the result will be 0 in that case, and we don't |
1701 | // have to check the string itself. |
1702 | if (stateZeroSize) { |
1703 | SVal zero = C.getSValBuilder().makeZeroVal(type: Call.getResultType()); |
1704 | stateZeroSize = stateZeroSize->BindExpr(S: Call.getOriginExpr(), LCtx, V: zero); |
1705 | C.addTransition(State: stateZeroSize); |
1706 | } |
1707 | |
1708 | // If the size is GUARANTEED to be zero, we're done! |
1709 | if (!stateNonZeroSize) |
1710 | return; |
1711 | |
1712 | // Otherwise, record the assumption that the size is nonzero. |
1713 | state = stateNonZeroSize; |
1714 | } |
1715 | |
1716 | // Check that the string argument is non-null. |
1717 | AnyArgExpr Arg = {.Expression: Call.getArgExpr(Index: 0), .ArgumentIndex: 0}; |
1718 | SVal ArgVal = state->getSVal(Ex: Arg.Expression, LCtx); |
1719 | state = checkNonNull(C, State: state, Arg, l: ArgVal); |
1720 | |
1721 | if (!state) |
1722 | return; |
1723 | |
1724 | SVal strLength = getCStringLength(C, state, Ex: Arg.Expression, Buf: ArgVal); |
1725 | |
1726 | // If the argument isn't a valid C string, there's no valid state to |
1727 | // transition to. |
1728 | if (strLength.isUndef()) |
1729 | return; |
1730 | |
1731 | DefinedOrUnknownSVal result = UnknownVal(); |
1732 | |
1733 | // If the check is for strnlen() then bind the return value to no more than |
1734 | // the maxlen value. |
1735 | if (IsStrnlen) { |
1736 | QualType cmpTy = C.getSValBuilder().getConditionType(); |
1737 | |
1738 | // It's a little unfortunate to be getting this again, |
1739 | // but it's not that expensive... |
1740 | const Expr *maxlenExpr = Call.getArgExpr(Index: 1); |
1741 | SVal maxlenVal = state->getSVal(Ex: maxlenExpr, LCtx); |
1742 | |
1743 | std::optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>(); |
1744 | std::optional<NonLoc> maxlenValNL = maxlenVal.getAs<NonLoc>(); |
1745 | |
1746 | if (strLengthNL && maxlenValNL) { |
1747 | ProgramStateRef stateStringTooLong, stateStringNotTooLong; |
1748 | |
1749 | // Check if the strLength is greater than the maxlen. |
1750 | std::tie(args&: stateStringTooLong, args&: stateStringNotTooLong) = state->assume( |
1751 | Cond: C.getSValBuilder() |
1752 | .evalBinOpNN(state, op: BO_GT, lhs: *strLengthNL, rhs: *maxlenValNL, resultTy: cmpTy) |
1753 | .castAs<DefinedOrUnknownSVal>()); |
1754 | |
1755 | if (stateStringTooLong && !stateStringNotTooLong) { |
1756 | // If the string is longer than maxlen, return maxlen. |
1757 | result = *maxlenValNL; |
1758 | } else if (stateStringNotTooLong && !stateStringTooLong) { |
1759 | // If the string is shorter than maxlen, return its length. |
1760 | result = *strLengthNL; |
1761 | } |
1762 | } |
1763 | |
1764 | if (result.isUnknown()) { |
1765 | // If we don't have enough information for a comparison, there's |
1766 | // no guarantee the full string length will actually be returned. |
1767 | // All we know is the return value is the min of the string length |
1768 | // and the limit. This is better than nothing. |
1769 | result = C.getSValBuilder().conjureSymbolVal(call: Call, visitCount: C.blockCount()); |
1770 | NonLoc resultNL = result.castAs<NonLoc>(); |
1771 | |
1772 | if (strLengthNL) { |
1773 | state = state->assume(Cond: C.getSValBuilder().evalBinOpNN( |
1774 | state, op: BO_LE, lhs: resultNL, rhs: *strLengthNL, resultTy: cmpTy) |
1775 | .castAs<DefinedOrUnknownSVal>(), Assumption: true); |
1776 | } |
1777 | |
1778 | if (maxlenValNL) { |
1779 | state = state->assume(Cond: C.getSValBuilder().evalBinOpNN( |
1780 | state, op: BO_LE, lhs: resultNL, rhs: *maxlenValNL, resultTy: cmpTy) |
1781 | .castAs<DefinedOrUnknownSVal>(), Assumption: true); |
1782 | } |
1783 | } |
1784 | |
1785 | } else { |
1786 | // This is a plain strlen(), not strnlen(). |
1787 | result = strLength.castAs<DefinedOrUnknownSVal>(); |
1788 | |
1789 | // If we don't know the length of the string, conjure a return |
1790 | // value, so it can be used in constraints, at least. |
1791 | if (result.isUnknown()) { |
1792 | result = C.getSValBuilder().conjureSymbolVal(call: Call, visitCount: C.blockCount()); |
1793 | } |
1794 | } |
1795 | |
1796 | // Bind the return value. |
1797 | assert(!result.isUnknown() && "Should have conjured a value by now" ); |
1798 | state = state->BindExpr(S: Call.getOriginExpr(), LCtx, V: result); |
1799 | C.addTransition(State: state); |
1800 | } |
1801 | |
1802 | void CStringChecker::evalStrcpy(CheckerContext &C, |
1803 | const CallEvent &Call) const { |
1804 | // char *strcpy(char *restrict dst, const char *restrict src); |
1805 | evalStrcpyCommon(C, Call, |
1806 | /* ReturnEnd = */ false, |
1807 | /* IsBounded = */ false, |
1808 | /* appendK = */ ConcatFnKind::none); |
1809 | } |
1810 | |
1811 | void CStringChecker::evalStrncpy(CheckerContext &C, |
1812 | const CallEvent &Call) const { |
1813 | // char *strncpy(char *restrict dst, const char *restrict src, size_t n); |
1814 | evalStrcpyCommon(C, Call, |
1815 | /* ReturnEnd = */ false, |
1816 | /* IsBounded = */ true, |
1817 | /* appendK = */ ConcatFnKind::none); |
1818 | } |
1819 | |
1820 | void CStringChecker::evalStpcpy(CheckerContext &C, |
1821 | const CallEvent &Call) const { |
1822 | // char *stpcpy(char *restrict dst, const char *restrict src); |
1823 | evalStrcpyCommon(C, Call, |
1824 | /* ReturnEnd = */ true, |
1825 | /* IsBounded = */ false, |
1826 | /* appendK = */ ConcatFnKind::none); |
1827 | } |
1828 | |
1829 | void CStringChecker::evalStrlcpy(CheckerContext &C, |
1830 | const CallEvent &Call) const { |
1831 | // size_t strlcpy(char *dest, const char *src, size_t size); |
1832 | evalStrcpyCommon(C, Call, |
1833 | /* ReturnEnd = */ true, |
1834 | /* IsBounded = */ true, |
1835 | /* appendK = */ ConcatFnKind::none, |
1836 | /* returnPtr = */ false); |
1837 | } |
1838 | |
1839 | void CStringChecker::evalStrcat(CheckerContext &C, |
1840 | const CallEvent &Call) const { |
1841 | // char *strcat(char *restrict s1, const char *restrict s2); |
1842 | evalStrcpyCommon(C, Call, |
1843 | /* ReturnEnd = */ false, |
1844 | /* IsBounded = */ false, |
1845 | /* appendK = */ ConcatFnKind::strcat); |
1846 | } |
1847 | |
1848 | void CStringChecker::evalStrncat(CheckerContext &C, |
1849 | const CallEvent &Call) const { |
1850 | // char *strncat(char *restrict s1, const char *restrict s2, size_t n); |
1851 | evalStrcpyCommon(C, Call, |
1852 | /* ReturnEnd = */ false, |
1853 | /* IsBounded = */ true, |
1854 | /* appendK = */ ConcatFnKind::strcat); |
1855 | } |
1856 | |
1857 | void CStringChecker::evalStrlcat(CheckerContext &C, |
1858 | const CallEvent &Call) const { |
1859 | // size_t strlcat(char *dst, const char *src, size_t size); |
1860 | // It will append at most size - strlen(dst) - 1 bytes, |
1861 | // NULL-terminating the result. |
1862 | evalStrcpyCommon(C, Call, |
1863 | /* ReturnEnd = */ false, |
1864 | /* IsBounded = */ true, |
1865 | /* appendK = */ ConcatFnKind::strlcat, |
1866 | /* returnPtr = */ false); |
1867 | } |
1868 | |
1869 | void CStringChecker::evalStrcpyCommon(CheckerContext &C, const CallEvent &Call, |
1870 | bool ReturnEnd, bool IsBounded, |
1871 | ConcatFnKind appendK, |
1872 | bool returnPtr) const { |
1873 | if (appendK == ConcatFnKind::none) |
1874 | CurrentFunctionDescription = "string copy function" ; |
1875 | else |
1876 | CurrentFunctionDescription = "string concatenation function" ; |
1877 | |
1878 | ProgramStateRef state = C.getState(); |
1879 | const LocationContext *LCtx = C.getLocationContext(); |
1880 | |
1881 | // Check that the destination is non-null. |
1882 | DestinationArgExpr Dst = {{.Expression: Call.getArgExpr(Index: 0), .ArgumentIndex: 0}}; |
1883 | SVal DstVal = state->getSVal(Ex: Dst.Expression, LCtx); |
1884 | state = checkNonNull(C, State: state, Arg: Dst, l: DstVal); |
1885 | if (!state) |
1886 | return; |
1887 | |
1888 | // Check that the source is non-null. |
1889 | SourceArgExpr srcExpr = {{.Expression: Call.getArgExpr(Index: 1), .ArgumentIndex: 1}}; |
1890 | SVal srcVal = state->getSVal(Ex: srcExpr.Expression, LCtx); |
1891 | state = checkNonNull(C, State: state, Arg: srcExpr, l: srcVal); |
1892 | if (!state) |
1893 | return; |
1894 | |
1895 | // Get the string length of the source. |
1896 | SVal strLength = getCStringLength(C, state, Ex: srcExpr.Expression, Buf: srcVal); |
1897 | std::optional<NonLoc> strLengthNL = strLength.getAs<NonLoc>(); |
1898 | |
1899 | // Get the string length of the destination buffer. |
1900 | SVal dstStrLength = getCStringLength(C, state, Ex: Dst.Expression, Buf: DstVal); |
1901 | std::optional<NonLoc> dstStrLengthNL = dstStrLength.getAs<NonLoc>(); |
1902 | |
1903 | // If the source isn't a valid C string, give up. |
1904 | if (strLength.isUndef()) |
1905 | return; |
1906 | |
1907 | SValBuilder &svalBuilder = C.getSValBuilder(); |
1908 | QualType cmpTy = svalBuilder.getConditionType(); |
1909 | QualType sizeTy = svalBuilder.getContext().getSizeType(); |
1910 | |
1911 | // These two values allow checking two kinds of errors: |
1912 | // - actual overflows caused by a source that doesn't fit in the destination |
1913 | // - potential overflows caused by a bound that could exceed the destination |
1914 | SVal amountCopied = UnknownVal(); |
1915 | SVal maxLastElementIndex = UnknownVal(); |
1916 | const char *boundWarning = nullptr; |
1917 | |
1918 | // FIXME: Why do we choose the srcExpr if the access has no size? |
1919 | // Note that the 3rd argument of the call would be the size parameter. |
1920 | SizeArgExpr SrcExprAsSizeDummy = { |
1921 | {.Expression: srcExpr.Expression, .ArgumentIndex: srcExpr.ArgumentIndex}}; |
1922 | state = CheckOverlap( |
1923 | C, state, |
1924 | Size: (IsBounded ? SizeArgExpr{{.Expression: Call.getArgExpr(Index: 2), .ArgumentIndex: 2}} : SrcExprAsSizeDummy), |
1925 | First: Dst, Second: srcExpr); |
1926 | |
1927 | if (!state) |
1928 | return; |
1929 | |
1930 | // If the function is strncpy, strncat, etc... it is bounded. |
1931 | if (IsBounded) { |
1932 | // Get the max number of characters to copy. |
1933 | SizeArgExpr lenExpr = {{.Expression: Call.getArgExpr(Index: 2), .ArgumentIndex: 2}}; |
1934 | SVal lenVal = state->getSVal(Ex: lenExpr.Expression, LCtx); |
1935 | |
1936 | // Protect against misdeclared strncpy(). |
1937 | lenVal = |
1938 | svalBuilder.evalCast(V: lenVal, CastTy: sizeTy, OriginalTy: lenExpr.Expression->getType()); |
1939 | |
1940 | std::optional<NonLoc> lenValNL = lenVal.getAs<NonLoc>(); |
1941 | |
1942 | // If we know both values, we might be able to figure out how much |
1943 | // we're copying. |
1944 | if (strLengthNL && lenValNL) { |
1945 | switch (appendK) { |
1946 | case ConcatFnKind::none: |
1947 | case ConcatFnKind::strcat: { |
1948 | ProgramStateRef stateSourceTooLong, stateSourceNotTooLong; |
1949 | // Check if the max number to copy is less than the length of the src. |
1950 | // If the bound is equal to the source length, strncpy won't null- |
1951 | // terminate the result! |
1952 | std::tie(args&: stateSourceTooLong, args&: stateSourceNotTooLong) = state->assume( |
1953 | Cond: svalBuilder |
1954 | .evalBinOpNN(state, op: BO_GE, lhs: *strLengthNL, rhs: *lenValNL, resultTy: cmpTy) |
1955 | .castAs<DefinedOrUnknownSVal>()); |
1956 | |
1957 | if (stateSourceTooLong && !stateSourceNotTooLong) { |
1958 | // Max number to copy is less than the length of the src, so the |
1959 | // actual strLength copied is the max number arg. |
1960 | state = stateSourceTooLong; |
1961 | amountCopied = lenVal; |
1962 | |
1963 | } else if (!stateSourceTooLong && stateSourceNotTooLong) { |
1964 | // The source buffer entirely fits in the bound. |
1965 | state = stateSourceNotTooLong; |
1966 | amountCopied = strLength; |
1967 | } |
1968 | break; |
1969 | } |
1970 | case ConcatFnKind::strlcat: |
1971 | if (!dstStrLengthNL) |
1972 | return; |
1973 | |
1974 | // amountCopied = min (size - dstLen - 1 , srcLen) |
1975 | SVal freeSpace = svalBuilder.evalBinOpNN(state, op: BO_Sub, lhs: *lenValNL, |
1976 | rhs: *dstStrLengthNL, resultTy: sizeTy); |
1977 | if (!isa<NonLoc>(Val: freeSpace)) |
1978 | return; |
1979 | freeSpace = |
1980 | svalBuilder.evalBinOp(state, op: BO_Sub, lhs: freeSpace, |
1981 | rhs: svalBuilder.makeIntVal(integer: 1, type: sizeTy), type: sizeTy); |
1982 | std::optional<NonLoc> freeSpaceNL = freeSpace.getAs<NonLoc>(); |
1983 | |
1984 | // While unlikely, it is possible that the subtraction is |
1985 | // too complex to compute, let's check whether it succeeded. |
1986 | if (!freeSpaceNL) |
1987 | return; |
1988 | SVal hasEnoughSpace = svalBuilder.evalBinOpNN( |
1989 | state, op: BO_LE, lhs: *strLengthNL, rhs: *freeSpaceNL, resultTy: cmpTy); |
1990 | |
1991 | ProgramStateRef TrueState, FalseState; |
1992 | std::tie(args&: TrueState, args&: FalseState) = |
1993 | state->assume(Cond: hasEnoughSpace.castAs<DefinedOrUnknownSVal>()); |
1994 | |
1995 | // srcStrLength <= size - dstStrLength -1 |
1996 | if (TrueState && !FalseState) { |
1997 | amountCopied = strLength; |
1998 | } |
1999 | |
2000 | // srcStrLength > size - dstStrLength -1 |
2001 | if (!TrueState && FalseState) { |
2002 | amountCopied = freeSpace; |
2003 | } |
2004 | |
2005 | if (TrueState && FalseState) |
2006 | amountCopied = UnknownVal(); |
2007 | break; |
2008 | } |
2009 | } |
2010 | // We still want to know if the bound is known to be too large. |
2011 | if (lenValNL) { |
2012 | switch (appendK) { |
2013 | case ConcatFnKind::strcat: |
2014 | // For strncat, the check is strlen(dst) + lenVal < sizeof(dst) |
2015 | |
2016 | // Get the string length of the destination. If the destination is |
2017 | // memory that can't have a string length, we shouldn't be copying |
2018 | // into it anyway. |
2019 | if (dstStrLength.isUndef()) |
2020 | return; |
2021 | |
2022 | if (dstStrLengthNL) { |
2023 | maxLastElementIndex = svalBuilder.evalBinOpNN( |
2024 | state, op: BO_Add, lhs: *lenValNL, rhs: *dstStrLengthNL, resultTy: sizeTy); |
2025 | |
2026 | boundWarning = "Size argument is greater than the free space in the " |
2027 | "destination buffer" ; |
2028 | } |
2029 | break; |
2030 | case ConcatFnKind::none: |
2031 | case ConcatFnKind::strlcat: |
2032 | // For strncpy and strlcat, this is just checking |
2033 | // that lenVal <= sizeof(dst). |
2034 | // (Yes, strncpy and strncat differ in how they treat termination. |
2035 | // strncat ALWAYS terminates, but strncpy doesn't.) |
2036 | |
2037 | // We need a special case for when the copy size is zero, in which |
2038 | // case strncpy will do no work at all. Our bounds check uses n-1 |
2039 | // as the last element accessed, so n == 0 is problematic. |
2040 | ProgramStateRef StateZeroSize, StateNonZeroSize; |
2041 | std::tie(args&: StateZeroSize, args&: StateNonZeroSize) = |
2042 | assumeZero(C, State: state, V: *lenValNL, Ty: sizeTy); |
2043 | |
2044 | // If the size is known to be zero, we're done. |
2045 | if (StateZeroSize && !StateNonZeroSize) { |
2046 | if (returnPtr) { |
2047 | StateZeroSize = |
2048 | StateZeroSize->BindExpr(S: Call.getOriginExpr(), LCtx, V: DstVal); |
2049 | } else { |
2050 | if (appendK == ConcatFnKind::none) { |
2051 | // strlcpy returns strlen(src) |
2052 | StateZeroSize = StateZeroSize->BindExpr(S: Call.getOriginExpr(), |
2053 | LCtx, V: strLength); |
2054 | } else { |
2055 | // strlcat returns strlen(src) + strlen(dst) |
2056 | SVal retSize = svalBuilder.evalBinOp( |
2057 | state, op: BO_Add, lhs: strLength, rhs: dstStrLength, type: sizeTy); |
2058 | StateZeroSize = |
2059 | StateZeroSize->BindExpr(S: Call.getOriginExpr(), LCtx, V: retSize); |
2060 | } |
2061 | } |
2062 | C.addTransition(State: StateZeroSize); |
2063 | return; |
2064 | } |
2065 | |
2066 | // Otherwise, go ahead and figure out the last element we'll touch. |
2067 | // We don't record the non-zero assumption here because we can't |
2068 | // be sure. We won't warn on a possible zero. |
2069 | NonLoc one = svalBuilder.makeIntVal(integer: 1, type: sizeTy).castAs<NonLoc>(); |
2070 | maxLastElementIndex = |
2071 | svalBuilder.evalBinOpNN(state, op: BO_Sub, lhs: *lenValNL, rhs: one, resultTy: sizeTy); |
2072 | boundWarning = "Size argument is greater than the length of the " |
2073 | "destination buffer" ; |
2074 | break; |
2075 | } |
2076 | } |
2077 | } else { |
2078 | // The function isn't bounded. The amount copied should match the length |
2079 | // of the source buffer. |
2080 | amountCopied = strLength; |
2081 | } |
2082 | |
2083 | assert(state); |
2084 | |
2085 | // This represents the number of characters copied into the destination |
2086 | // buffer. (It may not actually be the strlen if the destination buffer |
2087 | // is not terminated.) |
2088 | SVal finalStrLength = UnknownVal(); |
2089 | SVal strlRetVal = UnknownVal(); |
2090 | |
2091 | if (appendK == ConcatFnKind::none && !returnPtr) { |
2092 | // strlcpy returns the sizeof(src) |
2093 | strlRetVal = strLength; |
2094 | } |
2095 | |
2096 | // If this is an appending function (strcat, strncat...) then set the |
2097 | // string length to strlen(src) + strlen(dst) since the buffer will |
2098 | // ultimately contain both. |
2099 | if (appendK != ConcatFnKind::none) { |
2100 | // Get the string length of the destination. If the destination is memory |
2101 | // that can't have a string length, we shouldn't be copying into it anyway. |
2102 | if (dstStrLength.isUndef()) |
2103 | return; |
2104 | |
2105 | if (appendK == ConcatFnKind::strlcat && dstStrLengthNL && strLengthNL) { |
2106 | strlRetVal = svalBuilder.evalBinOpNN(state, op: BO_Add, lhs: *strLengthNL, |
2107 | rhs: *dstStrLengthNL, resultTy: sizeTy); |
2108 | } |
2109 | |
2110 | std::optional<NonLoc> amountCopiedNL = amountCopied.getAs<NonLoc>(); |
2111 | |
2112 | // If we know both string lengths, we might know the final string length. |
2113 | if (amountCopiedNL && dstStrLengthNL) { |
2114 | // Make sure the two lengths together don't overflow a size_t. |
2115 | state = checkAdditionOverflow(C, state, left: *amountCopiedNL, right: *dstStrLengthNL); |
2116 | if (!state) |
2117 | return; |
2118 | |
2119 | finalStrLength = svalBuilder.evalBinOpNN(state, op: BO_Add, lhs: *amountCopiedNL, |
2120 | rhs: *dstStrLengthNL, resultTy: sizeTy); |
2121 | } |
2122 | |
2123 | // If we couldn't get a single value for the final string length, |
2124 | // we can at least bound it by the individual lengths. |
2125 | if (finalStrLength.isUnknown()) { |
2126 | // Try to get a "hypothetical" string length symbol, which we can later |
2127 | // set as a real value if that turns out to be the case. |
2128 | finalStrLength = |
2129 | getCStringLength(C, state, Ex: Call.getOriginExpr(), Buf: DstVal, hypothetical: true); |
2130 | assert(!finalStrLength.isUndef()); |
2131 | |
2132 | if (std::optional<NonLoc> finalStrLengthNL = |
2133 | finalStrLength.getAs<NonLoc>()) { |
2134 | if (amountCopiedNL && appendK == ConcatFnKind::none) { |
2135 | // we overwrite dst string with the src |
2136 | // finalStrLength >= srcStrLength |
2137 | SVal sourceInResult = svalBuilder.evalBinOpNN( |
2138 | state, op: BO_GE, lhs: *finalStrLengthNL, rhs: *amountCopiedNL, resultTy: cmpTy); |
2139 | state = state->assume(Cond: sourceInResult.castAs<DefinedOrUnknownSVal>(), |
2140 | Assumption: true); |
2141 | if (!state) |
2142 | return; |
2143 | } |
2144 | |
2145 | if (dstStrLengthNL && appendK != ConcatFnKind::none) { |
2146 | // we extend the dst string with the src |
2147 | // finalStrLength >= dstStrLength |
2148 | SVal destInResult = svalBuilder.evalBinOpNN(state, op: BO_GE, |
2149 | lhs: *finalStrLengthNL, |
2150 | rhs: *dstStrLengthNL, |
2151 | resultTy: cmpTy); |
2152 | state = |
2153 | state->assume(Cond: destInResult.castAs<DefinedOrUnknownSVal>(), Assumption: true); |
2154 | if (!state) |
2155 | return; |
2156 | } |
2157 | } |
2158 | } |
2159 | |
2160 | } else { |
2161 | // Otherwise, this is a copy-over function (strcpy, strncpy, ...), and |
2162 | // the final string length will match the input string length. |
2163 | finalStrLength = amountCopied; |
2164 | } |
2165 | |
2166 | SVal Result; |
2167 | |
2168 | if (returnPtr) { |
2169 | // The final result of the function will either be a pointer past the last |
2170 | // copied element, or a pointer to the start of the destination buffer. |
2171 | Result = (ReturnEnd ? UnknownVal() : DstVal); |
2172 | } else { |
2173 | if (appendK == ConcatFnKind::strlcat || appendK == ConcatFnKind::none) |
2174 | //strlcpy, strlcat |
2175 | Result = strlRetVal; |
2176 | else |
2177 | Result = finalStrLength; |
2178 | } |
2179 | |
2180 | assert(state); |
2181 | |
2182 | // If the destination is a MemRegion, try to check for a buffer overflow and |
2183 | // record the new string length. |
2184 | if (std::optional<loc::MemRegionVal> dstRegVal = |
2185 | DstVal.getAs<loc::MemRegionVal>()) { |
2186 | QualType ptrTy = Dst.Expression->getType(); |
2187 | |
2188 | // If we have an exact value on a bounded copy, use that to check for |
2189 | // overflows, rather than our estimate about how much is actually copied. |
2190 | if (std::optional<NonLoc> maxLastNL = maxLastElementIndex.getAs<NonLoc>()) { |
2191 | SVal maxLastElement = |
2192 | svalBuilder.evalBinOpLN(state, op: BO_Add, lhs: *dstRegVal, rhs: *maxLastNL, resultTy: ptrTy); |
2193 | |
2194 | // Check if the first byte of the destination is writable. |
2195 | state = CheckLocation(C, state, Buffer: Dst, Element: DstVal, Access: AccessKind::write); |
2196 | if (!state) |
2197 | return; |
2198 | // Check if the last byte of the destination is writable. |
2199 | state = CheckLocation(C, state, Buffer: Dst, Element: maxLastElement, Access: AccessKind::write); |
2200 | if (!state) |
2201 | return; |
2202 | } |
2203 | |
2204 | // Then, if the final length is known... |
2205 | if (std::optional<NonLoc> knownStrLength = finalStrLength.getAs<NonLoc>()) { |
2206 | SVal lastElement = svalBuilder.evalBinOpLN(state, op: BO_Add, lhs: *dstRegVal, |
2207 | rhs: *knownStrLength, resultTy: ptrTy); |
2208 | |
2209 | // ...and we haven't checked the bound, we'll check the actual copy. |
2210 | if (!boundWarning) { |
2211 | // Check if the first byte of the destination is writable. |
2212 | state = CheckLocation(C, state, Buffer: Dst, Element: DstVal, Access: AccessKind::write); |
2213 | if (!state) |
2214 | return; |
2215 | // Check if the last byte of the destination is writable. |
2216 | state = CheckLocation(C, state, Buffer: Dst, Element: lastElement, Access: AccessKind::write); |
2217 | if (!state) |
2218 | return; |
2219 | } |
2220 | |
2221 | // If this is a stpcpy-style copy, the last element is the return value. |
2222 | if (returnPtr && ReturnEnd) |
2223 | Result = lastElement; |
2224 | } |
2225 | |
2226 | // Invalidate the destination (regular invalidation without pointer-escaping |
2227 | // the address of the top-level region). This must happen before we set the |
2228 | // C string length because invalidation will clear the length. |
2229 | // FIXME: Even if we can't perfectly model the copy, we should see if we |
2230 | // can use LazyCompoundVals to copy the source values into the destination. |
2231 | // This would probably remove any existing bindings past the end of the |
2232 | // string, but that's still an improvement over blank invalidation. |
2233 | state = invalidateDestinationBufferBySize( |
2234 | C, S: state, BufE: Dst.Expression, Elem: Call.getCFGElementRef(), BufV: *dstRegVal, |
2235 | SizeV: amountCopied, SizeTy: C.getASTContext().getSizeType()); |
2236 | |
2237 | // Invalidate the source (const-invalidation without const-pointer-escaping |
2238 | // the address of the top-level region). |
2239 | state = invalidateSourceBuffer(C, S: state, Elem: Call.getCFGElementRef(), BufV: srcVal); |
2240 | |
2241 | // Set the C string length of the destination, if we know it. |
2242 | if (IsBounded && (appendK == ConcatFnKind::none)) { |
2243 | // strncpy is annoying in that it doesn't guarantee to null-terminate |
2244 | // the result string. If the original string didn't fit entirely inside |
2245 | // the bound (including the null-terminator), we don't know how long the |
2246 | // result is. |
2247 | if (amountCopied != strLength) |
2248 | finalStrLength = UnknownVal(); |
2249 | } |
2250 | state = setCStringLength(state, MR: dstRegVal->getRegion(), strLength: finalStrLength); |
2251 | } |
2252 | |
2253 | assert(state); |
2254 | |
2255 | if (returnPtr) { |
2256 | // If this is a stpcpy-style copy, but we were unable to check for a buffer |
2257 | // overflow, we still need a result. Conjure a return value. |
2258 | if (ReturnEnd && Result.isUnknown()) { |
2259 | Result = svalBuilder.conjureSymbolVal(call: Call, visitCount: C.blockCount()); |
2260 | } |
2261 | } |
2262 | // Set the return value. |
2263 | state = state->BindExpr(S: Call.getOriginExpr(), LCtx, V: Result); |
2264 | C.addTransition(State: state); |
2265 | } |
2266 | |
2267 | void CStringChecker::evalStrcmp(CheckerContext &C, |
2268 | const CallEvent &Call) const { |
2269 | //int strcmp(const char *s1, const char *s2); |
2270 | evalStrcmpCommon(C, Call, /* IsBounded = */ false, /* IgnoreCase = */ false); |
2271 | } |
2272 | |
2273 | void CStringChecker::evalStrncmp(CheckerContext &C, |
2274 | const CallEvent &Call) const { |
2275 | //int strncmp(const char *s1, const char *s2, size_t n); |
2276 | evalStrcmpCommon(C, Call, /* IsBounded = */ true, /* IgnoreCase = */ false); |
2277 | } |
2278 | |
2279 | void CStringChecker::evalStrcasecmp(CheckerContext &C, |
2280 | const CallEvent &Call) const { |
2281 | //int strcasecmp(const char *s1, const char *s2); |
2282 | evalStrcmpCommon(C, Call, /* IsBounded = */ false, /* IgnoreCase = */ true); |
2283 | } |
2284 | |
2285 | void CStringChecker::evalStrncasecmp(CheckerContext &C, |
2286 | const CallEvent &Call) const { |
2287 | //int strncasecmp(const char *s1, const char *s2, size_t n); |
2288 | evalStrcmpCommon(C, Call, /* IsBounded = */ true, /* IgnoreCase = */ true); |
2289 | } |
2290 | |
2291 | void CStringChecker::evalStrcmpCommon(CheckerContext &C, const CallEvent &Call, |
2292 | bool IsBounded, bool IgnoreCase) const { |
2293 | CurrentFunctionDescription = "string comparison function" ; |
2294 | ProgramStateRef state = C.getState(); |
2295 | const LocationContext *LCtx = C.getLocationContext(); |
2296 | |
2297 | // Check that the first string is non-null |
2298 | AnyArgExpr Left = {.Expression: Call.getArgExpr(Index: 0), .ArgumentIndex: 0}; |
2299 | SVal LeftVal = state->getSVal(Ex: Left.Expression, LCtx); |
2300 | state = checkNonNull(C, State: state, Arg: Left, l: LeftVal); |
2301 | if (!state) |
2302 | return; |
2303 | |
2304 | // Check that the second string is non-null. |
2305 | AnyArgExpr Right = {.Expression: Call.getArgExpr(Index: 1), .ArgumentIndex: 1}; |
2306 | SVal RightVal = state->getSVal(Ex: Right.Expression, LCtx); |
2307 | state = checkNonNull(C, State: state, Arg: Right, l: RightVal); |
2308 | if (!state) |
2309 | return; |
2310 | |
2311 | // Get the string length of the first string or give up. |
2312 | SVal LeftLength = getCStringLength(C, state, Ex: Left.Expression, Buf: LeftVal); |
2313 | if (LeftLength.isUndef()) |
2314 | return; |
2315 | |
2316 | // Get the string length of the second string or give up. |
2317 | SVal RightLength = getCStringLength(C, state, Ex: Right.Expression, Buf: RightVal); |
2318 | if (RightLength.isUndef()) |
2319 | return; |
2320 | |
2321 | // If we know the two buffers are the same, we know the result is 0. |
2322 | // First, get the two buffers' addresses. Another checker will have already |
2323 | // made sure they're not undefined. |
2324 | DefinedOrUnknownSVal LV = LeftVal.castAs<DefinedOrUnknownSVal>(); |
2325 | DefinedOrUnknownSVal RV = RightVal.castAs<DefinedOrUnknownSVal>(); |
2326 | |
2327 | // See if they are the same. |
2328 | SValBuilder &svalBuilder = C.getSValBuilder(); |
2329 | DefinedOrUnknownSVal SameBuf = svalBuilder.evalEQ(state, lhs: LV, rhs: RV); |
2330 | ProgramStateRef StSameBuf, StNotSameBuf; |
2331 | std::tie(args&: StSameBuf, args&: StNotSameBuf) = state->assume(Cond: SameBuf); |
2332 | |
2333 | // If the two arguments might be the same buffer, we know the result is 0, |
2334 | // and we only need to check one size. |
2335 | if (StSameBuf) { |
2336 | StSameBuf = |
2337 | StSameBuf->BindExpr(S: Call.getOriginExpr(), LCtx, |
2338 | V: svalBuilder.makeZeroVal(type: Call.getResultType())); |
2339 | C.addTransition(State: StSameBuf); |
2340 | |
2341 | // If the two arguments are GUARANTEED to be the same, we're done! |
2342 | if (!StNotSameBuf) |
2343 | return; |
2344 | } |
2345 | |
2346 | assert(StNotSameBuf); |
2347 | state = StNotSameBuf; |
2348 | |
2349 | // At this point we can go about comparing the two buffers. |
2350 | // For now, we only do this if they're both known string literals. |
2351 | |
2352 | // Attempt to extract string literals from both expressions. |
2353 | const StringLiteral *LeftStrLiteral = |
2354 | getCStringLiteral(C, state, expr: Left.Expression, val: LeftVal); |
2355 | const StringLiteral *RightStrLiteral = |
2356 | getCStringLiteral(C, state, expr: Right.Expression, val: RightVal); |
2357 | bool canComputeResult = false; |
2358 | SVal resultVal = svalBuilder.conjureSymbolVal(call: Call, visitCount: C.blockCount()); |
2359 | |
2360 | if (LeftStrLiteral && RightStrLiteral) { |
2361 | StringRef LeftStrRef = LeftStrLiteral->getString(); |
2362 | StringRef RightStrRef = RightStrLiteral->getString(); |
2363 | |
2364 | if (IsBounded) { |
2365 | // Get the max number of characters to compare. |
2366 | const Expr *lenExpr = Call.getArgExpr(Index: 2); |
2367 | SVal lenVal = state->getSVal(Ex: lenExpr, LCtx); |
2368 | |
2369 | // If the length is known, we can get the right substrings. |
2370 | if (const llvm::APSInt *len = svalBuilder.getKnownValue(state, val: lenVal)) { |
2371 | // Create substrings of each to compare the prefix. |
2372 | LeftStrRef = LeftStrRef.substr(Start: 0, N: (size_t)len->getZExtValue()); |
2373 | RightStrRef = RightStrRef.substr(Start: 0, N: (size_t)len->getZExtValue()); |
2374 | canComputeResult = true; |
2375 | } |
2376 | } else { |
2377 | // This is a normal, unbounded strcmp. |
2378 | canComputeResult = true; |
2379 | } |
2380 | |
2381 | if (canComputeResult) { |
2382 | // Real strcmp stops at null characters. |
2383 | size_t s1Term = LeftStrRef.find(C: '\0'); |
2384 | if (s1Term != StringRef::npos) |
2385 | LeftStrRef = LeftStrRef.substr(Start: 0, N: s1Term); |
2386 | |
2387 | size_t s2Term = RightStrRef.find(C: '\0'); |
2388 | if (s2Term != StringRef::npos) |
2389 | RightStrRef = RightStrRef.substr(Start: 0, N: s2Term); |
2390 | |
2391 | // Use StringRef's comparison methods to compute the actual result. |
2392 | int compareRes = IgnoreCase ? LeftStrRef.compare_insensitive(RHS: RightStrRef) |
2393 | : LeftStrRef.compare(RHS: RightStrRef); |
2394 | |
2395 | // The strcmp function returns an integer greater than, equal to, or less |
2396 | // than zero, [c11, p7.24.4.2]. |
2397 | if (compareRes == 0) { |
2398 | resultVal = svalBuilder.makeIntVal(integer: compareRes, type: Call.getResultType()); |
2399 | } |
2400 | else { |
2401 | DefinedSVal zeroVal = svalBuilder.makeIntVal(integer: 0, type: Call.getResultType()); |
2402 | // Constrain strcmp's result range based on the result of StringRef's |
2403 | // comparison methods. |
2404 | BinaryOperatorKind op = (compareRes > 0) ? BO_GT : BO_LT; |
2405 | SVal compareWithZero = |
2406 | svalBuilder.evalBinOp(state, op, lhs: resultVal, rhs: zeroVal, |
2407 | type: svalBuilder.getConditionType()); |
2408 | DefinedSVal compareWithZeroVal = compareWithZero.castAs<DefinedSVal>(); |
2409 | state = state->assume(Cond: compareWithZeroVal, Assumption: true); |
2410 | } |
2411 | } |
2412 | } |
2413 | |
2414 | state = state->BindExpr(S: Call.getOriginExpr(), LCtx, V: resultVal); |
2415 | |
2416 | // Record this as a possible path. |
2417 | C.addTransition(State: state); |
2418 | } |
2419 | |
2420 | void CStringChecker::evalStrsep(CheckerContext &C, |
2421 | const CallEvent &Call) const { |
2422 | // char *strsep(char **stringp, const char *delim); |
2423 | // Verify whether the search string parameter matches the return type. |
2424 | SourceArgExpr SearchStrPtr = {{.Expression: Call.getArgExpr(Index: 0), .ArgumentIndex: 0}}; |
2425 | |
2426 | QualType CharPtrTy = SearchStrPtr.Expression->getType()->getPointeeType(); |
2427 | if (CharPtrTy.isNull() || Call.getResultType().getUnqualifiedType() != |
2428 | CharPtrTy.getUnqualifiedType()) |
2429 | return; |
2430 | |
2431 | CurrentFunctionDescription = "strsep()" ; |
2432 | ProgramStateRef State = C.getState(); |
2433 | const LocationContext *LCtx = C.getLocationContext(); |
2434 | |
2435 | // Check that the search string pointer is non-null (though it may point to |
2436 | // a null string). |
2437 | SVal SearchStrVal = State->getSVal(Ex: SearchStrPtr.Expression, LCtx); |
2438 | State = checkNonNull(C, State, Arg: SearchStrPtr, l: SearchStrVal); |
2439 | if (!State) |
2440 | return; |
2441 | |
2442 | // Check that the delimiter string is non-null. |
2443 | AnyArgExpr DelimStr = {.Expression: Call.getArgExpr(Index: 1), .ArgumentIndex: 1}; |
2444 | SVal DelimStrVal = State->getSVal(Ex: DelimStr.Expression, LCtx); |
2445 | State = checkNonNull(C, State, Arg: DelimStr, l: DelimStrVal); |
2446 | if (!State) |
2447 | return; |
2448 | |
2449 | SValBuilder &SVB = C.getSValBuilder(); |
2450 | SVal Result; |
2451 | if (std::optional<Loc> SearchStrLoc = SearchStrVal.getAs<Loc>()) { |
2452 | // Get the current value of the search string pointer, as a char*. |
2453 | Result = State->getSVal(LV: *SearchStrLoc, T: CharPtrTy); |
2454 | |
2455 | // Invalidate the search string, representing the change of one delimiter |
2456 | // character to NUL. |
2457 | // As the replacement never overflows, do not invalidate its super region. |
2458 | State = invalidateDestinationBufferNeverOverflows( |
2459 | C, S: State, Elem: Call.getCFGElementRef(), BufV: Result); |
2460 | |
2461 | // Overwrite the search string pointer. The new value is either an address |
2462 | // further along in the same string, or NULL if there are no more tokens. |
2463 | State = State->bindLoc(location: *SearchStrLoc, |
2464 | V: SVB.conjureSymbolVal(call: Call, visitCount: C.blockCount(), symbolTag: getTag()), |
2465 | LCtx); |
2466 | } else { |
2467 | assert(SearchStrVal.isUnknown()); |
2468 | // Conjure a symbolic value. It's the best we can do. |
2469 | Result = SVB.conjureSymbolVal(call: Call, visitCount: C.blockCount()); |
2470 | } |
2471 | |
2472 | // Set the return value, and finish. |
2473 | State = State->BindExpr(S: Call.getOriginExpr(), LCtx, V: Result); |
2474 | C.addTransition(State); |
2475 | } |
2476 | |
2477 | // These should probably be moved into a C++ standard library checker. |
2478 | void CStringChecker::evalStdCopy(CheckerContext &C, |
2479 | const CallEvent &Call) const { |
2480 | evalStdCopyCommon(C, Call); |
2481 | } |
2482 | |
2483 | void CStringChecker::evalStdCopyBackward(CheckerContext &C, |
2484 | const CallEvent &Call) const { |
2485 | evalStdCopyCommon(C, Call); |
2486 | } |
2487 | |
2488 | void CStringChecker::evalStdCopyCommon(CheckerContext &C, |
2489 | const CallEvent &Call) const { |
2490 | if (!Call.getArgExpr(Index: 2)->getType()->isPointerType()) |
2491 | return; |
2492 | |
2493 | ProgramStateRef State = C.getState(); |
2494 | |
2495 | const LocationContext *LCtx = C.getLocationContext(); |
2496 | |
2497 | // template <class _InputIterator, class _OutputIterator> |
2498 | // _OutputIterator |
2499 | // copy(_InputIterator __first, _InputIterator __last, |
2500 | // _OutputIterator __result) |
2501 | |
2502 | // Invalidate the destination buffer |
2503 | const Expr *Dst = Call.getArgExpr(Index: 2); |
2504 | SVal DstVal = State->getSVal(Ex: Dst, LCtx); |
2505 | // FIXME: As we do not know how many items are copied, we also invalidate the |
2506 | // super region containing the target location. |
2507 | State = invalidateDestinationBufferAlwaysEscapeSuperRegion( |
2508 | C, S: State, Elem: Call.getCFGElementRef(), BufV: DstVal); |
2509 | |
2510 | SValBuilder &SVB = C.getSValBuilder(); |
2511 | |
2512 | SVal ResultVal = SVB.conjureSymbolVal(call: Call, visitCount: C.blockCount()); |
2513 | State = State->BindExpr(S: Call.getOriginExpr(), LCtx, V: ResultVal); |
2514 | |
2515 | C.addTransition(State); |
2516 | } |
2517 | |
2518 | void CStringChecker::evalMemset(CheckerContext &C, |
2519 | const CallEvent &Call) const { |
2520 | // void *memset(void *s, int c, size_t n); |
2521 | CurrentFunctionDescription = "memory set function" ; |
2522 | |
2523 | DestinationArgExpr Buffer = {{.Expression: Call.getArgExpr(Index: 0), .ArgumentIndex: 0}}; |
2524 | AnyArgExpr CharE = {.Expression: Call.getArgExpr(Index: 1), .ArgumentIndex: 1}; |
2525 | SizeArgExpr Size = {{.Expression: Call.getArgExpr(Index: 2), .ArgumentIndex: 2}}; |
2526 | |
2527 | ProgramStateRef State = C.getState(); |
2528 | |
2529 | // See if the size argument is zero. |
2530 | const LocationContext *LCtx = C.getLocationContext(); |
2531 | SVal SizeVal = C.getSVal(S: Size.Expression); |
2532 | QualType SizeTy = Size.Expression->getType(); |
2533 | |
2534 | ProgramStateRef ZeroSize, NonZeroSize; |
2535 | std::tie(args&: ZeroSize, args&: NonZeroSize) = assumeZero(C, State, V: SizeVal, Ty: SizeTy); |
2536 | |
2537 | // Get the value of the memory area. |
2538 | SVal BufferPtrVal = C.getSVal(S: Buffer.Expression); |
2539 | |
2540 | // If the size is zero, there won't be any actual memory access, so |
2541 | // just bind the return value to the buffer and return. |
2542 | if (ZeroSize && !NonZeroSize) { |
2543 | ZeroSize = ZeroSize->BindExpr(S: Call.getOriginExpr(), LCtx, V: BufferPtrVal); |
2544 | C.addTransition(State: ZeroSize); |
2545 | return; |
2546 | } |
2547 | |
2548 | // Ensure the memory area is not null. |
2549 | // If it is NULL there will be a NULL pointer dereference. |
2550 | State = checkNonNull(C, State: NonZeroSize, Arg: Buffer, l: BufferPtrVal); |
2551 | if (!State) |
2552 | return; |
2553 | |
2554 | State = CheckBufferAccess(C, State, Buffer, Size, Access: AccessKind::write); |
2555 | if (!State) |
2556 | return; |
2557 | |
2558 | // According to the values of the arguments, bind the value of the second |
2559 | // argument to the destination buffer and set string length, or just |
2560 | // invalidate the destination buffer. |
2561 | if (!memsetAux(DstBuffer: Buffer.Expression, Elem: Call.getCFGElementRef(), |
2562 | CharVal: C.getSVal(S: CharE.Expression), Size: Size.Expression, C, State)) |
2563 | return; |
2564 | |
2565 | State = State->BindExpr(S: Call.getOriginExpr(), LCtx, V: BufferPtrVal); |
2566 | C.addTransition(State); |
2567 | } |
2568 | |
2569 | void CStringChecker::evalBzero(CheckerContext &C, const CallEvent &Call) const { |
2570 | CurrentFunctionDescription = "memory clearance function" ; |
2571 | |
2572 | DestinationArgExpr Buffer = {{.Expression: Call.getArgExpr(Index: 0), .ArgumentIndex: 0}}; |
2573 | SizeArgExpr Size = {{.Expression: Call.getArgExpr(Index: 1), .ArgumentIndex: 1}}; |
2574 | SVal Zero = C.getSValBuilder().makeZeroVal(type: C.getASTContext().IntTy); |
2575 | |
2576 | ProgramStateRef State = C.getState(); |
2577 | |
2578 | // See if the size argument is zero. |
2579 | SVal SizeVal = C.getSVal(S: Size.Expression); |
2580 | QualType SizeTy = Size.Expression->getType(); |
2581 | |
2582 | ProgramStateRef StateZeroSize, StateNonZeroSize; |
2583 | std::tie(args&: StateZeroSize, args&: StateNonZeroSize) = |
2584 | assumeZero(C, State, V: SizeVal, Ty: SizeTy); |
2585 | |
2586 | // If the size is zero, there won't be any actual memory access, |
2587 | // In this case we just return. |
2588 | if (StateZeroSize && !StateNonZeroSize) { |
2589 | C.addTransition(State: StateZeroSize); |
2590 | return; |
2591 | } |
2592 | |
2593 | // Get the value of the memory area. |
2594 | SVal MemVal = C.getSVal(S: Buffer.Expression); |
2595 | |
2596 | // Ensure the memory area is not null. |
2597 | // If it is NULL there will be a NULL pointer dereference. |
2598 | State = checkNonNull(C, State: StateNonZeroSize, Arg: Buffer, l: MemVal); |
2599 | if (!State) |
2600 | return; |
2601 | |
2602 | State = CheckBufferAccess(C, State, Buffer, Size, Access: AccessKind::write); |
2603 | if (!State) |
2604 | return; |
2605 | |
2606 | if (!memsetAux(DstBuffer: Buffer.Expression, Elem: Call.getCFGElementRef(), CharVal: Zero, |
2607 | Size: Size.Expression, C, State)) |
2608 | return; |
2609 | |
2610 | C.addTransition(State); |
2611 | } |
2612 | |
2613 | void CStringChecker::evalSprintf(CheckerContext &C, |
2614 | const CallEvent &Call) const { |
2615 | CurrentFunctionDescription = "'sprintf'" ; |
2616 | evalSprintfCommon(C, Call, /* IsBounded = */ false); |
2617 | } |
2618 | |
2619 | void CStringChecker::evalSnprintf(CheckerContext &C, |
2620 | const CallEvent &Call) const { |
2621 | CurrentFunctionDescription = "'snprintf'" ; |
2622 | evalSprintfCommon(C, Call, /* IsBounded = */ true); |
2623 | } |
2624 | |
2625 | void CStringChecker::evalSprintfCommon(CheckerContext &C, const CallEvent &Call, |
2626 | bool IsBounded) const { |
2627 | ProgramStateRef State = C.getState(); |
2628 | const auto *CE = cast<CallExpr>(Val: Call.getOriginExpr()); |
2629 | DestinationArgExpr Dest = {{.Expression: Call.getArgExpr(Index: 0), .ArgumentIndex: 0}}; |
2630 | |
2631 | const auto NumParams = Call.parameters().size(); |
2632 | if (CE->getNumArgs() < NumParams) { |
2633 | // This is an invalid call, let's just ignore it. |
2634 | return; |
2635 | } |
2636 | |
2637 | const auto AllArguments = |
2638 | llvm::make_range(x: CE->getArgs(), y: CE->getArgs() + CE->getNumArgs()); |
2639 | const auto VariadicArguments = drop_begin(RangeOrContainer: enumerate(First: AllArguments), N: NumParams); |
2640 | |
2641 | for (const auto &[ArgIdx, ArgExpr] : VariadicArguments) { |
2642 | // We consider only string buffers |
2643 | if (const QualType type = ArgExpr->getType(); |
2644 | !type->isAnyPointerType() || |
2645 | !type->getPointeeType()->isAnyCharacterType()) |
2646 | continue; |
2647 | SourceArgExpr Source = {{.Expression: ArgExpr, .ArgumentIndex: unsigned(ArgIdx)}}; |
2648 | |
2649 | // Ensure the buffers do not overlap. |
2650 | SizeArgExpr SrcExprAsSizeDummy = { |
2651 | {.Expression: Source.Expression, .ArgumentIndex: Source.ArgumentIndex}}; |
2652 | State = CheckOverlap( |
2653 | C, state: State, |
2654 | Size: (IsBounded ? SizeArgExpr{{.Expression: Call.getArgExpr(Index: 1), .ArgumentIndex: 1}} : SrcExprAsSizeDummy), |
2655 | First: Dest, Second: Source); |
2656 | if (!State) |
2657 | return; |
2658 | } |
2659 | |
2660 | C.addTransition(State); |
2661 | } |
2662 | |
2663 | //===----------------------------------------------------------------------===// |
2664 | // The driver method, and other Checker callbacks. |
2665 | //===----------------------------------------------------------------------===// |
2666 | |
2667 | CStringChecker::FnCheck CStringChecker::identifyCall(const CallEvent &Call, |
2668 | CheckerContext &C) const { |
2669 | const auto *CE = dyn_cast_or_null<CallExpr>(Val: Call.getOriginExpr()); |
2670 | if (!CE) |
2671 | return nullptr; |
2672 | |
2673 | const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Call.getDecl()); |
2674 | if (!FD) |
2675 | return nullptr; |
2676 | |
2677 | if (StdCopy.matches(Call)) |
2678 | return &CStringChecker::evalStdCopy; |
2679 | if (StdCopyBackward.matches(Call)) |
2680 | return &CStringChecker::evalStdCopyBackward; |
2681 | |
2682 | // Pro-actively check that argument types are safe to do arithmetic upon. |
2683 | // We do not want to crash if someone accidentally passes a structure |
2684 | // into, say, a C++ overload of any of these functions. We could not check |
2685 | // that for std::copy because they may have arguments of other types. |
2686 | for (auto I : CE->arguments()) { |
2687 | QualType T = I->getType(); |
2688 | if (!T->isIntegralOrEnumerationType() && !T->isPointerType()) |
2689 | return nullptr; |
2690 | } |
2691 | |
2692 | const FnCheck *Callback = Callbacks.lookup(Call); |
2693 | if (Callback) |
2694 | return *Callback; |
2695 | |
2696 | return nullptr; |
2697 | } |
2698 | |
2699 | bool CStringChecker::evalCall(const CallEvent &Call, CheckerContext &C) const { |
2700 | FnCheck Callback = identifyCall(Call, C); |
2701 | |
2702 | // If the callee isn't a string function, let another checker handle it. |
2703 | if (!Callback) |
2704 | return false; |
2705 | |
2706 | // Check and evaluate the call. |
2707 | assert(isa<CallExpr>(Call.getOriginExpr())); |
2708 | Callback(this, C, Call); |
2709 | |
2710 | // If the evaluate call resulted in no change, chain to the next eval call |
2711 | // handler. |
2712 | // Note, the custom CString evaluation calls assume that basic safety |
2713 | // properties are held. However, if the user chooses to turn off some of these |
2714 | // checks, we ignore the issues and leave the call evaluation to a generic |
2715 | // handler. |
2716 | return C.isDifferent(); |
2717 | } |
2718 | |
2719 | void CStringChecker::checkPreStmt(const DeclStmt *DS, CheckerContext &C) const { |
2720 | // Record string length for char a[] = "abc"; |
2721 | ProgramStateRef state = C.getState(); |
2722 | |
2723 | for (const auto *I : DS->decls()) { |
2724 | const VarDecl *D = dyn_cast<VarDecl>(Val: I); |
2725 | if (!D) |
2726 | continue; |
2727 | |
2728 | // FIXME: Handle array fields of structs. |
2729 | if (!D->getType()->isArrayType()) |
2730 | continue; |
2731 | |
2732 | const Expr *Init = D->getInit(); |
2733 | if (!Init) |
2734 | continue; |
2735 | if (!isa<StringLiteral>(Val: Init)) |
2736 | continue; |
2737 | |
2738 | Loc VarLoc = state->getLValue(VD: D, LC: C.getLocationContext()); |
2739 | const MemRegion *MR = VarLoc.getAsRegion(); |
2740 | if (!MR) |
2741 | continue; |
2742 | |
2743 | SVal StrVal = C.getSVal(S: Init); |
2744 | assert(StrVal.isValid() && "Initializer string is unknown or undefined" ); |
2745 | DefinedOrUnknownSVal strLength = |
2746 | getCStringLength(C, state, Ex: Init, Buf: StrVal).castAs<DefinedOrUnknownSVal>(); |
2747 | |
2748 | state = state->set<CStringLength>(K: MR, E: strLength); |
2749 | } |
2750 | |
2751 | C.addTransition(State: state); |
2752 | } |
2753 | |
2754 | ProgramStateRef |
2755 | CStringChecker::checkRegionChanges(ProgramStateRef state, |
2756 | const InvalidatedSymbols *, |
2757 | ArrayRef<const MemRegion *> ExplicitRegions, |
2758 | ArrayRef<const MemRegion *> Regions, |
2759 | const LocationContext *LCtx, |
2760 | const CallEvent *Call) const { |
2761 | CStringLengthTy Entries = state->get<CStringLength>(); |
2762 | if (Entries.isEmpty()) |
2763 | return state; |
2764 | |
2765 | llvm::SmallPtrSet<const MemRegion *, 8> Invalidated; |
2766 | llvm::SmallPtrSet<const MemRegion *, 32> SuperRegions; |
2767 | |
2768 | // First build sets for the changed regions and their super-regions. |
2769 | for (const MemRegion *MR : Regions) { |
2770 | Invalidated.insert(Ptr: MR); |
2771 | |
2772 | SuperRegions.insert(Ptr: MR); |
2773 | while (const SubRegion *SR = dyn_cast<SubRegion>(Val: MR)) { |
2774 | MR = SR->getSuperRegion(); |
2775 | SuperRegions.insert(Ptr: MR); |
2776 | } |
2777 | } |
2778 | |
2779 | CStringLengthTy::Factory &F = state->get_context<CStringLength>(); |
2780 | |
2781 | // Then loop over the entries in the current state. |
2782 | for (const MemRegion *MR : llvm::make_first_range(c&: Entries)) { |
2783 | // Is this entry for a super-region of a changed region? |
2784 | if (SuperRegions.count(Ptr: MR)) { |
2785 | Entries = F.remove(Old: Entries, K: MR); |
2786 | continue; |
2787 | } |
2788 | |
2789 | // Is this entry for a sub-region of a changed region? |
2790 | const MemRegion *Super = MR; |
2791 | while (const SubRegion *SR = dyn_cast<SubRegion>(Val: Super)) { |
2792 | Super = SR->getSuperRegion(); |
2793 | if (Invalidated.count(Ptr: Super)) { |
2794 | Entries = F.remove(Old: Entries, K: MR); |
2795 | break; |
2796 | } |
2797 | } |
2798 | } |
2799 | |
2800 | return state->set<CStringLength>(Entries); |
2801 | } |
2802 | |
2803 | void CStringChecker::checkLiveSymbols(ProgramStateRef state, |
2804 | SymbolReaper &SR) const { |
2805 | // Mark all symbols in our string length map as valid. |
2806 | CStringLengthTy Entries = state->get<CStringLength>(); |
2807 | |
2808 | for (SVal Len : llvm::make_second_range(c&: Entries)) { |
2809 | for (SymbolRef Sym : Len.symbols()) |
2810 | SR.markInUse(sym: Sym); |
2811 | } |
2812 | } |
2813 | |
2814 | void CStringChecker::checkDeadSymbols(SymbolReaper &SR, |
2815 | CheckerContext &C) const { |
2816 | ProgramStateRef state = C.getState(); |
2817 | CStringLengthTy Entries = state->get<CStringLength>(); |
2818 | if (Entries.isEmpty()) |
2819 | return; |
2820 | |
2821 | CStringLengthTy::Factory &F = state->get_context<CStringLength>(); |
2822 | for (auto [Reg, Len] : Entries) { |
2823 | if (SymbolRef Sym = Len.getAsSymbol()) { |
2824 | if (SR.isDead(sym: Sym)) |
2825 | Entries = F.remove(Old: Entries, K: Reg); |
2826 | } |
2827 | } |
2828 | |
2829 | state = state->set<CStringLength>(Entries); |
2830 | C.addTransition(State: state); |
2831 | } |
2832 | |
2833 | void ento::registerCStringModeling(CheckerManager &Mgr) { |
2834 | Mgr.registerChecker<CStringChecker>(); |
2835 | } |
2836 | |
2837 | bool ento::shouldRegisterCStringModeling(const CheckerManager &mgr) { |
2838 | return true; |
2839 | } |
2840 | |
2841 | #define REGISTER_CHECKER(name) \ |
2842 | void ento::register##name(CheckerManager &mgr) { \ |
2843 | CStringChecker *checker = mgr.getChecker<CStringChecker>(); \ |
2844 | checker->Filter.Check##name = true; \ |
2845 | checker->Filter.CheckName##name = mgr.getCurrentCheckerName(); \ |
2846 | } \ |
2847 | \ |
2848 | bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; } |
2849 | |
2850 | REGISTER_CHECKER(CStringNullArg) |
2851 | REGISTER_CHECKER(CStringOutOfBounds) |
2852 | REGISTER_CHECKER(CStringBufferOverlap) |
2853 | REGISTER_CHECKER(CStringNotNullTerm) |
2854 | REGISTER_CHECKER(CStringUninitializedRead) |
2855 | |