我正在使用 LD_PRELOAD 来拦截 libc 调用,看起来 write 调用不会被 wc 拦截,尽管它似乎确实可以与 cat 一起使用。下面显示了该问题的精简版本。
红帽 Linux 2.6.9-42.ELsmp
Makefile
writelib:
gcc -Wall -rdynamic -fPIC -c write.c
gcc -shared -Wl,-soname,libwrite.so -Wl,-export-dynamic -o libwrite.so write.o -ldl
write.c:
#include <stdio.h>
#include <string.h>
#ifndef __USE_GNU
#define __USE_GNU
#define __USE_GNU_DEFINED
#endif
#include <dlfcn.h>
#ifdef __USE_GNU_DEFINED
#undef __USE_GNU
#undef __USE_GNU_DEFINED
#endif
#include <unistd.h>
#include <stdlib.h>
static ssize_t (*libc_write)(int fd, const void *buf, size_t len);
ssize_t
write(int fd, const void *buf, size_t len)
{
static int already;
ssize_t ret;
if (!already) {
if ((libc_write = dlsym(RTLD_NEXT, "write")) == NULL) {
exit(1);
}
already = 1;
}
ret = (*libc_write)(fd,"LD_PRELOAD\n",11);
return len; // not ret so cat doesn't take forever
}
Output:
prompt: make
gcc -Wall -rdynamic -fPIC -c write.c
gcc -shared -Wl,-soname,libwrite.so -Wl,-export-dynamic -o libwrite.so write.o -ldl
prompt: LD_PRELOAD=./libwrite.so /bin/cat write.c
LD_PRELOAD
prompt: LD_PRELOAD=./libwrite.so /usr/bin/wc write.c
32 70 572 write.c
有什么解释吗?