Bug Summary

File:clang/lib/StaticAnalyzer/Checkers/CastSizeChecker.cpp
Warning:line 64, column 26
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CastSizeChecker.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/StaticAnalyzer/Checkers -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/StaticAnalyzer/Checkers -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/StaticAnalyzer/Checkers/CastSizeChecker.cpp
1//=== CastSizeChecker.cpp ---------------------------------------*- 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// CastSizeChecker checks when casting a malloc'ed symbolic region to type T,
10// whether the size of the symbolic region is a multiple of the size of T.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/CharUnits.h"
15#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
16#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
17#include "clang/StaticAnalyzer/Core/Checker.h"
18#include "clang/StaticAnalyzer/Core/CheckerManager.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
21
22using namespace clang;
23using namespace ento;
24
25namespace {
26class CastSizeChecker : public Checker< check::PreStmt<CastExpr> > {
27 mutable std::unique_ptr<BuiltinBug> BT;
28
29public:
30 void checkPreStmt(const CastExpr *CE, CheckerContext &C) const;
31};
32}
33
34/// Check if we are casting to a struct with a flexible array at the end.
35/// \code
36/// struct foo {
37/// size_t len;
38/// struct bar data[];
39/// };
40/// \endcode
41/// or
42/// \code
43/// struct foo {
44/// size_t len;
45/// struct bar data[0];
46/// }
47/// \endcode
48/// In these cases it is also valid to allocate size of struct foo + a multiple
49/// of struct bar.
50static bool evenFlexibleArraySize(ASTContext &Ctx, CharUnits RegionSize,
51 CharUnits TypeSize, QualType ToPointeeTy) {
52 const RecordType *RT = ToPointeeTy->getAs<RecordType>();
16
Assuming the object is a 'RecordType'
53 if (!RT)
17
Assuming 'RT' is non-null
18
Taking false branch
54 return false;
55
56 const RecordDecl *RD = RT->getDecl();
57 RecordDecl::field_iterator Iter(RD->field_begin());
58 RecordDecl::field_iterator End(RD->field_end());
59 const FieldDecl *Last = nullptr;
19
'Last' initialized to a null pointer value
60 for (; Iter != End; ++Iter)
20
Loop condition is false. Execution continues on line 62
61 Last = *Iter;
62 assert(Last && "empty structs should already be handled")(static_cast<void> (0));
63
64 const Type *ElemType = Last->getType()->getArrayElementTypeNoTypeQual();
21
Called C++ object pointer is null
65 CharUnits FlexSize;
66 if (const ConstantArrayType *ArrayTy =
67 Ctx.getAsConstantArrayType(Last->getType())) {
68 FlexSize = Ctx.getTypeSizeInChars(ElemType);
69 if (ArrayTy->getSize() == 1 && TypeSize > FlexSize)
70 TypeSize -= FlexSize;
71 else if (ArrayTy->getSize() != 0)
72 return false;
73 } else if (RD->hasFlexibleArrayMember()) {
74 FlexSize = Ctx.getTypeSizeInChars(ElemType);
75 } else {
76 return false;
77 }
78
79 if (FlexSize.isZero())
80 return false;
81
82 CharUnits Left = RegionSize - TypeSize;
83 if (Left.isNegative())
84 return false;
85
86 return Left % FlexSize == 0;
87}
88
89void CastSizeChecker::checkPreStmt(const CastExpr *CE,CheckerContext &C) const {
90 const Expr *E = CE->getSubExpr();
91 ASTContext &Ctx = C.getASTContext();
92 QualType ToTy = Ctx.getCanonicalType(CE->getType());
93 const PointerType *ToPTy = dyn_cast<PointerType>(ToTy.getTypePtr());
1
Assuming the object is a 'PointerType'
94
95 if (!ToPTy)
2
Assuming 'ToPTy' is non-null
3
Taking false branch
96 return;
97
98 QualType ToPointeeTy = ToPTy->getPointeeType();
99
100 // Only perform the check if 'ToPointeeTy' is a complete type.
101 if (ToPointeeTy->isIncompleteType())
4
Assuming the condition is false
5
Taking false branch
102 return;
103
104 ProgramStateRef state = C.getState();
105 const MemRegion *R = C.getSVal(E).getAsRegion();
106 if (!R)
6
Assuming 'R' is non-null
7
Taking false branch
107 return;
108
109 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
8
Assuming 'R' is a 'SymbolicRegion'
110 if (!SR
8.1
'SR' is non-null
)
9
Taking false branch
111 return;
112
113 SValBuilder &svalBuilder = C.getSValBuilder();
114
115 DefinedOrUnknownSVal Size = getDynamicExtent(state, SR, svalBuilder);
116 const llvm::APSInt *SizeInt = svalBuilder.getKnownValue(state, Size);
117 if (!SizeInt)
10
Assuming 'SizeInt' is non-null
11
Taking false branch
118 return;
119
120 CharUnits regionSize = CharUnits::fromQuantity(SizeInt->getZExtValue());
121 CharUnits typeSize = C.getASTContext().getTypeSizeInChars(ToPointeeTy);
122
123 // Ignore void, and a few other un-sizeable types.
124 if (typeSize.isZero())
12
Taking false branch
125 return;
126
127 if (regionSize % typeSize == 0)
13
Assuming the condition is false
14
Taking false branch
128 return;
129
130 if (evenFlexibleArraySize(Ctx, regionSize, typeSize, ToPointeeTy))
15
Calling 'evenFlexibleArraySize'
131 return;
132
133 if (ExplodedNode *errorNode = C.generateErrorNode()) {
134 if (!BT)
135 BT.reset(new BuiltinBug(this, "Cast region with wrong size.",
136 "Cast a region whose size is not a multiple"
137 " of the destination type size."));
138 auto R = std::make_unique<PathSensitiveBugReport>(*BT, BT->getDescription(),
139 errorNode);
140 R->addRange(CE->getSourceRange());
141 C.emitReport(std::move(R));
142 }
143}
144
145void ento::registerCastSizeChecker(CheckerManager &mgr) {
146 mgr.registerChecker<CastSizeChecker>();
147}
148
149bool ento::shouldRegisterCastSizeChecker(const CheckerManager &mgr) {
150 // PR31226: C++ is more complicated than what this checker currently supports.
151 // There are derived-to-base casts, there are different rules for 0-size
152 // structures, no flexible arrays, etc.
153 // FIXME: Disabled on C++ for now.
154 const LangOptions &LO = mgr.getLangOpts();
155 return !LO.CPlusPlus;
156}