簡體   English   中英

Linux中的函數插入(寫函數)

[英]Function Interposition in Linux (write function)

請問如何恢復原始寫入的緩沖區?

size_t write(int fd, const void *buf, size_t count)
{
    static size_t (*write_func)(int, const void *, size_t) = NULL;

    /* get reference to original (libc provided) write */
    if (!write_func)
    {
        write_func = (size_t(*)(int, const void *, size_t))
                     dlsym(RTLD_NEXT, "write");
    }
    return  write_func(fd, buffer, sizeof (buffer));
}

執行擴充的最有效方法之一是在原始緩沖區中切出要更改的字節,然后拼接增量。 將它們粘貼在一起,然后使用writev將所有內容寫出。

struct iovec v[3];
v[0].iov_base = buf;
v[0].iov_len = position_of_new_data;
v[1].iov_base = new_data;
v[1].iov_len = new_data_len;
v[2].iov_base = (const char *)buf + beginning_of_the_end;
v[2].iov_len = count - beginning_of_the_end;
return writev(fd, v, 3);

這對於阻止I / O應該很好。 對於非阻塞I / O,您將要做更多的工作來隱藏write調用被攔截的事實。 或者,您可以僅將描述符翻轉為阻塞狀態,然后在返回之前翻轉回非阻塞狀態。

像這樣:

ssize_t write(int fd, const void *buf, size_t count)
{
    static size_t (*write_func)(int, const void *, size_t) = NULL;
    if (!write_func)
        write_func = (size_t(*)(int, const void *, size_t)) dlsym(RTLD_NEXT, "write");

    // buf is const so, in order to change it, we need to make a copy:
    char tmp[count+1];  // <- it might be safer to use malloc here
    memcpy(tmp,buf,count);

    // modify tmp here
    tmp[count]='a';

    return  write_func(fd, tmp, count+1);
}

如果您要這樣做,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM