redbpf icon indicating copy to clipboard operation
redbpf copied to clipboard

Support global variable

Open rhdxmr opened this issue 4 years ago • 4 comments

I am trying to support global variable in RedBPF.

Currently, users can make use of global variables in their probes since RedBPF relocates .data or .bss section to bpf map at runtime. (Actually relocating .bss isn't working correctly)

But I think the userspace API is not convenient enough yet.

This code is an exerpt from the example program of this draft PR.

#[repr(C)]
#[derive(Debug, Clone)]
struct Data {
    var: u64,
    var_wo_sync: u64,
}

let global = Array::<Data>::new(loaded.map(".bss").expect("map not found")).expect("can not initialize Array");
let gval = global.get(0).expect("global var value");
println!("w/ sync, w/o sync, pcpu = {}, {}, {}", gval.var, gval.var_wo_sync, pcpu_val.iter().sum::<u64>());

I think that loaded.map(".bss") or loaded.map(".data") using C structure is not cool enough to access global variable. It feels like C code. I am used to C and I like it but RedBPF is Rust library. :slightly_smiling_face:

I'd like to see more abstract API that exposes individual global variables to users.

Any suggestion and idea will be welcomed.

Thanks,

rhdxmr avatar Feb 06 '22 16:02 rhdxmr

Hello @rsdy

Yesterday, I tried to make use of variables defined in mod.rs Like you said I wanted to get whole information from the variable directly.

What I hoped to make was looked like this

let gvar = loaded.global(unsafe { &GLOBAL_VARIABLE }).expect("error on access gvar");

But I couldn't make it.

It is easy to get type info from the reference. But I couldn't find out how to match the &GLOBAL_VARIABLE with the variable defined in the resulting probe code.

If there is only one global variable in the probe code, we can assume what &GLOBAL_VARIABLE means. But what if there are two or three global variables? How to know which reference is corresponding to which variables in the probe code? I don't know.

Instead I found a workaround that I am not fully satisfied..

    let gvar = loaded
        .global::<u64>("GLOBAL_VAR")
        .expect("error on accessing gvar");

It looks pretty similar to the conventional Loaded::map method.

I still prefer the first API.. Do you have any idea to implement it?

rhdxmr avatar Feb 10 '22 14:02 rhdxmr

Compile errors in FC35 and archlinux are caused by change of kernel v5.16 header. #282 solves that problem.

rhdxmr avatar Feb 10 '22 16:02 rhdxmr

@rsdy I just converted this draft to PR.

It supports users to access global variables of BPF programs.

rhdxmr avatar Mar 03 '22 15:03 rhdxmr

Sorry for ignoring this. I actually read and re-read and re-read it and kept trying to come up with a way to make this API cleaner, but the only thing I can think of was using a macro to get the name with something like paste. Either way, it's kinda hackish, unfortunately.

rsdy avatar Mar 03 '22 17:03 rsdy