Generating a Call Graph for C Code to Visualize Execution Paths
To generate a calling graph for C code, we aim to uncover all potential execution paths that lead to a specific target function. This can be beneficial in eliminating the manual identification of every path, especially when multiple paths exist.
In the provided example, the target function is D. To achieve this, we can use the following steps:
static void D() {} static void Y() { D(); } static void X() { Y(); } static void C() { D(); X(); } static void B() { C(); } static void S() { D(); } static void P() { S(); } static void O() { P(); } static void N() { O(); } static void M() { N(); } static void G() { M(); } static void A() { B(); G(); } int main() { A(); }
Once we have our code, we can generate the call graph using the following commands:
$ clang++ -S -emit-llvm main1.cpp -o - | opt -analyze -dot-callgraph $ dot -Tpng -ocallgraph.png callgraph.dot
This will produce a visual representation of the call graph.
However, to obtain the actual function names rather than their mangled counterparts, we can postprocess the graph using c filt:
#include <vector> struct A { A(int); void f(); // not defined, prevents inlining it! }; int main() { std::vector<A> v; v.push_back(42); v[0].f(); } $ clang++ -S -emit-llvm main1.cpp -o - | opt -analyze -std-link-opts -dot-callgraph $ cat callgraph.dot | c++filt | sed 's,>,\>,g; s,-\>,->,g; s,<,\<,g' | gawk '/external node/{id=} != id' | dot -Tpng -ocallgraph.png
This will yield a more informative call graph, showing the actual names of the functions and classes involved.
The above is the detailed content of How can I generate a call graph for C code to visualize execution paths?. For more information, please follow other related articles on the PHP Chinese website!