Search code examples
ccall-graph

Static analysis for call-graph generation in C programs


I found plenty of programs such as Doxygen or gprof that can do the job using external visualization tools like graphviz.

Unfortunately these programs requires lots of initial configuration where I am only interested to know the call-stack of the functions that use malloc.

The project is huge, hundred of files and somewhere a main function.

My current solution which will take me some time is to write a Perl/Python script that:

  1. Search for malloc\s*(.*?) calls.
  2. Retrieve the name of the parent function
  3. Search where this parent function is called
  4. goto 2

Is there some utilities that can help me in here?

The project is on Microsoft VisualStudio 2010 and generate dlls as an API for an embedded device. The use of external libraries is not very large. We use common libraries such as ftdi or wdapi910


Solution

  • For malloc related bugs, the valgrind tool is very useful (at runtime, when testing).

    Your quest cannot be satisfied by purely textual inspection of source code (e.g. because malloc might be called from many inlined functions or macros, and because it even could be #define-d to something else, or called thru function pointers, or in functions from external libraries: even fopen or fprintf may call malloc). Actually it can be proven equivalent to the halting problem.

    Also, the call stack is only known at runtime, and it is dynamically changing. It has no sense at compile time. The compiler only organize call frames.

    You need a tool which works inside the compiler, on internal representations of the compiler, so you need some more sophisticated static program analyzer, and even that will give you approximate results.

    You could use MELT (a plugin and domain specific language to customize the GCC compiler, that I am developing as free software) since it works on GCC internal representations. The example of findgimple mode in the tutorial about using MELT is quite close to your question, but you could customize GCC with your own MELT extension (or ask someone to do that).

    PS. valgrind & MELT are mostly available on Linux and POSIX systems. You might try hard to find costly equivalents in the Microsoft ecosystem.