1 //== AdjustedReturnValueChecker.cpp -----------------------------*- 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 file defines AdjustedReturnValueChecker, a simple check to see if the
11 // return value of a function call is different than the one the caller thinks
14 //===----------------------------------------------------------------------===//
16 #include "ClangSACheckers.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/BugReporter/BugReporter.h"
22 using namespace clang;
26 class AdjustedReturnValueChecker :
27 public Checker< check::PostStmt<CallExpr> > {
29 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
33 void AdjustedReturnValueChecker::checkPostStmt(const CallExpr *CE,
34 CheckerContext &C) const {
36 // Get the result type of the call.
37 QualType expectedResultTy = CE->getType();
39 // Fetch the signature of the called function.
40 const ProgramState *state = C.getState();
42 SVal V = state->getSVal(CE);
47 // Casting to void? Discard the value.
48 if (expectedResultTy->isVoidType()) {
49 C.generateNode(state->BindExpr(CE, UnknownVal()));
53 const MemRegion *callee = state->getSVal(CE->getCallee()).getAsRegion();
57 QualType actualResultTy;
59 if (const FunctionTextRegion *FT = dyn_cast<FunctionTextRegion>(callee)) {
60 const FunctionDecl *FD = FT->getDecl();
61 actualResultTy = FD->getResultType();
63 else if (const BlockDataRegion *BD = dyn_cast<BlockDataRegion>(callee)) {
64 const BlockTextRegion *BR = BD->getCodeRegion();
65 const BlockPointerType *BT=BR->getLocationType()->getAs<BlockPointerType>();
66 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
67 actualResultTy = FT->getResultType();
71 if (actualResultTy.isNull())
74 // For now, ignore references.
75 if (actualResultTy->getAs<ReferenceType>())
80 if (expectedResultTy != actualResultTy) {
81 // FIXME: Do more checking and actual emit an error. At least performing
82 // the cast avoids some assertion failures elsewhere.
83 SValBuilder &svalBuilder = C.getSValBuilder();
84 V = svalBuilder.evalCast(V, expectedResultTy, actualResultTy);
85 C.generateNode(state->BindExpr(CE, V));
89 void ento::registerAdjustedReturnValueChecker(CheckerManager &mgr) {
90 mgr.registerChecker<AdjustedReturnValueChecker>();