How to add hook to memcpy function of linux kernel?

My steps are listed below, but this did not work as intended.

Linux-3.16-code2 \ arch \ x86 \ Lib \ memcpy_64.S:

changed

ENTRY(__memcpy)
ENTRY(memcpy)
...
CFI_ENDPROC
ENDPROC(memcpy)
ENDPROC(__memcpy)

at

ENTRY(__memcpy)
ENTRY(x86_memcpy)
...
CFI_ENDPROC
ENDPROC(x86_memcpy)
ENDPROC(__memcpy)

Linux-3.16-code2 \ Lib \ string.c:

has changed

#ifndef __HAVE_ARCH_MEMCPY
void *memcpy(void *dest, const void *src, size_t count)
{
    char *tmp = dest;
    const char *s = src;

    while (count--)
        *tmp++ = *s++;
    return dest;
}
#endif

at

//#ifndef __HAVE_ARCH_MEMCPY
void *memcpy(void *dest, const void *src, size_t count)
{
    char *tmp = dest;
    const char *s = src;
    my_hook();
    while (count--)
            *tmp++ = *s++;
    return dest;
}
//#endif

remove EXPORT_SYMBOL (memcpy) in arch / x86 / kernel / x8664_ksyms_64.c

add test code to linux-3.16-rc2 \ mm \ memcpy_test.c:

#include <linux/mm.h>
#include <linux/kallsyms.h>
#include <linux/module.h>
int hook_value = -1;
int test_begin = 0;
void  my_test_begin(void)
{
    char src[128] = {0};
    char dst[128] = {1};
    test_begin = 1;
    mb();
    memcpy((char*)dst,(char*)src,50);
    test_begin = 0;
    mb();
    printk("hook value:%d\n",hook_value);
}

void  my_hook(void)
{
    if(test_begin)
            hook_value=1;
}

After calling my_test_begin, I found that hook_value remained -1, it seems that memcpy in my_test_begin never reached hook_value = 1 can anyone help? THX!

+4
source share
1 answer

thanks @Basile Starynkevitch I solve the problem, yes: "Sometimes the compiler optimizes memcpy for __builtin_memcpy"

0

All Articles