#include "clang/AST/Attr.h"
#include "clang/Analysis/AnyCall.h"
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.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/CallDescription.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
using namespace clang;
using namespace ento;
namespace {
class MIGChecker : public Checker<check::PostCall, check::PreStmt<ReturnStmt>,
check::EndFunction> {
BugType BT{this, "Use-after-free (MIG calling convention violation)",
categories::MemoryError};
std::vector<std::pair<CallDescription, unsigned>> Deallocators = {
#define CALL(required_args, deallocated_arg, ...) \
{{{__VA_ARGS__}, required_args}, deallocated_arg}
CALL(3, 1, "vm_deallocate"),
CALL(3, 1, "mach_vm_deallocate"),
CALL(2, 0, "mig_deallocate"),
CALL(2, 1, "mach_port_deallocate"),
CALL(1, 0, "device_deallocate"),
CALL(1, 0, "iokit_remove_connect_reference"),
CALL(1, 0, "iokit_remove_reference"),
CALL(1, 0, "iokit_release_port"),
CALL(1, 0, "ipc_port_release"),
CALL(1, 0, "ipc_port_release_sonce"),
CALL(1, 0, "ipc_voucher_attr_control_release"),
CALL(1, 0, "ipc_voucher_release"),
CALL(1, 0, "lock_set_dereference"),
CALL(1, 0, "memory_object_control_deallocate"),
CALL(1, 0, "pset_deallocate"),
CALL(1, 0, "semaphore_dereference"),
CALL(1, 0, "space_deallocate"),
CALL(1, 0, "space_inspect_deallocate"),
CALL(1, 0, "task_deallocate"),
CALL(1, 0, "task_inspect_deallocate"),
CALL(1, 0, "task_name_deallocate"),
CALL(1, 0, "thread_deallocate"),
CALL(1, 0, "thread_inspect_deallocate"),
CALL(1, 0, "upl_deallocate"),
CALL(1, 0, "vm_map_deallocate"),
CALL(1, 0, "IOUserClient", "releaseAsyncReference64"),
CALL(1, 0, "IOUserClient", "releaseNotificationPort"),
#undef CALL
};
CallDescription OsRefRetain{"os_ref_retain", 1};
void checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const;
public:
void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const {
checkReturnAux(RS, C);
}
void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const {
checkReturnAux(RS, C);
}
};
}
REGISTER_TRAIT_WITH_PROGRAMSTATE(ReleasedParameter, bool)
REGISTER_SET_WITH_PROGRAMSTATE(RefCountedParameters, const ParmVarDecl *)
static const ParmVarDecl *getOriginParam(SVal V, CheckerContext &C,
bool IncludeBaseRegions = false) {
SymbolRef Sym = V.getAsSymbol(IncludeBaseRegions);
if (!Sym)
return nullptr;
while (const MemRegion *MR = Sym->getOriginRegion()) {
const auto *VR = dyn_cast<VarRegion>(MR);
if (VR && VR->hasStackParametersStorage() &&
VR->getStackFrame()->inTopFrame())
return cast<ParmVarDecl>(VR->getDecl());
const SymbolicRegion *SR = MR->getSymbolicBase();
if (!SR)
return nullptr;
Sym = SR->getSymbol();
}
return nullptr;
}
static bool isInMIGCall(CheckerContext &C) {
const LocationContext *LC = C.getLocationContext();
assert(LC && "Unknown location context");
const StackFrameContext *SFC;
while (LC) {
SFC = LC->getStackFrame();
LC = SFC->getParent();
}
const Decl *D = SFC->getDecl();
if (Optional<AnyCall> AC = AnyCall::forDecl(D)) {
if (!AC->getReturnType(C.getASTContext())
.getCanonicalType()->isSignedIntegerType())
return false;
}
if (D->hasAttr<MIGServerRoutineAttr>())
return true;
if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
for (const auto *OMD: MD->overridden_methods())
if (OMD->hasAttr<MIGServerRoutineAttr>())
return true;
return false;
}
void MIGChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const {
if (OsRefRetain.matches(Call)) {
if (const ParmVarDecl *PVD =
getOriginParam(Call.getArgSVal(0), C, true)) {
C.addTransition(C.getState()->add<RefCountedParameters>(PVD));
}
return;
}
if (!isInMIGCall(C))
return;
auto I = llvm::find_if(Deallocators,
[&](const std::pair<CallDescription, unsigned> &Item) {
return Item.first.matches(Call);
});
if (I == Deallocators.end())
return;
ProgramStateRef State = C.getState();
unsigned ArgIdx = I->second;
SVal Arg = Call.getArgSVal(ArgIdx);
const ParmVarDecl *PVD = getOriginParam(Arg, C);
if (!PVD || State->contains<RefCountedParameters>(PVD))
return;
const NoteTag *T =
C.getNoteTag([this, PVD](PathSensitiveBugReport &BR) -> std::string {
if (&BR.getBugType() != &BT)
return "";
SmallString<64> Str;
llvm::raw_svector_ostream OS(Str);
OS << "Value passed through parameter '" << PVD->getName()
<< "\' is deallocated";
return std::string(OS.str());
});
C.addTransition(State->set<ReleasedParameter>(true), T);
}
static bool mayBeSuccess(SVal V, CheckerContext &C) {
ProgramStateRef State = C.getState();
if (!State->isNull(V).isConstrainedFalse())
return true;
SValBuilder &SVB = C.getSValBuilder();
ASTContext &ACtx = C.getASTContext();
static const int MigNoReply = -305;
V = SVB.evalEQ(C.getState(), V, SVB.makeIntVal(MigNoReply, ACtx.IntTy));
if (!State->isNull(V).isConstrainedTrue())
return true;
return false;
}
void MIGChecker::checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const {
if (!C.inTopFrame())
return;
if (!isInMIGCall(C))
return;
if (!RS)
return;
ProgramStateRef State = C.getState();
if (!State->get<ReleasedParameter>())
return;
SVal V = C.getSVal(RS);
if (mayBeSuccess(V, C))
return;
ExplodedNode *N = C.generateErrorNode();
if (!N)
return;
auto R = std::make_unique<PathSensitiveBugReport>(
BT,
"MIG callback fails with error after deallocating argument value. "
"This is a use-after-free vulnerability because the caller will try to "
"deallocate it again",
N);
R->addRange(RS->getSourceRange());
bugreporter::trackExpressionValue(
N, RS->getRetValue(), *R,
{bugreporter::TrackingKind::Thorough, false});
C.emitReport(std::move(R));
}
void ento::registerMIGChecker(CheckerManager &Mgr) {
Mgr.registerChecker<MIGChecker>();
}
bool ento::shouldRegisterMIGChecker(const CheckerManager &mgr) {
return true;
}