为什么LD_PRELOAD似乎不能用wc写入

Cha*_*etz 9 c linux linker ld

我正在玩LD_PRELOAD来拦截libc调用,似乎写入调用不会被wc拦截,尽管它似乎与cat一起工作.问题的精简版本如下所示.

RedHat 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
Run Code Online (Sandbox Code Playgroud)

为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
}
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

有什么解释吗?

nin*_*alj 7

那是因为虽然cat使用write,wc使用printf,可能使用内联版本write或其引用write被绑定libc,所以不能插入.

这可以通过以下方式轻松看出ltrace:

$ echo foo | ltrace wc 2>&1 | grep 'write\|print'
printf("%*s", 7, "1")                            = 7
printf(" %*s", 7, "1")                           = 8
printf(" %*s", 7, "4")                           = 8


$ echo foo | ltrace cat 2>&1 | grep 'write\|print'
write(1, "foo\n", 4foo
Run Code Online (Sandbox Code Playgroud)