1//=== FixedAddressChecker.cpp - Fixed address usage checker ----*- C++ -*--===//
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// This files defines FixedAddressChecker, a builtin checker that checks for
10// assignment of a fixed address to a pointer.
11// This check corresponds to CWE-587.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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"
20
21using namespace clang;
22using namespace ento;
23
24namespace {
25class FixedAddressChecker
26 : public Checker< check::PreStmt<BinaryOperator> > {
27 const BugType BT{this, "Use fixed address"};
28
29public:
30 void checkPreStmt(const BinaryOperator *B, CheckerContext &C) const;
31};
32}
33
34void FixedAddressChecker::checkPreStmt(const BinaryOperator *B,
35 CheckerContext &C) const {
36 // Using a fixed address is not portable because that address will probably
37 // not be valid in all environments or platforms.
38
39 if (B->getOpcode() != BO_Assign)
40 return;
41
42 QualType T = B->getType();
43 if (!T->isPointerType())
44 return;
45
46 SVal RV = C.getSVal(S: B->getRHS());
47
48 if (!RV.isConstant() || RV.isZeroConstant())
49 return;
50
51 if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
52 // FIXME: improve grammar in the following strings:
53 constexpr llvm::StringLiteral Msg =
54 "Using a fixed address is not portable because that address will "
55 "probably not be valid in all environments or platforms.";
56 auto R = std::make_unique<PathSensitiveBugReport>(args: BT, args: Msg, args&: N);
57 R->addRange(R: B->getRHS()->getSourceRange());
58 C.emitReport(R: std::move(R));
59 }
60}
61
62void ento::registerFixedAddressChecker(CheckerManager &mgr) {
63 mgr.registerChecker<FixedAddressChecker>();
64}
65
66bool ento::shouldRegisterFixedAddressChecker(const CheckerManager &mgr) {
67 return true;
68}
69