Callgraph generation using gcc, egypt & graphviz

In this post, we will see how to use gcc, egypt & graphviz to generate call graphs of any C-based source code / multiple source codes. This technique will be helpful if you are working on legacy code and want to have a view of the code architecture at first.



Among the three tools mentioned above, GCC is generally pre-installed in Linux. So You need to install the other two. 


Follow the following :


1. Download Egypt from here egypt download and then unzip it


~/Downloads$ tar -xzvf egypt-1.10.tar.gz
~/Downloads$ sudo mv egypt-1.10 /opt


go to the egypt directory then install it by these commands


/opt/egypt-1.10$ perl Makefile.PL
/opt/egypt-1.10$ make
/opt/egypt-1.10$ sudo make install


2. then install graphViz by


$sudo apt-get install graphviz


Alright then tools are installed So now let's go to the basics 


In order to generate call graph, you basically need the following steps 


1. compile and generate object files using gcc

2. generate RTL from the object files using gcc

3. generate the call graphs using egypt & graphviz 


RTL means Register transfer Language. It is used to describe the data flow at the register transfer level. It is actually a kind of intermediate representation that is very close to assembly language. 


First of all compile and run a simple C program with an additional file 


$mkdir test
$cd test
$notepadqq hello.h
$notepadqq hello.c
$notepadqq main.c


#include <stdio.h>
#include "hello.h"

void main(int argc, char const *argv[])
{
    printf("I am the Main Function\n");
    hello_world();

}

main.c


#ifndef HELLO_H
#define HELLO_H

void hello_world(void);

#endif  

hello.h


#include <stdio.h>
#include "hello.h"

void hello_world(void)
{
    printf("hello world\n");
}

hello.c 


Now let’s compile using GCC 



$gcc -Wall main.c hello.c -o hello
$./hello


Now generate the RTL expands and run egypt command on the output to get a callgrqaph picture 


$gcc -fdump-rtl-expand main.c hello.c
$egypt main.c.192r.expand hello.c.192r.expand | dot -Grankdir=LR -Tsvg -o hello.svg


now open the svg file and you will see the pictorial call graph of the hello application that you made




0 comments:

Post a Comment

Categories

Pages

Firmware Engineer

My photo
Works on Firmware, Embedded Linux, Smart Metering, RTOS, IoT backend

Contact Form

Name

Email *

Message *

Copyrighted by Hassin. Powered by Blogger.