Search code examples
ebpfbpf

eBPF - Is map.update() not causing undefined behaviour?


I'm completely new to eBPF, I tried to find an answer to this but can't so I was hoping to get some help.

Take Liz's ebpf.py example

It looks like this:

BPF_HASH(clones);

int hello_world(void *ctx) {
   u64 uid;
   u64 counter = 0;
   u64 *p;
   uid = bpf_get_current_uid_gid() & 0xFFFFFFFF;
   p = clones.lookup(&uid);
   if (p != 0) {
      counter = *p;
   }
   counter++;
   clones.update(&uid, &counter);
   return 0;
}

This then makes me wonder, for the map named clones she calls the update method. She enters a pointer to a stack-allocated variable (counter), does this not cause undefined behaviour when the stack frame is deallocated.

A possible option is that the value within the pointer is copied instead of stored as a pointer.

But then, according to this reference guide BPF_HASH can specify the leaf_type (value of the map). Meaning you can set it to a struct, which can't necessarily be copied.

I feel like I'm missing something so I'm thankful for any explanation for the matter.


Solution

  • A possible option is that the value within the pointer is copied instead of stored as a pointer.

    That's correct. The value pointed to by the pointer is copied in the memory buffer allocated for the map's value.

    Meaning you can set it to a struct, which can't necessarily be copied.

    Why wouldn't that be possible? Note the kernel doesn't really care that it's a struct. It sees a pointer to a memory buffer with a size (the map's value size); it simply copies whatever is in that buffer to the memory buffer allocated for the map value.