Search code examples
linuxkernelebpfbpf

(epbf) Unable to use string.h apis on string that probe read from kernel


When I tried to do some string operations (strlen, strcpy and strtok) today, I found it is unable to use those string.h apis on string probe read from kernel. It will raise unknown opcode error on python bcc/bpf and raise libbpf: failed to find BTF for extern 'strlen' on libbpf.

A pseudo code I tried as follows:

u64 ptr = PT_REGS_PARMX(regs);
char str1[10] = {};
char str2[10] = "test";
bpf_probe_read_kernel(str1, sizeof(str1), (const void *) ptr);
u64 len = strlen(str1);    // error will raise here
len = strlen(str2);        // but this is ok if string not read from kernel

Although strlen I could implement in:

u64 len = 0;
for(len; len < sizeof(str1); len++){
    if (str1[len] == '\0') break;
}

I still wonder that why it is unable to use string.h apis and how could make it able to use.


Solution

  • You can't call arbitrary kernel functions from BPF bytecode.

    The reason it works for str2 is because it's a constant and the compiler therefore optimizes it to 4 without needing to call strlen.

    If you need to compute the length of a string, you need to implement strlen() yourself or to copy one of the kernel's implementations. Note that in general, it is not recommended to perform computation on strings in BPF; that's a job better left to the userspace counterpart.