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?
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.