3

While debugging my program I want to observe changes which the program is making to files and I want debugger to tell me when that happens

I am debugging a program which either creates or modifies certain files (let's say text files). A file can be modified from multiple places in the program and it can be modified a multiple number of times. The sequence of modification is important. I am looking for a way to set a watchpoint on the file just like we set on variables. Basically I want the program to break whenever the file is modified so that I can analyze the file content and observe the program further. Is there a way to achieve this?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Sharad
  • 1,867
  • 14
  • 33
  • Put a breakpoint on a fprintf / write or whatever functions you use to write to files. Or implement a wrapper for these functions and add logging. – dbrank0 Mar 24 '16 at 07:50
  • But that would break at all frprintf. It won't be file specific. I would expect that it break only for specific file I want to observe – Sharad Mar 24 '16 at 08:37
  • Do you need to detect when the file is actually modified (with `write`, `ftruncate`, `WriteFile`, etc.), or whenever a library routine that buffers up data that may be written to the file somewhat later is called (`fprintf`, `fputs`, `fwrite`)? If the latter, and if you're using stdio functions, then putting a watchpoint on some element of the `FILE` structure, though non-portable, may be the easiest way to do this. What operating system are you using? – Mark Plotnick Mar 25 '16 at 20:40

2 Answers2

2

I don't think you're going to be able to do this easily. It's a novel concept, I've never heard of it at least.

Files are not typically things in the "scope" understood and managed by a debugger, so there's no way to tell a debugger to do this. Also, it's not quite how the single-step/debugging model works under the hood either, since files are a pretty high-level concept and breaking relies on stopping execution once it reaches a particular address.

You would need to put conditional breakpoints in all functions that do I/O to the file in question, and somehow come up with a condition to filter out only the file(s) you're interested in.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

Two approaches I can think of:

  • Set a conditional break-point for your read/write functions that will break on your specified file descriptor / file pointer.

  • Write wrappers for the read/write syscalls that logs activity for file descriptor and load it as a shared library using LD_PRELOAD.

rohit89
  • 5,745
  • 2
  • 25
  • 42