Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic tracing of program execution [closed]

Tags:

c++

c

trace

I would like to know if we can enable tracing in any C or C++ application.

For example, with a gcc option or a small tool, I will enable trace and either trace is printed on console or dumped to a file.

Since there are lots of files and function / classes, I don't want to start adding the trace prints manually.

If such tools are not available, next choice is use scripting and try to add at the trace printing.

strace is not much useful as it gives mainly the system calls.

like image 547
hari Avatar asked Apr 28 '11 10:04

hari


People also ask

What is program execution trace?

Tracing collects information about what is happening in your program and displays it. If a program arrives at a breakpoint created with a trace command, the program halts and an event-specific trace information line is emitted, then the program continues.

How do I trace a program in C++?

To define tracing functions in C++ programs, use the extern "C" linkage directive before your function definition. The function calls are only inserted into the function definition, and if a function is inlined, no tracing is done within the inlined code.


2 Answers

To trace the function entry/exit, you can recompile your code with the option -finstrument-functions so that each time a function is invoked, a __cyg_profile_func_enter() function is called, and __cyg_profile_func_exit() is called when the function returns.

You can implement those functions to trace the addresses on the called functions, and them use nm to convert the addresses into function names.

EDIT: etrace does all this: it provides the source code for the __cyg_profile_func_enter() and __cyg_profile_func_exit() and functions that write the addresses to a named pipe and a Perl and a Python script to read the addresses and do the actual tracing with the function names and indentation.

like image 126
philant Avatar answered Oct 13 '22 09:10

philant


For GCC, you could build with profiling support, and then run the program. That will create the gmon.out file, which in turn will contain a (sort of) trace of the functions executed by the program.

That will not even come close to the utility or ease of use of hand-written trace printf()s, though.

like image 41
unwind Avatar answered Oct 13 '22 09:10

unwind