Skip to content

Instantly share code, notes, and snippets.

@iamben
Created November 21, 2012 13:25
Show Gist options
  • Save iamben/4124829 to your computer and use it in GitHub Desktop.
Save iamben/4124829 to your computer and use it in GitHub Desktop.
dynamic library interposition
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
void* malloc(size_t size)
{
static void* (*rmalloc)(size_t) = NULL;
void* p = NULL;
// resolve next malloc
if(!rmalloc) rmalloc = dlsym(RTLD_NEXT, "malloc");
// do actual malloc
p = rmalloc(size);
// show statistic
fprintf(stderr, "[MEM | malloc] Allocated: %lu bytes\n", size);
return p;
}
libint.so: libint.c
clang -shared -fPIC libint.c -o libint.so
str: str.c
clang -o str str.c
clean:
rm -f str libint.so
run: str libint.so
@echo "========= direct exec ========="
@./str
@echo
@echo "========= With lib interposition ========="
@LD_PRELOAD=./libint.so ./str
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STR_LEN 128
int main(int argc, const char *argv[])
{
char *c;
char *str1 = "Hello ";
char *str2 = "World";
//allocate an empty string
c = malloc(STR_LEN * sizeof(char));
c[0] = 0x0;
//and concatenate str{1,2}
strcat(c, str1);
strcat(c, str2);
printf("New str: %s\n", c);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment