问题描述
我试图破解malloc函数以首先调用我的malloc函数,一旦在其中执行了我的malloc函数,我想调用标准的malloc.但是,我得到了递归,因为它只是加载了我定义的malloc.我该如何解决以下代码?
I am trying to hack the malloc function to call my malloc function first.Once my malloc function is executed within that, I want to invoke the standard malloc. But, I am getting a recursion, since it is just loading my defined malloc. How can i fix the below code?
#include <dlfcn.h>
#include "stdio.h"
//#include "stdlib.h"
void *handle;
void *handle_malloc;
int (*loadprg)(void);
void * (*malloc_sysm)(size_t);
void init()
{
handle = dlopen ("/export/home/joshis1/Foxtel/temp/libloadmap.so", RTLD_LAZY);
if( handle == NULL)
{
puts(dlerror());
}
handle_malloc = dlopen ("/lib/libc.so.6", RTLD_LAZY);
if( handle_malloc == NULL)
{
puts("handle malloc error\r\n");
puts(dlerror());
}
}
#include "stdio.h"
void *malloc(int size)
{
printf("called..my malloc\r\n");
malloc_sysm = dlsym(handle_malloc,"malloc");
if ( dlerror() != NULL)
{
puts("malloc symbol not found..");
exit(1);
}
printf("This should call actual malloc now..\r\n");
return malloc_sysm(size);
}
int main()
{
int *t;
init();
printf("call load program now\r\n");
loadprg = dlsym(handle, "loadprg");
if( dlerror()!= NULL)
{
puts("Symbol load errror");
}
(*loadprg)();
printf("Close the handle now..\r\n");
dlclose(handle);
t = (int *) malloc (100);
dlclose(handle_malloc);
return 0;
}
输出递归到我定义的malloc().该如何解决?
The output is recursion to my defined malloc(). how to fix this?
推荐答案
要覆盖共享函数,您需要编译自己的共享库并通过LD_PRELOAD环境变量对其进行预加载.
To override shared functions you need to compile your own shared library and preload it via the LD_PRELOAD environment variable.
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
void *malloc(size_t size) {
printf("called..my malloc\r\n");
void *(*original_malloc)(size_t size);
// Find original malloc function
original_malloc = dlsym(RTLD_NEXT, "malloc");
if ( dlerror() != NULL)
{
puts("malloc symbol not found..");
exit(1);
}
printf("This should call actual malloc now..\r\n");
return (*original_malloc)(size);
}
$ gcc -Wall -fPIC -shared -o mymalloc.so mymalloc.c -ldl
$ LD_PRELOAD=./mymalloc.so ./prog
现在您的程序将使用预加载库中的malloc.
Now your program will use malloc from preloaded library.
这篇关于在库中修改标准函数,然后调用本地库函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!