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. 37 LLVM_ATTRIBUTE_UNUSED std::ostream &operator<<(std::ostream &OS, 38 const QualType &T) { 39 return OS << T.getAsString(); 40 } 41 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: 64 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 75 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. 85 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 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 })") { 165 SVal X = getByName("x"); 166 ASSERT_FALSE(X.getType(Context).isNull()); 167 EXPECT_EQ(Context.IntTy, X.getType(Context)); 168 169 SVal Y = getByName("y"); 170 ASSERT_FALSE(Y.getType(Context).isNull()); 171 expectSameSignAndBitWidth(Context.getUIntPtrType(), Y.getType(Context), 172 Context); 173 } 174 175 SVAL_TEST(GetLocAsIntType, R"( 176 void foo(int *x) { 177 long int a = (long long int)x; 178 unsigned b = (long long unsigned)&a; 179 int c = (long long int)nullptr; 180 })") { 181 SVal A = getByName("a"); 182 ASSERT_FALSE(A.getType(Context).isNull()); 183 184 // TODO: Turn it into signed long 185 expectSameSignAndBitWidth(Context.UnsignedLongTy, A.getType(Context), 186 Context); 187 188 SVal B = getByName("b"); 189 ASSERT_FALSE(B.getType(Context).isNull()); 190 expectSameSignAndBitWidth(Context.UnsignedIntTy, B.getType(Context), Context); 191 192 SVal C = getByName("c"); 193 ASSERT_FALSE(C.getType(Context).isNull()); 194 expectSameSignAndBitWidth(Context.IntTy, C.getType(Context), Context); 195 } 196 197 SVAL_TEST(GetSymExprType, R"( 198 void foo(int a, int b) { 199 int x = a; 200 int y = a + b; 201 long z = a; 202 })") { 203 QualType Int = Context.IntTy; 204 205 SVal X = getByName("x"); 206 ASSERT_FALSE(X.getType(Context).isNull()); 207 EXPECT_EQ(Int, X.getType(Context)); 208 209 SVal Y = getByName("y"); 210 ASSERT_FALSE(Y.getType(Context).isNull()); 211 EXPECT_EQ(Int, Y.getType(Context)); 212 213 // TODO: Change to Long when we support symbolic casts 214 SVal Z = getByName("z"); 215 ASSERT_FALSE(Z.getType(Context).isNull()); 216 EXPECT_EQ(Int, Z.getType(Context)); 217 } 218 219 SVAL_TEST(GetPointerType, R"( 220 int *bar(); 221 int &foobar(); 222 struct Z { 223 int a; 224 int *b; 225 }; 226 void foo(int x, int *y, Z z) { 227 int &a = x; 228 int &b = *y; 229 int &c = *bar(); 230 int &d = foobar(); 231 int &e = z.a; 232 int &f = *z.b; 233 })") { 234 QualType Int = Context.IntTy; 235 236 SVal A = getByName("a"); 237 ASSERT_FALSE(A.getType(Context).isNull()); 238 const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context)); 239 ASSERT_NE(APtrTy, nullptr); 240 EXPECT_EQ(Int, APtrTy->getPointeeType()); 241 242 SVal B = getByName("b"); 243 ASSERT_FALSE(B.getType(Context).isNull()); 244 const auto *BPtrTy = dyn_cast<PointerType>(B.getType(Context)); 245 ASSERT_NE(BPtrTy, nullptr); 246 EXPECT_EQ(Int, BPtrTy->getPointeeType()); 247 248 SVal C = getByName("c"); 249 ASSERT_FALSE(C.getType(Context).isNull()); 250 const auto *CPtrTy = dyn_cast<PointerType>(C.getType(Context)); 251 ASSERT_NE(CPtrTy, nullptr); 252 EXPECT_EQ(Int, CPtrTy->getPointeeType()); 253 254 SVal D = getByName("d"); 255 ASSERT_FALSE(D.getType(Context).isNull()); 256 const auto *DRefTy = dyn_cast<LValueReferenceType>(D.getType(Context)); 257 ASSERT_NE(DRefTy, nullptr); 258 EXPECT_EQ(Int, DRefTy->getPointeeType()); 259 260 SVal E = getByName("e"); 261 ASSERT_FALSE(E.getType(Context).isNull()); 262 const auto *EPtrTy = dyn_cast<PointerType>(E.getType(Context)); 263 ASSERT_NE(EPtrTy, nullptr); 264 EXPECT_EQ(Int, EPtrTy->getPointeeType()); 265 266 SVal F = getByName("f"); 267 ASSERT_FALSE(F.getType(Context).isNull()); 268 const auto *FPtrTy = dyn_cast<PointerType>(F.getType(Context)); 269 ASSERT_NE(FPtrTy, nullptr); 270 EXPECT_EQ(Int, FPtrTy->getPointeeType()); 271 } 272 273 SVAL_TEST(GetCompoundType, R"( 274 struct TestStruct { 275 int a, b; 276 }; 277 union TestUnion { 278 int a; 279 float b; 280 TestStruct c; 281 }; 282 void foo(int x) { 283 int a[] = {1, x, 2}; 284 TestStruct b = {x, 42}; 285 TestUnion c = {42}; 286 TestUnion d = {.c=b}; 287 } 288 )") { 289 SVal A = getByName("a"); 290 ASSERT_FALSE(A.getType(Context).isNull()); 291 const auto *AArrayType = dyn_cast<ArrayType>(A.getType(Context)); 292 ASSERT_NE(AArrayType, nullptr); 293 EXPECT_EQ(Context.IntTy, AArrayType->getElementType()); 294 295 SVal B = getByName("b"); 296 ASSERT_FALSE(B.getType(Context).isNull()); 297 const auto *BRecordType = dyn_cast<RecordType>(B.getType(Context)); 298 ASSERT_NE(BRecordType, nullptr); 299 EXPECT_EQ("TestStruct", BRecordType->getDecl()->getName()); 300 301 SVal C = getByName("c"); 302 ASSERT_FALSE(C.getType(Context).isNull()); 303 const auto *CRecordType = dyn_cast<RecordType>(C.getType(Context)); 304 ASSERT_NE(CRecordType, nullptr); 305 EXPECT_EQ("TestUnion", CRecordType->getDecl()->getName()); 306 307 auto D = getByName("d").getAs<nonloc::CompoundVal>(); 308 ASSERT_TRUE(D.has_value()); 309 auto Begin = D->begin(); 310 ASSERT_NE(D->end(), Begin); 311 ++Begin; 312 ASSERT_EQ(D->end(), Begin); 313 auto LD = D->begin()->getAs<nonloc::LazyCompoundVal>(); 314 ASSERT_TRUE(LD.has_value()); 315 auto LDT = LD->getType(Context); 316 ASSERT_FALSE(LDT.isNull()); 317 const auto *DRecordType = dyn_cast<RecordType>(LDT); 318 ASSERT_NE(DRecordType, nullptr); 319 EXPECT_EQ("TestStruct", DRecordType->getDecl()->getName()); 320 } 321 322 SVAL_TEST(GetStringType, R"( 323 void foo() { 324 const char *a = "Hello, world!"; 325 } 326 )") { 327 SVal A = getByName("a"); 328 ASSERT_FALSE(A.getType(Context).isNull()); 329 const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context)); 330 ASSERT_NE(APtrTy, nullptr); 331 EXPECT_EQ(Context.CharTy, APtrTy->getPointeeType()); 332 } 333 334 SVAL_TEST(GetThisType, R"( 335 class TestClass { 336 void foo(); 337 }; 338 void TestClass::foo() { 339 const auto *a = this; 340 } 341 )") { 342 SVal A = getByName("a"); 343 ASSERT_FALSE(A.getType(Context).isNull()); 344 const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context)); 345 ASSERT_NE(APtrTy, nullptr); 346 const auto *ARecordType = dyn_cast<RecordType>(APtrTy->getPointeeType()); 347 ASSERT_NE(ARecordType, nullptr); 348 EXPECT_EQ("TestClass", ARecordType->getDecl()->getName()); 349 } 350 351 SVAL_TEST(GetFunctionPtrType, R"( 352 void bar(); 353 void foo() { 354 auto *a = &bar; 355 } 356 )") { 357 SVal A = getByName("a"); 358 ASSERT_FALSE(A.getType(Context).isNull()); 359 const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context)); 360 ASSERT_NE(APtrTy, nullptr); 361 ASSERT_TRUE(isa<FunctionProtoType>(APtrTy->getPointeeType())); 362 } 363 364 SVAL_TEST(GetLabelType, R"( 365 void foo() { 366 entry: 367 void *a = &&entry; 368 char *b = (char *)&&entry; 369 } 370 )") { 371 SVal A = getByName("a"); 372 ASSERT_FALSE(A.getType(Context).isNull()); 373 EXPECT_EQ(Context.VoidPtrTy, A.getType(Context)); 374 375 SVal B = getByName("a"); 376 ASSERT_FALSE(B.getType(Context).isNull()); 377 // TODO: Change to CharTy when we support symbolic casts 378 EXPECT_EQ(Context.VoidPtrTy, B.getType(Context)); 379 } 380 381 std::vector<TestClangConfig> allTestClangConfigs() { 382 std::vector<TestClangConfig> all_configs; 383 TestClangConfig config; 384 config.Language = Lang_CXX14; 385 for (std::string target : 386 {"i686-pc-windows-msvc", "i686-apple-darwin9", 387 "x86_64-apple-darwin9", "x86_64-scei-ps4", 388 "x86_64-windows-msvc", "x86_64-unknown-linux", 389 "x86_64-apple-macosx", "x86_64-apple-ios14.0", 390 "wasm32-unknown-unknown", "wasm64-unknown-unknown", 391 "thumb-pc-win32", "sparc64-none-openbsd", 392 "sparc-none-none", "riscv64-unknown-linux", 393 "ppc64-windows-msvc", "powerpc-ibm-aix", 394 "powerpc64-ibm-aix", "s390x-ibm-zos", 395 "armv7-pc-windows-msvc", "aarch64-pc-windows-msvc", 396 "xcore-xmos-elf"}) { 397 config.Target = target; 398 all_configs.push_back(config); 399 } 400 return all_configs; 401 } 402 403 INSTANTIATE_TEST_SUITE_P(SValTests, SValTest, 404 testing::ValuesIn(allTestClangConfigs())); 405 406 } // namespace 407 } // namespace ento 408 } // namespace clang 409