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