#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
using namespace ento;
enum class OpenVariant {
Open,
OpenAt
};
namespace {
class UnixAPIMisuseChecker : public Checker< check::PreStmt<CallExpr> > {
mutable std::unique_ptr<BugType> BT_open, BT_pthreadOnce;
mutable Optional<uint64_t> Val_O_CREAT;
public:
void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
void CheckOpenAt(CheckerContext &C, const CallExpr *CE) const;
void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
void CheckOpenVariant(CheckerContext &C,
const CallExpr *CE, OpenVariant Variant) const;
void ReportOpenBug(CheckerContext &C,
ProgramStateRef State,
const char *Msg,
SourceRange SR) const;
};
class UnixAPIPortabilityChecker : public Checker< check::PreStmt<CallExpr> > {
public:
void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
private:
mutable std::unique_ptr<BugType> BT_mallocZero;
void CheckCallocZero(CheckerContext &C, const CallExpr *CE) const;
void CheckMallocZero(CheckerContext &C, const CallExpr *CE) const;
void CheckReallocZero(CheckerContext &C, const CallExpr *CE) const;
void CheckReallocfZero(CheckerContext &C, const CallExpr *CE) const;
void CheckAllocaZero(CheckerContext &C, const CallExpr *CE) const;
void CheckAllocaWithAlignZero(CheckerContext &C, const CallExpr *CE) const;
void CheckVallocZero(CheckerContext &C, const CallExpr *CE) const;
bool ReportZeroByteAllocation(CheckerContext &C,
ProgramStateRef falseState,
const Expr *arg,
const char *fn_name) const;
void BasicAllocationCheck(CheckerContext &C,
const CallExpr *CE,
const unsigned numArgs,
const unsigned sizeArg,
const char *fn) const;
};
}
static void LazyInitialize(const CheckerBase *Checker,
std::unique_ptr<BugType> &BT,
const char *name) {
if (BT)
return;
BT.reset(new BugType(Checker, name, categories::UnixAPI));
}
void UnixAPIMisuseChecker::checkPreStmt(const CallExpr *CE,
CheckerContext &C) const {
const FunctionDecl *FD = C.getCalleeDecl(CE);
if (!FD || FD->getKind() != Decl::Function)
return;
const DeclContext *NamespaceCtx = FD->getEnclosingNamespaceContext();
if (isa_and_nonnull<NamespaceDecl>(NamespaceCtx))
return;
StringRef FName = C.getCalleeName(FD);
if (FName.empty())
return;
if (FName == "open")
CheckOpen(C, CE);
else if (FName == "openat")
CheckOpenAt(C, CE);
else if (FName == "pthread_once")
CheckPthreadOnce(C, CE);
}
void UnixAPIMisuseChecker::ReportOpenBug(CheckerContext &C,
ProgramStateRef State,
const char *Msg,
SourceRange SR) const {
ExplodedNode *N = C.generateErrorNode(State);
if (!N)
return;
LazyInitialize(this, BT_open, "Improper use of 'open'");
auto Report = std::make_unique<PathSensitiveBugReport>(*BT_open, Msg, N);
Report->addRange(SR);
C.emitReport(std::move(Report));
}
void UnixAPIMisuseChecker::CheckOpen(CheckerContext &C,
const CallExpr *CE) const {
CheckOpenVariant(C, CE, OpenVariant::Open);
}
void UnixAPIMisuseChecker::CheckOpenAt(CheckerContext &C,
const CallExpr *CE) const {
CheckOpenVariant(C, CE, OpenVariant::OpenAt);
}
void UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext &C,
const CallExpr *CE,
OpenVariant Variant) const {
unsigned int FlagsArgIndex;
const char *VariantName;
switch (Variant) {
case OpenVariant::Open:
FlagsArgIndex = 1;
VariantName = "open";
break;
case OpenVariant::OpenAt:
FlagsArgIndex = 2;
VariantName = "openat";
break;
};
unsigned int MinArgCount = FlagsArgIndex + 1;
unsigned int CreateModeArgIndex = FlagsArgIndex + 1;
unsigned int MaxArgCount = CreateModeArgIndex + 1;
ProgramStateRef state = C.getState();
if (CE->getNumArgs() < MinArgCount) {
return;
} else if (CE->getNumArgs() == MaxArgCount) {
const Expr *Arg = CE->getArg(CreateModeArgIndex);
QualType QT = Arg->getType();
if (!QT->isIntegerType()) {
SmallString<256> SBuf;
llvm::raw_svector_ostream OS(SBuf);
OS << "The " << CreateModeArgIndex + 1
<< llvm::getOrdinalSuffix(CreateModeArgIndex + 1)
<< " argument to '" << VariantName << "' is not an integer";
ReportOpenBug(C, state,
SBuf.c_str(),
Arg->getSourceRange());
return;
}
} else if (CE->getNumArgs() > MaxArgCount) {
SmallString<256> SBuf;
llvm::raw_svector_ostream OS(SBuf);
OS << "Call to '" << VariantName << "' with more than " << MaxArgCount
<< " arguments";
ReportOpenBug(C, state,
SBuf.c_str(),
CE->getArg(MaxArgCount)->getSourceRange());
return;
}
if (!Val_O_CREAT) {
if (C.getASTContext().getTargetInfo().getTriple().getVendor()
== llvm::Triple::Apple)
Val_O_CREAT = 0x0200;
else {
return;
}
}
const Expr *oflagsEx = CE->getArg(FlagsArgIndex);
const SVal V = C.getSVal(oflagsEx);
if (!isa<NonLoc>(V)) {
return;
}
NonLoc oflags = V.castAs<NonLoc>();
NonLoc ocreateFlag = C.getSValBuilder()
.makeIntVal(Val_O_CREAT.value(), oflagsEx->getType())
.castAs<NonLoc>();
SVal maskedFlagsUC = C.getSValBuilder().evalBinOpNN(state, BO_And,
oflags, ocreateFlag,
oflagsEx->getType());
if (maskedFlagsUC.isUnknownOrUndef())
return;
DefinedSVal maskedFlags = maskedFlagsUC.castAs<DefinedSVal>();
ProgramStateRef trueState, falseState;
std::tie(trueState, falseState) = state->assume(maskedFlags);
if (!(trueState && !falseState))
return;
if (CE->getNumArgs() < MaxArgCount) {
SmallString<256> SBuf;
llvm::raw_svector_ostream OS(SBuf);
OS << "Call to '" << VariantName << "' requires a "
<< CreateModeArgIndex + 1
<< llvm::getOrdinalSuffix(CreateModeArgIndex + 1)
<< " argument when the 'O_CREAT' flag is set";
ReportOpenBug(C, trueState,
SBuf.c_str(),
oflagsEx->getSourceRange());
}
}
void UnixAPIMisuseChecker::CheckPthreadOnce(CheckerContext &C,
const CallExpr *CE) const {
if (CE->getNumArgs() < 1)
return;
ProgramStateRef state = C.getState();
const MemRegion *R = C.getSVal(CE->getArg(0)).getAsRegion();
if (!R || !isa<StackSpaceRegion>(R->getMemorySpace()))
return;
ExplodedNode *N = C.generateErrorNode(state);
if (!N)
return;
SmallString<256> S;
llvm::raw_svector_ostream os(S);
os << "Call to 'pthread_once' uses";
if (const VarRegion *VR = dyn_cast<VarRegion>(R))
os << " the local variable '" << VR->getDecl()->getName() << '\'';
else
os << " stack allocated memory";
os << " for the \"control\" value. Using such transient memory for "
"the control value is potentially dangerous.";
if (isa<VarRegion>(R) && isa<StackLocalsSpaceRegion>(R->getMemorySpace()))
os << " Perhaps you intended to declare the variable as 'static'?";
LazyInitialize(this, BT_pthreadOnce, "Improper use of 'pthread_once'");
auto report =
std::make_unique<PathSensitiveBugReport>(*BT_pthreadOnce, os.str(), N);
report->addRange(CE->getArg(0)->getSourceRange());
C.emitReport(std::move(report));
}
static bool IsZeroByteAllocation(ProgramStateRef state,
const SVal argVal,
ProgramStateRef *trueState,
ProgramStateRef *falseState) {
std::tie(*trueState, *falseState) =
state->assume(argVal.castAs<DefinedSVal>());
return (*falseState && !*trueState);
}
bool UnixAPIPortabilityChecker::ReportZeroByteAllocation(
CheckerContext &C,
ProgramStateRef falseState,
const Expr *arg,
const char *fn_name) const {
ExplodedNode *N = C.generateErrorNode(falseState);
if (!N)
return false;
LazyInitialize(this, BT_mallocZero,
"Undefined allocation of 0 bytes (CERT MEM04-C; CWE-131)");
SmallString<256> S;
llvm::raw_svector_ostream os(S);
os << "Call to '" << fn_name << "' has an allocation size of 0 bytes";
auto report =
std::make_unique<PathSensitiveBugReport>(*BT_mallocZero, os.str(), N);
report->addRange(arg->getSourceRange());
bugreporter::trackExpressionValue(N, arg, *report);
C.emitReport(std::move(report));
return true;
}
void UnixAPIPortabilityChecker::BasicAllocationCheck(CheckerContext &C,
const CallExpr *CE,
const unsigned numArgs,
const unsigned sizeArg,
const char *fn) const {
if (CE->getNumArgs() != numArgs)
return;
ProgramStateRef state = C.getState();
ProgramStateRef trueState = nullptr, falseState = nullptr;
const Expr *arg = CE->getArg(sizeArg);
SVal argVal = C.getSVal(arg);
if (argVal.isUnknownOrUndef())
return;
if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
(void) ReportZeroByteAllocation(C, falseState, arg, fn);
return;
}
assert(trueState);
if (trueState != state)
C.addTransition(trueState);
}
void UnixAPIPortabilityChecker::CheckCallocZero(CheckerContext &C,
const CallExpr *CE) const {
unsigned int nArgs = CE->getNumArgs();
if (nArgs != 2)
return;
ProgramStateRef state = C.getState();
ProgramStateRef trueState = nullptr, falseState = nullptr;
unsigned int i;
for (i = 0; i < nArgs; i++) {
const Expr *arg = CE->getArg(i);
SVal argVal = C.getSVal(arg);
if (argVal.isUnknownOrUndef()) {
if (i == 0)
continue;
else
return;
}
if (IsZeroByteAllocation(state, argVal, &trueState, &falseState)) {
if (ReportZeroByteAllocation(C, falseState, arg, "calloc"))
return;
else if (i == 0)
continue;
else
return;
}
}
assert(trueState);
if (trueState != state)
C.addTransition(trueState);
}
void UnixAPIPortabilityChecker::CheckMallocZero(CheckerContext &C,
const CallExpr *CE) const {
BasicAllocationCheck(C, CE, 1, 0, "malloc");
}
void UnixAPIPortabilityChecker::CheckReallocZero(CheckerContext &C,
const CallExpr *CE) const {
BasicAllocationCheck(C, CE, 2, 1, "realloc");
}
void UnixAPIPortabilityChecker::CheckReallocfZero(CheckerContext &C,
const CallExpr *CE) const {
BasicAllocationCheck(C, CE, 2, 1, "reallocf");
}
void UnixAPIPortabilityChecker::CheckAllocaZero(CheckerContext &C,
const CallExpr *CE) const {
BasicAllocationCheck(C, CE, 1, 0, "alloca");
}
void UnixAPIPortabilityChecker::CheckAllocaWithAlignZero(
CheckerContext &C,
const CallExpr *CE) const {
BasicAllocationCheck(C, CE, 2, 0, "__builtin_alloca_with_align");
}
void UnixAPIPortabilityChecker::CheckVallocZero(CheckerContext &C,
const CallExpr *CE) const {
BasicAllocationCheck(C, CE, 1, 0, "valloc");
}
void UnixAPIPortabilityChecker::checkPreStmt(const CallExpr *CE,
CheckerContext &C) const {
const FunctionDecl *FD = C.getCalleeDecl(CE);
if (!FD || FD->getKind() != Decl::Function)
return;
const DeclContext *NamespaceCtx = FD->getEnclosingNamespaceContext();
if (isa_and_nonnull<NamespaceDecl>(NamespaceCtx))
return;
StringRef FName = C.getCalleeName(FD);
if (FName.empty())
return;
if (FName == "calloc")
CheckCallocZero(C, CE);
else if (FName == "malloc")
CheckMallocZero(C, CE);
else if (FName == "realloc")
CheckReallocZero(C, CE);
else if (FName == "reallocf")
CheckReallocfZero(C, CE);
else if (FName == "alloca" || FName == "__builtin_alloca")
CheckAllocaZero(C, CE);
else if (FName == "__builtin_alloca_with_align")
CheckAllocaWithAlignZero(C, CE);
else if (FName == "valloc")
CheckVallocZero(C, CE);
}
#define REGISTER_CHECKER(CHECKERNAME) \
void ento::register##CHECKERNAME(CheckerManager &mgr) { \
mgr.registerChecker<CHECKERNAME>(); \
} \
\
bool ento::shouldRegister##CHECKERNAME(const CheckerManager &mgr) { \
return true; \
}
REGISTER_CHECKER(UnixAPIMisuseChecker)
REGISTER_CHECKER(UnixAPIPortabilityChecker)