Search code examples
bpfebpfbcc-bpf

Is there a String size limit when sending strings back to BPF code and back to userspace?


I am sending this sentence through my BPF code through a BPF Char Array here:

jmommyijsadifjasdijfa, hello, world

And when I print out my output, I only seem to get this output

jmommyij

I seem to be hitting some kind of String size limit. Is there any way to go over this string size limit and print the entire string?

Here is what my BPF code looks like:

#include <uapi/linux/bpf.h>
#define ARRAYSIZE 512

BPF_ARRAY(lookupTable, char**, ARRAYSIZE);

int helloworld2(void *ctx)
{
    int k = 0;
    //print the values in the lookup table
    #pragma clang loop unroll(full)
    for (int i = 0; i < sizeof(lookupTable); i++) {
        //need to use an intermiate variable to hold the value since the pointer will not increment correctly.
        k = i;
        char *key = lookupTable.lookup(&k);
        // if the key is not null, print the value
        if (key != NULL && sizeof(key) > 1) {
            bpf_trace_printk("%s\n", key);
        }
    }
    return 0;
}

Here is my py file:

import ctypes
from bcc import BPF


b = BPF(src_file="hello.c")

lookupTable = b["lookupTable"]
#add hello.csv to the lookupTable array
f = open("hello.csv","r")
file_contents = f.read()
#append file contents to the lookupTable array
b_string1 = file_contents.encode('utf-8')
print(b_string1)
lookupTable[ctypes.c_int(0)] = ctypes.create_string_buffer(b_string1, len(b_string1))
#print(file_contents)
f.close()
# This attaches the compiled BPF program to a kernel event of your choosing,
#in this case to the sys_clone syscall which will cause the BPF program to run
#everytime the sys_clone call occurs.
b.attach_kprobe(event=b.get_syscall_fnname("clone"), fn_name="helloworld2")
# Capture and print the BPF program's trace output
b.trace_print()

Solution

  • You're creating an array of 512 char** (basically u64). So you're just storing the first 8 bytes of your string the rest is discarded.

    What you need is an array of 1 holding a 512 byte value:

    struct data_t {
      char buf[ARRAYSIZE];
    };
    
    BPF_ARRAY(lookupTable, struct data_t, ARRAYSIZE);
    
    

    Also see https://github.com/iovisor/bpftrace/issues/1957