1 //===--- UndefinedAssignmentChecker.h ---------------------------*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines UndefinedAssignmentChecker, a builtin check in ExprEngine that
11 // checks for assigning undefined values.
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.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"
21 using namespace clang;
25 class UndefinedAssignmentChecker
26 : public Checker<check::Bind> {
27 mutable std::unique_ptr<BugType> BT;
30 void checkBind(SVal location, SVal val, const Stmt *S,
31 CheckerContext &C) const;
35 void UndefinedAssignmentChecker::checkBind(SVal location, SVal val,
37 CheckerContext &C) const {
41 // Do not report assignments of uninitialized values inside swap functions.
42 // This should allow to swap partially uninitialized structs
44 if (const FunctionDecl *EnclosingFunctionDecl =
45 dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
46 if (C.getCalleeName(EnclosingFunctionDecl) == "swap")
49 ExplodedNode *N = C.generateErrorNode();
54 static const char *const DefaultMsg =
55 "Assigned value is garbage or undefined";
57 BT.reset(new BuiltinBug(this, DefaultMsg));
59 // Generate a report for this bug.
60 llvm::SmallString<128> Str;
61 llvm::raw_svector_ostream OS(Str);
63 const Expr *ex = nullptr;
66 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(StoreE)) {
67 OS << "The expression is an uninitialized value. "
68 "The computed value will also be garbage";
74 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(StoreE)) {
75 if (B->isCompoundAssignmentOp()) {
76 if (C.getSVal(B->getLHS()).isUndef()) {
77 OS << "The left expression of the compound assignment is an "
78 "uninitialized value. The computed value will also be garbage";
88 if (const DeclStmt *DS = dyn_cast<DeclStmt>(StoreE)) {
89 const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
94 dyn_cast<CXXConstructorDecl>(C.getStackFrame()->getDecl())) {
95 if (CD->isImplicit()) {
96 for (auto I : CD->inits()) {
97 if (I->getInit()->IgnoreImpCasts() == StoreE) {
98 OS << "Value assigned to field '" << I->getMember()->getName()
99 << "' in implicit constructor is garbage or undefined";
109 if (OS.str().empty())
112 auto R = llvm::make_unique<BugReport>(*BT, OS.str(), N);
114 R->addRange(ex->getSourceRange());
115 bugreporter::trackNullOrUndefValue(N, ex, *R);
117 C.emitReport(std::move(R));
120 void ento::registerUndefinedAssignmentChecker(CheckerManager &mgr) {
121 mgr.registerChecker<UndefinedAssignmentChecker>();