Finding all instances of calls to a specific function using ASTMatcher

Hi All,

I want to find all the instances of calls to a specific function. Right now, I can find all the function calls using ASTMatcher using following code:

Finder.addMatcher(
callExpr(hasParent(binaryOperator(hasOperatorName("=")).bind("assignment"))).bind("functionCall"),
       &HandlerForFunctionCall);

But I want to find all the function calls whose name is say "malloc". I know how do that using classic "RecursiveASTVisitor" class, but how can I do this using ASTMatcher?

Thanks
Riyad

Use clang-query to try things out, you’ll need to generate compilation database to use it but that shouldn’t be too hard. It sure beats having to recompile your code to test it.

The matcher you’re after is probably callExpr(callee(functionDecl(hasName(“malloc”))))

Use clang-query to try things out, you’ll need to generate compilation database to use it but that shouldn’t be too hard. It sure beats having to recompile your code to test it.

The matcher you’re after is probably callExpr(callee(functionDecl(hasName(“malloc”))))

Hi Nikola,

I had a related question. Can I run such a matcher on a whole program? I am currently using the CSA framework but running into some issues and I think using the matchers suit my task better.

Thanks for your reply!
Saheel.

I’m not an expert on this but I think that’s what you get by generating a compilation database for your project and feeding it to your tool.

Hi,

I’ve tried your query and getting segmentation fault. I’ve tried to get backtrace from gdb, but for some reason gdb is printing garbage. Thanks Riyad

The only thing I can suggest is to use clang-query and start from the most basic matcher, say functionDecl, then gradually constrain it using hasName, etc. See at what point you get the crash. Reducing your input source might also help, if this is a Clang bug you’ll have a minimal repro case. I’ve only tried my query on a super simple file.