0

我有一个小 txt 文件,我想在这里写给 BPF。这是我的 BPF 的 python 代码的样子,但我现在无法打印出任何东西。我一直以加载程序失败告终:带有一堆寄存器错误的无效参数。截至目前,我的字符串基本上说你好,世界,嗨

BPF_ARRAY(lookupTable, char, 512);
int helloworld2(void *ctx)
{
    //print the values in the lookup table
    #pragma clang loop unroll(full)
    for (int i = 0; i < 512; i++) {
        char *key = lookupTable.lookup(&i);
        if (key) {
            bpf_trace_printk("%s\n", key);
        }
    }
    return 0;
}

这是Python代码:

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')
b_string1 = ctypes.create_string_buffer(b_string1)
lookupTable[0] = b_string1
f.close()

b.attach_kprobe(event=b.get_syscall_fnname("clone"), fn_name="helloworld2")
b.trace_print()

我在这个 pastebin 中链接了错误,因为它太长了: BPF 错误

一个值得注意的错误是提到检测到无限循环,这是我需要检查的。

4

1 回答 1

1

问题是它i是通过指针传递的bpf_map_lookup_elem,因此编译器实际上无法展开循环(从它的角度来看,i可能不会线性增加)。

使用中间变量足以解决此问题:

BPF_ARRAY(lookupTable, char, 512);
#define MAX_LENGTH 1
int helloworld2(void *ctx)
{
    //print the values in the lookup table
    #pragma clang loop unroll(full)
    for (int i = 0; i < 1; i++) {
        int k = i;
        char *key = lookupTable.lookup(&k);
        if (key) {
            bpf_trace_printk("%s\n", key);
        }
    }
    return 0;
}
于 2021-07-28T08:30:32.783 回答