Skip to content

[analyzer] EnumCastOutOfRangeChecker: report the value #74503

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "llvm/Support/FormatVariadic.h"
#include <optional>

using namespace clang;
using namespace ento;
using llvm::formatv;

namespace {
// This evaluator checks two SVals for equality. The first SVal is provided via
Expand Down Expand Up @@ -87,17 +89,22 @@ void EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C,
EnumValueCastOutOfRange.reset(
new BugType(this, "Enum cast out of range"));

llvm::SmallString<128> Msg{"The value provided to the cast expression is "
"not in the valid range of values for "};
StringRef EnumName{E->getName()};
if (EnumName.empty()) {
Msg += "the enum";
} else {
Msg += '\'';
Msg += EnumName;
Msg += '\'';
std::string ValueStr = "", NameStr = "the enum";

// Try to add details to the message:
const auto ConcreteValue =
C.getSVal(CE->getSubExpr()).getAs<nonloc::ConcreteInt>();
if (ConcreteValue) {
ValueStr = formatv(" '{0}'", ConcreteValue->getValue());
}
if (StringRef EnumName{E->getName()}; !EnumName.empty()) {
NameStr = formatv("'{0}'", EnumName);
}

std::string Msg = formatv("The value{0} provided to the cast expression is "
"not in the valid range of values for {1}",
ValueStr, NameStr);

auto BR = std::make_unique<PathSensitiveBugReport>(*EnumValueCastOutOfRange,
Msg, N);
bugreporter::trackExpressionValue(N, CE->getSubExpr(), *BR);
Expand Down
Loading