Question

I have the source code of a program. The source code is extremely huge and written in C/C++. I have the credentials to modify the source code, compile and execute it.

I want to know the filenames of all the files opened and closed by this program when it executes. It would be a plus if this list is sorted in the order the file operations occurred.

How can I get this information? Is there some monitoring tool I need to use or can I inject a library call into the C++ code to achieve this? The code is too large and complicated to hunt down every file open/close call and add a printf there. Or adding a pseudo macro to the file open API call might also be difficult.

Note that this is not the same as viewing what files are open currently by a process. I am aware of the many questions on StackOverflow that already address this problem (using lsof or /proc and so on).

Was it helpful?

Solution

You can use strace as below

$ strace -e trace=open,close -o /tmp/trace.log <your_program> <program_options>

In file /tmp/trace.log you will get all open, close operation done by the program.

OTHER TIPS

In addition to strace, you can use interposition to intercept open/close syscalls. If you Google for "interposition shared library linux" you'll get many other references also.

I am understanding that you want to determine statically what files a given source code could open (for many runs of its compiled program).

If you just want to know it dynamically for a given run, use strace(1) as answered by Rohan and/or interposition library as answered by Kec. Notice that ltrace(1) could also be useful, and perhaps more relevant (since you would trace stdio or C++ library calls).


First, a program can (and many do) open a file whose name is some input (or some program argument). Then you cannot add that arbitrary file name to a list.

You could #define fopen and #define open to print a message. You could use LD_PRELOAD tricks to override open, fopen

If in C++, the program may open files using std::ifstream etc...

You could consider customizing the GCC compiler with MELT to help you...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top