英文:
How to use bpf_map_lookup_elem() to get a char array in eBPF?
问题
我有一个类型为`BPF_MAP_TYPE_ARRAY`的bpf映射:
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__uint(max_entries, 1);
__type(key, u32);
__type(value, char[MAX_SIZE]);
} input_map SEC(".maps");
然后我想获取用户空间输入字符串的值,它是char数组的一种类型:
char target_string[MAX_SIZE] ;
target_string = bpf_map_lookup_elem(&input_map, &0);
出现了编译错误:
error: array type 'char[MAX_SIZE]' is not assignable
我对eBPF和C非常不熟悉,有人可以告诉我为什么会出现这个错误,以及实现我的功能的最佳方法是什么吗?
英文:
I have a bpf map of type BPF_MAP_TYPE_ARRAY
:
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__uint(max_entries, 1);
__type(key, u32);
__type(value, char[MAX__SIZE]);
} input_map SEC(".maps");
Then I want to get the value of the userspace-input string, which is a type of char array:
char target_string[MAX_SIZE] ;
target_string = bpf_map_lookup_elem(&input_map, &0);
It has a compile error:
error: array type 'char[MAX__SIZE]' is not assignable
I'm really new to eBPF and C, could anyone tell me why do I get this error and what is the best way to implement my function?
答案1
得分: 3
您收到此错误是因为在C中,不允许您为char target_string[MAX_SIZE];
分配新值,因为它是一个数组。诀窍在于,在C中,数组和指针在内存方面基本上是相同的。只是数组类型具有编译时边界检查。然而,指针是可以赋值的,所以我们可以这样做:
char *target_string;
__u32 key = 0;
target_string = bpf_map_lookup_elem(&input_map, &key);
if (!target_string) {
return 0;
}
return target_string[2];
额外提示,&0
也是不允许的,您必须创建一个键变量并将其传递给指针。
请注意,我们仍然可以在指针上使用[]
运算符,与数组的使用方式相同。唯一的区别是,您必须确保不超出MAX_SIZE
的边界,否则验证器会阻止您。
英文:
You are getting this error because C does not allow you to assign a new value to char target_string[MAX_SIZE];
because it is an array.
The trick here is that in C, arrays and pointers are basically the same thing (memory wise). Except array types have compile time bounds checking. Pointers however are assignable, so we can do:
char *target_string;
__u32 key = 0;
target_string = bpf_map_lookup_elem(&input_map, &key);
if (!target_string) {
return 0;
}
return target_string[2];
Bonus tip, &0
is also not allowed, you have to make a key var and pass a pointer to it.
Notice how we can still use the []
operator on the pointer, works the same as the array. The only thing is that you have to make sure you do not go out of bounds of your MAX_SIZE
or the verifier will stop you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论