xref: /llvm-project/clang/unittests/StaticAnalyzer/SValTest.cpp (revision 15f3cd6bfc670ba6106184a903eb04be059e5977)
1 //===- unittests/StaticAnalyzer/SvalTest.cpp ------------------------------===//
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 #include "CheckerRegistration.h"
10 
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/Decl.h"
13 #include "clang/AST/DeclGroup.h"
14 #include "clang/AST/RecursiveASTVisitor.h"
15 #include "clang/AST/Stmt.h"
16 #include "clang/AST/Type.h"
17 #include "clang/StaticAnalyzer/Core/Checker.h"
18 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
22 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
23 #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
24 #include "clang/Testing/TestClangConfig.h"
25 #include "clang/Tooling/Tooling.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "gtest/gtest.h"
31 
32 namespace clang {
33 
34 // getType() tests include whole bunch of type comparisons,
35 // so when something is wrong, it's good to have gtest telling us
36 // what are those types.
operator <<(std::ostream & OS,const QualType & T)37 LLVM_ATTRIBUTE_UNUSED std::ostream &operator<<(std::ostream &OS,
38                                                const QualType &T) {
39   return OS << T.getAsString();
40 }
41 
operator <<(std::ostream & OS,const CanQualType & T)42 LLVM_ATTRIBUTE_UNUSED std::ostream &operator<<(std::ostream &OS,
43                                                const CanQualType &T) {
44   return OS << QualType{T};
45 }
46 
47 namespace ento {
48 namespace {
49 
50 //===----------------------------------------------------------------------===//
51 //                       Testing framework implementation
52 //===----------------------------------------------------------------------===//
53 
54 /// A simple map from variable names to symbolic values used to init them.
55 using SVals = llvm::StringMap<SVal>;
56 
57 /// SValCollector is the barebone of all tests.
58 ///
59 /// It is implemented as a checker and reacts to binds, so we find
60 /// symbolic values of interest, and to end analysis, where we actually
61 /// can test whatever we gathered.
62 class SValCollector : public Checker<check::Bind, check::EndAnalysis> {
63 public:
checkBind(SVal Loc,SVal Val,const Stmt * S,CheckerContext & C) const64   void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const {
65     // Skip instantly if we finished testing.
66     // Also, we care only for binds happening in variable initializations.
67     if (Tested || !isa<DeclStmt>(S))
68       return;
69 
70     if (const auto *VR = llvm::dyn_cast_or_null<VarRegion>(Loc.getAsRegion())) {
71       CollectedSVals[VR->getDescriptiveName(false)] = Val;
72     }
73   }
74 
checkEndAnalysis(ExplodedGraph & G,BugReporter & B,ExprEngine & Engine) const75   void checkEndAnalysis(ExplodedGraph &G, BugReporter &B,
76                         ExprEngine &Engine) const {
77     if (!Tested) {
78       test(Engine, Engine.getContext());
79       Tested = true;
80       CollectedSVals.clear();
81     }
82   }
83 
84   /// Helper function for tests to access bound symbolic values.
getByName(StringRef Name) const85   SVal getByName(StringRef Name) const { return CollectedSVals[Name]; }
86 
87 private:
88   /// Entry point for tests.
89   virtual void test(ExprEngine &Engine, const ASTContext &Context) const = 0;
90 
91   mutable bool Tested = false;
92   mutable SVals CollectedSVals;
93 };
94 
expectSameSignAndBitWidth(QualType ExpectedTy,QualType ActualTy,const ASTContext & Context)95 static void expectSameSignAndBitWidth(QualType ExpectedTy, QualType ActualTy,
96                                       const ASTContext &Context) {
97   EXPECT_EQ(ExpectedTy->isUnsignedIntegerType(),
98             ActualTy->isUnsignedIntegerType());
99   EXPECT_EQ(Context.getTypeSize(ExpectedTy), Context.getTypeSize(ActualTy));
100 }
101 
102 // Fixture class for parameterized SValTest
103 class SValTest : public testing::TestWithParam<TestClangConfig> {};
104 
105 // SVAL_TEST is a combined way of providing a short code snippet and
106 // to test some programmatic predicates on symbolic values produced by the
107 // engine for the actual code.
108 //
109 // Each test has a NAME.  One can think of it as a name for normal gtests.
110 //
111 // Each test should provide a CODE snippet.  Code snippets might contain any
112 // valid C/C++, but have ONLY ONE defined function.  There are no requirements
113 // about function's name or parameters.  It can even be a class method.  The
114 // body of the function must contain a set of variable declarations.  Each
115 // variable declaration gets bound to a symbolic value, so for the following
116 // example:
117 //
118 //     int x = <expr>;
119 //
120 // `x` will be bound to whatever symbolic value the engine produced for <expr>.
121 // LIVENESS and REASSIGNMENTS don't affect this binding.
122 //
123 // During the test the actual values can be accessed via `getByName` function,
124 // and, for the `x`-bound value, one must use "x" as its name.
125 //
126 // Example:
127 // SVAL_TEST(SimpleSValTest, R"(
128 // void foo() {
129 //   int x = 42;
130 // })") {
131 //   SVal X = getByName("x");
132 //   EXPECT_TRUE(X.isConstant(42));
133 // }
134 #define SVAL_TEST(NAME, CODE)                                                  \
135   class NAME##SValCollector final : public SValCollector {                     \
136   public:                                                                      \
137     void test(ExprEngine &Engine, const ASTContext &Context) const override;   \
138   };                                                                           \
139                                                                                \
140   void add##NAME##SValCollector(AnalysisASTConsumer &AnalysisConsumer,         \
141                                 AnalyzerOptions &AnOpts) {                     \
142     AnOpts.CheckersAndPackages = {{"test.##NAME##SValCollector", true}};       \
143     AnalysisConsumer.AddCheckerRegistrationFn([](CheckerRegistry &Registry) {  \
144       Registry.addChecker<NAME##SValCollector>("test.##NAME##SValCollector",   \
145                                                "Description", "");             \
146     });                                                                        \
147   }                                                                            \
148                                                                                \
149   TEST_P(SValTest, NAME) {                                                     \
150     EXPECT_TRUE(runCheckerOnCodeWithArgs<add##NAME##SValCollector>(            \
151         CODE, GetParam().getCommandLineArgs()));                               \
152   }                                                                            \
153   void NAME##SValCollector::test(ExprEngine &Engine,                           \
154                                  const ASTContext &Context) const
155 
156 //===----------------------------------------------------------------------===//
157 //                                 Actual tests
158 //===----------------------------------------------------------------------===//
159 
160 SVAL_TEST(GetConstType, R"(
161 void foo() {
162   int x = 42;
163   int *y = nullptr;
164   bool z = true;
165 })") {
166   SVal X = getByName("x");
167   ASSERT_FALSE(X.getType(Context).isNull());
168   EXPECT_EQ(Context.IntTy, X.getType(Context));
169 
170   SVal Y = getByName("y");
171   ASSERT_FALSE(Y.getType(Context).isNull());
172   expectSameSignAndBitWidth(Context.getUIntPtrType(), Y.getType(Context),
173                             Context);
174 
175   SVal Z = getByName("z");
176   ASSERT_FALSE(Z.getType(Context).isNull());
177   EXPECT_EQ(Context.BoolTy, Z.getType(Context));
178 }
179 
180 SVAL_TEST(GetLocAsIntType, R"(
181 void foo(int *x) {
182   long int a = (long long int)x;
183   unsigned b = (long long unsigned)&a;
184   int c = (long long int)nullptr;
185 })") {
186   SVal A = getByName("a");
187   ASSERT_FALSE(A.getType(Context).isNull());
188 
189   // TODO: Turn it into signed long
190   expectSameSignAndBitWidth(Context.UnsignedLongTy, A.getType(Context),
191                             Context);
192 
193   SVal B = getByName("b");
194   ASSERT_FALSE(B.getType(Context).isNull());
195   expectSameSignAndBitWidth(Context.UnsignedIntTy, B.getType(Context), Context);
196 
197   SVal C = getByName("c");
198   ASSERT_FALSE(C.getType(Context).isNull());
199   expectSameSignAndBitWidth(Context.IntTy, C.getType(Context), Context);
200 }
201 
202 SVAL_TEST(GetSymExprType, R"(
203 void foo(int a, int b) {
204   int x = a;
205   int y = a + b;
206   long z = a;
207 })") {
208   QualType Int = Context.IntTy;
209 
210   SVal X = getByName("x");
211   ASSERT_FALSE(X.getType(Context).isNull());
212   EXPECT_EQ(Int, X.getType(Context));
213 
214   SVal Y = getByName("y");
215   ASSERT_FALSE(Y.getType(Context).isNull());
216   EXPECT_EQ(Int, Y.getType(Context));
217 
218   // TODO: Change to Long when we support symbolic casts
219   SVal Z = getByName("z");
220   ASSERT_FALSE(Z.getType(Context).isNull());
221   EXPECT_EQ(Int, Z.getType(Context));
222 }
223 
224 SVAL_TEST(GetPointerType, R"(
225 int *bar();
226 int &foobar();
227 struct Z {
228   int a;
229   int *b;
230 };
231 void foo(int x, int *y, Z z) {
232   int &a = x;
233   int &b = *y;
234   int &c = *bar();
235   int &d = foobar();
236   int &e = z.a;
237   int &f = *z.b;
238 })") {
239   QualType Int = Context.IntTy;
240 
241   SVal A = getByName("a");
242   ASSERT_FALSE(A.getType(Context).isNull());
243   const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context));
244   ASSERT_NE(APtrTy, nullptr);
245   EXPECT_EQ(Int, APtrTy->getPointeeType());
246 
247   SVal B = getByName("b");
248   ASSERT_FALSE(B.getType(Context).isNull());
249   const auto *BPtrTy = dyn_cast<PointerType>(B.getType(Context));
250   ASSERT_NE(BPtrTy, nullptr);
251   EXPECT_EQ(Int, BPtrTy->getPointeeType());
252 
253   SVal C = getByName("c");
254   ASSERT_FALSE(C.getType(Context).isNull());
255   const auto *CPtrTy = dyn_cast<PointerType>(C.getType(Context));
256   ASSERT_NE(CPtrTy, nullptr);
257   EXPECT_EQ(Int, CPtrTy->getPointeeType());
258 
259   SVal D = getByName("d");
260   ASSERT_FALSE(D.getType(Context).isNull());
261   const auto *DRefTy = dyn_cast<LValueReferenceType>(D.getType(Context));
262   ASSERT_NE(DRefTy, nullptr);
263   EXPECT_EQ(Int, DRefTy->getPointeeType());
264 
265   SVal E = getByName("e");
266   ASSERT_FALSE(E.getType(Context).isNull());
267   const auto *EPtrTy = dyn_cast<PointerType>(E.getType(Context));
268   ASSERT_NE(EPtrTy, nullptr);
269   EXPECT_EQ(Int, EPtrTy->getPointeeType());
270 
271   SVal F = getByName("f");
272   ASSERT_FALSE(F.getType(Context).isNull());
273   const auto *FPtrTy = dyn_cast<PointerType>(F.getType(Context));
274   ASSERT_NE(FPtrTy, nullptr);
275   EXPECT_EQ(Int, FPtrTy->getPointeeType());
276 }
277 
278 SVAL_TEST(GetCompoundType, R"(
279 struct TestStruct {
280   int a, b;
281 };
282 union TestUnion {
283   int a;
284   float b;
285   TestStruct c;
286 };
287 void foo(int x) {
288   int a[] = {1, x, 2};
289   TestStruct b = {x, 42};
290   TestUnion c = {42};
291   TestUnion d = {.c=b};
292 }
293 )") {
294   SVal A = getByName("a");
295   ASSERT_FALSE(A.getType(Context).isNull());
296   const auto *AArrayType = dyn_cast<ArrayType>(A.getType(Context));
297   ASSERT_NE(AArrayType, nullptr);
298   EXPECT_EQ(Context.IntTy, AArrayType->getElementType());
299 
300   SVal B = getByName("b");
301   ASSERT_FALSE(B.getType(Context).isNull());
302   const auto *BRecordType = dyn_cast<RecordType>(B.getType(Context));
303   ASSERT_NE(BRecordType, nullptr);
304   EXPECT_EQ("TestStruct", BRecordType->getDecl()->getName());
305 
306   SVal C = getByName("c");
307   ASSERT_FALSE(C.getType(Context).isNull());
308   const auto *CRecordType = dyn_cast<RecordType>(C.getType(Context));
309   ASSERT_NE(CRecordType, nullptr);
310   EXPECT_EQ("TestUnion", CRecordType->getDecl()->getName());
311 
312   auto D = getByName("d").getAs<nonloc::CompoundVal>();
313   ASSERT_TRUE(D.has_value());
314   auto Begin = D->begin();
315   ASSERT_NE(D->end(), Begin);
316   ++Begin;
317   ASSERT_EQ(D->end(), Begin);
318   auto LD = D->begin()->getAs<nonloc::LazyCompoundVal>();
319   ASSERT_TRUE(LD.has_value());
320   auto LDT = LD->getType(Context);
321   ASSERT_FALSE(LDT.isNull());
322   const auto *DElaboratedType = dyn_cast<ElaboratedType>(LDT);
323   ASSERT_NE(DElaboratedType, nullptr);
324   const auto *DRecordType =
325       dyn_cast<RecordType>(DElaboratedType->getNamedType());
326   ASSERT_NE(DRecordType, nullptr);
327   EXPECT_EQ("TestStruct", DRecordType->getDecl()->getName());
328 }
329 
330 SVAL_TEST(GetStringType, R"(
331 void foo() {
332   const char *a = "Hello, world!";
333 }
334 )") {
335   SVal A = getByName("a");
336   ASSERT_FALSE(A.getType(Context).isNull());
337   const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context));
338   ASSERT_NE(APtrTy, nullptr);
339   EXPECT_EQ(Context.CharTy, APtrTy->getPointeeType());
340 }
341 
342 SVAL_TEST(GetThisType, R"(
343 class TestClass {
344   void foo();
345 };
346 void TestClass::foo() {
347   const auto *a = this;
348 }
349 )") {
350   SVal A = getByName("a");
351   ASSERT_FALSE(A.getType(Context).isNull());
352   const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context));
353   ASSERT_NE(APtrTy, nullptr);
354   const auto *ARecordType = dyn_cast<RecordType>(APtrTy->getPointeeType());
355   ASSERT_NE(ARecordType, nullptr);
356   EXPECT_EQ("TestClass", ARecordType->getDecl()->getName());
357 }
358 
359 SVAL_TEST(GetFunctionPtrType, R"(
360 void bar();
361 void foo() {
362   auto *a = &bar;
363 }
364 )") {
365   SVal A = getByName("a");
366   ASSERT_FALSE(A.getType(Context).isNull());
367   const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context));
368   ASSERT_NE(APtrTy, nullptr);
369   ASSERT_TRUE(isa<FunctionProtoType>(APtrTy->getPointeeType()));
370 }
371 
372 SVAL_TEST(GetLabelType, R"(
373 void foo() {
374   entry:
375   void *a = &&entry;
376   char *b = (char *)&&entry;
377 }
378 )") {
379   SVal A = getByName("a");
380   ASSERT_FALSE(A.getType(Context).isNull());
381   EXPECT_EQ(Context.VoidPtrTy, A.getType(Context));
382 
383   SVal B = getByName("a");
384   ASSERT_FALSE(B.getType(Context).isNull());
385   // TODO: Change to CharTy when we support symbolic casts
386   EXPECT_EQ(Context.VoidPtrTy, B.getType(Context));
387 }
388 
allTestClangConfigs()389 std::vector<TestClangConfig> allTestClangConfigs() {
390   std::vector<TestClangConfig> all_configs;
391   TestClangConfig config;
392   config.Language = Lang_CXX14;
393   for (std::string target :
394        {"i686-pc-windows-msvc",   "i686-apple-darwin9",
395         "x86_64-apple-darwin9",   "x86_64-scei-ps4",
396         "x86_64-windows-msvc",    "x86_64-unknown-linux",
397         "x86_64-apple-macosx",    "x86_64-apple-ios14.0",
398         "wasm32-unknown-unknown", "wasm64-unknown-unknown",
399         "thumb-pc-win32",         "sparc64-none-openbsd",
400         "sparc-none-none",        "riscv64-unknown-linux",
401         "ppc64-windows-msvc",     "powerpc-ibm-aix",
402         "powerpc64-ibm-aix",      "s390x-ibm-zos",
403         "armv7-pc-windows-msvc",  "aarch64-pc-windows-msvc",
404         "xcore-xmos-elf"}) {
405     config.Target = target;
406     all_configs.push_back(config);
407   }
408   return all_configs;
409 }
410 
411 INSTANTIATE_TEST_SUITE_P(SValTests, SValTest,
412                          testing::ValuesIn(allTestClangConfigs()));
413 
414 } // namespace
415 } // namespace ento
416 } // namespace clang
417