Reputation: 734
I want to trace a C program under Linux, and record all function calls and returns in a format of tree. For example, the source code:
void a ()
{
printf("a\n");
}
void b ()
{
printf("b\n");
}
void c ()
{
a();
b();
}
int main()
{
a();
b();
c();
}
And I want a output like the following:
call main
call a
exit a
call b
exit b
call c
call a
exit a
call b
exit b
exit c
exit main
It is a idealistic output. I just want to get all the process of local function calls and returns, so the similar output is also welcome.
Upvotes: 4
Views: 1345
Reputation: 48
Use cflow would be a good choice as well. The information of cflow could be found in gnu website, https://www.gnu.org/software/cflow/
Below is an example of cflow,
$ cflow foo.c cl.12.*.c
main() <int main (void) at foo.c:18>:
foo_trivial_questions() <void foo_trivial_questions (void) at foo.c:13>:
foo_cl_12_test() <void foo_cl_12_test (void) at cl.12.IntegertoRoman.c:32>:
foo() <void foo (int n) at cl.12.IntegertoRoman.c:24>:
intToRoman() <char *intToRoman (int num) at cl.12.IntegertoRoman.c:3>:
malloc()
strcat()
printf()
free()
Upvotes: 0
Reputation: 3496
To produce such an output by modifying code, try something like this (not optimized but does the job):
size_t indent;
#define ENTER_FUNC(function_name) \
indent++; \
for(size_t i=0; i<indent; i++) printf("\t"); \
printf("Call %s\n", function_name);
#define EXIT_FUNC(function_name) \
for(size_t i=0; i<indent; i++) printf("\t"); \
printf("Exit %s\n", function_name); \
indent--;
Call ENTER_FUNC
at the beginning of each function to trace and EXIT_FUNC
prior to any return
.
You can also enrich the macro to write in a log file.
Otherwise there are some profiling tools like gprof for example
Upvotes: 0