【发布时间】:2015-10-04 23:36:03
【问题描述】:
我的代码适用于malloc,但不适用于mmap。代码如下:
main.c
#include <stdio.h>
#include <stdlib.h>
int main(){
int * p = (int*) malloc(sizeof(int));
printf("in main(): value p = %d\n", *p);
free(p);
}
preload.c
#define _GNU_SOURCE
#include <time.h>
#include <dlfcn.h>
#include <stdio.h>
#include <sys/types.h>
void *(*orig_malloc)(size_t size);
void *malloc(size_t size){
printf(" Hooked(preload)! malloc:size:%lu\n", size);
return orig_malloc(size);
}
void * (*orig_mmap)(void *start, size_t length, int prot, int flags, int fd, off_t offset);
void * mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset){
printf(" Hooked(preload)! mmap:start:%p, length:%lu, prot:%d, flags:%p, fd:%p, offset:%d\n", start, length, prot, flags, fd, offset);
return orig_mmap(start, length, prot, flags, fd, offset);
}
void
_init(void)
{
printf("Loading hack.\n");
orig_malloc = (void* (*)(size_t)) dlsym(RTLD_NEXT, "malloc");
orig_mmap = (void* (*)(void*, size_t, int, int, int, off_t)) dlsym(RTLD_NEXT, "mmap");
}
编译
gcc -Wall -fPIC -DPIC -c preload.c
ld -shared -o preload.so preload.o -ldl
gcc main.c
使用LD_PRELOAD 运行它
LD_PRELOAD=./preload.so ./a.out
用 strace 运行它
strace ./a.out 2>&1 | view -
来自LD_PRELOAD 的打印输出不会挂钩对mmap 的调用,而只会调用对malloc 的调用。同时,当使用strace 运行时,打印输出确实显示mmap 被多次调用。
这个结果让我很困惑;假设mmap确实被main.c调用(我猜是通过malloc),为什么preload.c不能拦截mmap?
PS:我的平台是 Ubuntu 14.04 和 Linux 内核 3.13
PS2:系统调用是指 libc 中的系统调用包装器(但不确定这是否会对问题产生影响)..
【问题讨论】:
-
对于寻找如何在系统调用中注入失败或假成功的人:寻找
strace-e inject选项
标签: c system-calls ld-preload systrace