Skip to content

Instantly share code, notes, and snippets.

@karthick18
Created May 22, 2013 00:58
Show Gist options
  • Save karthick18/5624484 to your computer and use it in GitHub Desktop.
Save karthick18/5624484 to your computer and use it in GitHub Desktop.
Hook mmap
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#define TRAP_MMAP_LIMIT (4 << 20)
#define DECLARE_HOOK(mmap) \
void *mmap(void *addr, size_t, int, int, int, loff_t) __attribute__((weak,alias("hook_"#mmap)));\
typedef void *(*mmap_ptr_t)(void *, size_t, int, int, int, loff_t);
#define DEFINE_HOOK(mmap) \
void *hook_##mmap(void *addr, size_t length, int prot, int flags, int fd, loff_t offset) { \
printf("Inside %s\n", __FUNCTION__); \
mmap_ptr_t orig_mmap = (mmap_ptr_t)dlsym(RTLD_NEXT, #mmap); \
if(length > TRAP_MMAP_LIMIT) { \
printf("Large mmap\n"); \
} \
return orig_mmap(addr, length, prot, flags, fd, offset); \
}
DECLARE_HOOK(mmap)
DEFINE_HOOK(mmap)
## LD_PRELOAD=$PATH/libhookmmap.so $PROG
CC := gcc
SRCS := hook_mmap.c
OBJS := $(SRCS:%.c=%.o)
TARGETS = libhookmmap.so
DEBUG_FLAGS = -g
CFLAGS = -Wall -fPIC -shared
LD_LIBS = -ldl
all: $(TARGETS)
libhookmmap.so: $(OBJS)
$(CC) -shared -o $@ $^ $(DEBUG_FLAGS) $(LD_LIBS)
%.o:%.c
$(CC) -c $(CFLAGS) -o $@ $<
clean:
rm $(TARGETS); rm $(OBJS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment