414 lines · cpp
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-exception6//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 32namespace clang {33 34// getType() tests include whole bunch of type comparisons,35// so when something is wrong, it's good to have gtest telling us36// what are those types.37[[maybe_unused]] std::ostream &operator<<(std::ostream &OS, const QualType &T) {38 return OS << T.getAsString();39}40 41[[maybe_unused]] std::ostream &operator<<(std::ostream &OS,42 const CanQualType &T) {43 return OS << QualType{T};44}45 46namespace ento {47namespace {48 49//===----------------------------------------------------------------------===//50// Testing framework implementation51//===----------------------------------------------------------------------===//52 53/// A simple map from variable names to symbolic values used to init them.54using SVals = llvm::StringMap<SVal>;55 56/// SValCollector is the barebone of all tests.57///58/// It is implemented as a checker and reacts to binds, so we find59/// symbolic values of interest, and to end analysis, where we actually60/// can test whatever we gathered.61class SValCollector : public Checker<check::Bind, check::EndAnalysis> {62public:63 void checkBind(SVal Loc, SVal Val, const Stmt *S, bool AtDeclInit,64 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 87private: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 95static 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 SValTest103class SValTest : public testing::TestWithParam<TestClangConfig> {};104 105// SVAL_TEST is a combined way of providing a short code snippet and106// to test some programmatic predicates on symbolic values produced by the107// 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 any112// valid C/C++, but have ONLY ONE defined function. There are no requirements113// about function's name or parameters. It can even be a class method. The114// body of the function must contain a set of variable declarations. Each115// variable declaration gets bound to a symbolic value, so for the following116// 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 "SValColl", true}}; \143 AnalysisConsumer.AddCheckerRegistrationFn([](CheckerRegistry &Registry) { \144 Registry.addChecker<NAME##SValCollector>("test." #NAME "SValColl", \145 "MockDescription"); \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) const155 156//===----------------------------------------------------------------------===//157// Actual tests158//===----------------------------------------------------------------------===//159 160SVAL_TEST(GetConstType, R"(161void 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 180SVAL_TEST(GetLocAsIntType, R"(181void 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 long190 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 202SVAL_TEST(GetSymExprType, R"(203void 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 casts219 SVal Z = getByName("z");220 ASSERT_FALSE(Z.getType(Context).isNull());221 EXPECT_EQ(Int, Z.getType(Context));222}223 224SVAL_TEST(GetPointerType, R"(225int *bar();226int &foobar();227struct Z {228 int a;229 int *b;230};231void 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 278SVAL_TEST(GetCompoundType, R"(279struct TestStruct {280 int a, b;281};282union TestUnion {283 int a;284 float b;285 TestStruct c;286};287void 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 *DRecordType = dyn_cast<RecordType>(LDT);323 ASSERT_NE(DRecordType, nullptr);324 EXPECT_EQ("TestStruct", DRecordType->getDecl()->getName());325}326 327SVAL_TEST(GetStringType, R"(328void foo() {329 const char *a = "Hello, world!";330}331)") {332 SVal A = getByName("a");333 ASSERT_FALSE(A.getType(Context).isNull());334 const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context));335 ASSERT_NE(APtrTy, nullptr);336 EXPECT_EQ(Context.CharTy, APtrTy->getPointeeType());337}338 339SVAL_TEST(GetThisType, R"(340class TestClass {341 void foo();342};343void TestClass::foo() {344 const auto *a = this;345}346)") {347 SVal A = getByName("a");348 ASSERT_FALSE(A.getType(Context).isNull());349 const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context));350 ASSERT_NE(APtrTy, nullptr);351 const auto *ARecordType = dyn_cast<RecordType>(APtrTy->getPointeeType());352 ASSERT_NE(ARecordType, nullptr);353 EXPECT_EQ("TestClass", ARecordType->getDecl()->getName());354}355 356SVAL_TEST(GetFunctionPtrType, R"(357void bar();358void foo() {359 auto *a = &bar;360}361)") {362 SVal A = getByName("a");363 ASSERT_FALSE(A.getType(Context).isNull());364 const auto *APtrTy = dyn_cast<PointerType>(A.getType(Context));365 ASSERT_NE(APtrTy, nullptr);366 ASSERT_TRUE(isa<FunctionProtoType>(APtrTy->getPointeeType()));367}368 369SVAL_TEST(GetLabelType, R"(370void foo() {371 entry:372 void *a = &&entry;373 char *b = (char *)&&entry;374}375)") {376 SVal A = getByName("a");377 ASSERT_FALSE(A.getType(Context).isNull());378 EXPECT_EQ(Context.VoidPtrTy, A.getType(Context));379 380 SVal B = getByName("a");381 ASSERT_FALSE(B.getType(Context).isNull());382 // TODO: Change to CharTy when we support symbolic casts383 EXPECT_EQ(Context.VoidPtrTy, B.getType(Context));384}385 386std::vector<TestClangConfig> allTestClangConfigs() {387 std::vector<TestClangConfig> all_configs;388 TestClangConfig config;389 config.Language = Lang_CXX14;390 for (std::string target :391 {"i686-pc-windows-msvc", "i686-apple-darwin9",392 "x86_64-apple-darwin9", "x86_64-scei-ps4",393 "x86_64-windows-msvc", "x86_64-unknown-linux",394 "x86_64-apple-macosx", "x86_64-apple-ios14.0",395 "wasm32-unknown-unknown", "wasm64-unknown-unknown",396 "thumb-pc-win32", "sparc64-none-openbsd",397 "sparc-none-none", "riscv64-unknown-linux",398 "ppc64-windows-msvc", "powerpc-ibm-aix",399 "powerpc64-ibm-aix", "s390x-ibm-zos",400 "armv7-pc-windows-msvc", "aarch64-pc-windows-msvc",401 "xcore-xmos-elf"}) {402 config.Target = target;403 all_configs.push_back(config);404 }405 return all_configs;406}407 408INSTANTIATE_TEST_SUITE_P(SValTests, SValTest,409 testing::ValuesIn(allTestClangConfigs()));410 411} // namespace412} // namespace ento413} // namespace clang414