How to write automated AST inspection rules in Clang tooling:
To detect calls to malloc without null checks across millions of lines of code:
StatementMatcher MallocMatcher = callExpr(
callee(functionDecl(hasName("malloc"))),
unless(hasAncestor(ifStmt()))
).bind("unverifiedMalloc");
class MallocCallback : public MatchFinder::MatchCallback {
void run(const MatchFinder::MatchResult& result) override {
const auto* call = result.Nodes.getNodeAs<CallExpr>("unverifiedMalloc");
Diagnostics.Report(call->getBeginLoc(), DiagnosticID);
}
};