aboutsummaryrefslogtreecommitdiff
path: root/contrib/llvm-project/clang/lib/StaticAnalyzer/Checkers/TrustReturnsNonnullChecker.cpp
blob: d80559c6a9152247ae0013a36786040beda06880 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//== TrustReturnsNonnullChecker.cpp -- API nullability modeling -*- C++ -*--==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This checker adds nullability-related assumptions to methods annotated with
// returns_nonnull attribute.
//
//===----------------------------------------------------------------------===//

#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"

using namespace clang;
using namespace ento;

namespace {

class TrustReturnsNonnullChecker : public Checker<check::PostCall> {

public:
  TrustReturnsNonnullChecker(ASTContext &Ctx) {}

  void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
    ProgramStateRef State = C.getState();

    if (isNonNullPtr(Call))
      if (auto L = Call.getReturnValue().getAs<Loc>())
        State = State->assume(*L, /*assumption=*/true);

    C.addTransition(State);
  }

private:
  /// \returns Whether the method declaration has the attribute returns_nonnull.
  bool isNonNullPtr(const CallEvent &Call) const {
    QualType ExprRetType = Call.getResultType();
    const Decl *CallDeclaration =  Call.getDecl();
    if (!ExprRetType->isAnyPointerType() || !CallDeclaration)
      return false;

    return CallDeclaration->hasAttr<ReturnsNonNullAttr>();
  }
};

} // namespace

void ento::registerTrustReturnsNonnullChecker(CheckerManager &Mgr) {
  Mgr.registerChecker<TrustReturnsNonnullChecker>(Mgr.getASTContext());
}

bool ento::shouldRegisterTrustReturnsNonnullChecker(const CheckerManager &mgr) {
  return true;
}