0

I am trying to use LD_PRELOAD to intercept calls to open/close. My test implementation of close() is just

int close(int fd) {
  fprintf(stderr, "TEST\n");
  return syscall(SYS_close, fd);
}

and I have a test program that does

int handle=open("test.txt", O_WRONLY|O_CREAT, 0644);
close(handle);
FILE *f = fopen("test.txt", "w");
fclose(f);

The problem is: my LD_PRELOAD code successfully intercepted the close() call, but could not intercept the close() syscall made from fclose(), although from strace output the two syscall's look exactly the same.

I know I can just write my interception of fclose(), and it also worked for C++'s ofstream::close(). However, my interceptions for open()/fopen() still don't work for C++'s ofstream::ofstream(). How can I make sure I intercept all calls to open or close a file, no matter which wrapper function calls them? Thanks!

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
  • Welcome to Stack Overflow! Could you describe how you are building and deploying your test? Or provide a link to instructions that you are following? – Robᵩ Jan 14 '13 at 20:30
  • 3
    Have you tried setting a break point on `fclose` in gdb and stepping through it? Maybe it's invoking `syscall(SYS_close...`, either directly or because `close` is inlined. – eduffy Jan 14 '13 at 20:39
  • My build is just like `gcc -Wall -fPIC -shared -o libtest.so test.c -ldl` and `g++ -o testmain testmain.C`, and my run is just like `LD_PRELOAD=./libtest.so ./testmain`. Thanks. – user1978373 Jan 14 '13 at 20:47
  • I could not step through `fclose` in my gdb as gdb simply steps over this call. Also, I have no problem writing my own interceptions of `fopen` and `fclose` as well as `open` and `close`, but for some reason they don't work for `ofstream::ofstream`, and I am not sure what more I need to intercept. Thanks. – user1978373 Jan 14 '13 at 20:50
  • Try setting LD_DEBUG=all and run your program. You might need a glibc-debug package to be able to step into fclose in gdb. – ggiroux Jan 14 '13 at 20:58
  • Thanks! I tried that. It seems that `ofstream::ofstream` calls `fopen64` instead of `fopen`. I intercepted that and now I see my interceptor works. So I guess I need to intercept all the following: `open`, `open64`, `creat`, `creat64`, `fopen`, `fopen64`, `fdopen`, `fdopen64` in order to get all the calls to open files? – user1978373 Jan 14 '13 at 21:05
  • Also beware compiler optimizations. Once I tried interposing `printf()`, but gcc optimized `printf("constant string\n")` into `puts("constant string")`, so it "obviously" didn't work... –  Dec 23 '13 at 23:19

0 Answers0