| 1 | #define _GNU_SOURCE |
| 2 | #include <dlfcn.h> |
| 3 | #include <stdlib.h> |
| 4 | #include <stdio.h> |
| 5 | #include <sys/syscall.h> |
| 6 | #include <linux/limits.h> |
| 7 | |
| 8 | |
| 9 | static const char *fd_to_path(int fd) { |
| 10 | static char path[PATH_MAX]; |
| 11 | sprintf(path,"/proc/self/fd/%d",fd); |
| 12 | int l = (int) readlink((char * __restrict__) path, path, PATH_MAX); |
| 13 | path[l]=0; |
| 14 | return path; |
| 15 | } |
| 16 | |
| 17 | int at_close() { |
| 18 | unsetenv("LD_PRELOAD"); |
| 19 | return system(getenv("AT_CLOSE")); |
| 20 | /* |
| 21 | static const char *command; |
| 22 | if(!command) { |
| 23 | command = getenv("AT_CLOSE"); |
| 24 | unsetenv("LD_PRELOAD"); |
| 25 | } |
| 26 | fprintf(stderr,"%s\n",command); |
| 27 | system(command); |
| 28 | return 0; |
| 29 | */ |
| 30 | } |
| 31 | |
| 32 | int close(int fd) { |
| 33 | //fprintf(stderr,"%s(%d,%s);\n",__func__,fd,fd_to_path(fd)); |
| 34 | static int (*close_orig)(int fd); |
| 35 | if (!close_orig) { |
| 36 | close_orig = dlsym(RTLD_NEXT, "close"); |
| 37 | } |
| 38 | int ret = close_orig(fd); |
| 39 | //int ret = syscall(SYS_close,fd); |
| 40 | at_close(); |
| 41 | return ret; |
| 42 | } |
| 43 | int fclose(FILE *fd) { |
| 44 | //fprintf(stderr,"%s(%d,%d,%s);\n",__func__,fileno(fd),fd,fd_to_path(fileno(fd))); |
| 45 | static int (*fclose_orig)(FILE *fd); |
| 46 | if (!fclose_orig) { |
| 47 | fclose_orig = dlsym(RTLD_NEXT, "fclose"); |
| 48 | } |
| 49 | int ret = fclose_orig(fd); |
| 50 | at_close(); |
| 51 | return ret; |
| 52 | } |