Wednesday, October 23, 2013

Print control flow of c/c++ program using gdb


How to use gdb for inspecting control flow in a c/c++ programs.

            For inspecting the control flow, simply put break points on all functions of that particular process. If more functions are then, then it will be frustrating task to put break points one by one. so we automate the task of putting break points.

Step 1: Collect the function names from object file generated as a result of compilation. While compiling c/c++ program use -c option in gcc/g++ for creating only object file(s).

                            gcc -c sample.c
                                     or
                            g++ -c sample.cpp

Step 2: Run the following shell script

     nm -P sample.o | awk '$2 == "T" && $1 != "main" 
     {
         print "# code for " $NF; 
         print "b " $1; 
         print "commands"; 
         print "silent"; 
         print "bt 1"; 
         print "c"; 
         print "end"; 
         print "";        
     }' 
     &> function_names

a file(function_names) with all function names(except main()) and gdb commands will be created. 

If you wish to put breakpoint in main() also, then use following command.

  nm -P sample.o | awk '$2 == "T" 
     {
         print "# code for " $NF; 
         print "b " $1; 
         print "commands"; 
         print "silent"; 
         print "bt 1"; 
         print "c"; 
         print "end"; 
         print "";        
     }' 
     &> function_names 

Step 3: Start the GDB session and pass the commands file generated from that scipt as argument.

              gdb --command=function_names a.out 

          now gdb will show that all functions in that executable is set with breakpoints.

Step 4: In gdb prompt, give run to exceute the program. Whenever a function is called, it will be displayed with arguments.

More Reference.

No comments:

Post a Comment