Skip to content

Instantly share code, notes, and snippets.

@vifon
Created August 20, 2012 20:07
Show Gist options
  • Save vifon/3407391 to your computer and use it in GitHub Desktop.
Save vifon/3407391 to your computer and use it in GitHub Desktop.
File Access Monitor
#!/bin/sh
PROGRAM="$1"
shift
LD_PRELOAD="$HOME/local/lib/accessmonitor.so" exec "$PROGRAM" "$@"
#define _GNU_SOURCE 1
#include <dlfcn.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <fcntl.h>
FILE* fopen(const char* path, const char* mode)
{
FILE* (*orig)(const char*, const char*) = dlsym(RTLD_NEXT, "fopen");
fprintf(stderr, "%-70s %s\n", path, mode);
return orig(path, mode);
}
int open(const char* filename, int flags, ...)
{
int (*orig)(const char*, int, ...) = (int(*)(const char*, int, ...))dlsym(RTLD_NEXT, "open");
if (flags & O_CREAT) {
va_list ap;
int mode;
va_start(ap, flags);
mode = va_arg(ap, mode_t);
va_end(ap);
if (strcmp(filename, ".")) {
fprintf(stderr, "%-70s %4d %4d\n", filename, flags, mode);
}
return orig(filename, flags, mode);
} else {
if (strcmp(filename, ".")) {
fprintf(stderr, "%-70s %4d\n", filename, flags);
}
return orig(filename, flags);
}
}
int open64(const char* filename, int flags, ...)
{
int (*orig)(const char*, int, ...) = (int(*)(const char*, int, ...))dlsym(RTLD_NEXT, "open64");
if (flags & O_CREAT) {
va_list ap;
int mode;
va_start(ap, flags);
mode = va_arg(ap, mode_t);
va_end(ap);
if (strcmp(filename, ".")) {
fprintf(stderr, "%-70s %4d %4d\n", filename, flags, mode);
}
return orig(filename, flags, mode);
} else {
if (strcmp(filename, ".")) {
fprintf(stderr, "%-70s %4d\n", filename, flags);
}
return orig(filename, flags);
}
}
CFLAGS=-O2 -Wall -Wextra
.PHONY: all
all: accessmonitor.so
accessmonitor.so: accessmonitor.c
$(CC) $(CFLAGS) -fPIC -shared -ldl $< -o $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment