问题描述
我通过这里的 BPF 字符数组通过我的 BPF 代码发送这句话:
jmommyijsadifjasdijfa,你好,世界
jmommyij
我似乎遇到了某种字符串大小限制。有没有办法超过这个字符串大小限制并打印整个字符串?
这是我的 BPF 代码的样子:
#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;
}
这是我的py文件:
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()
解决方法
您正在创建一个包含 512 个字符**(基本上是 u64)的数组。因此,您只存储字符串的前 8 个字节,其余字节将被丢弃。
您需要的是一个 1 的数组,其中包含一个 512 字节的值:
struct data_t {
char buf[ARRAYSIZE];
};
BPF_ARRAY(lookupTable,struct data_t,ARRAYSIZE);