External Publication
Visit Post

[Pre-RFC] BTF relocations

Rust Internals [Unofficial] June 1, 2026
Source

I've made a small change to the RFC since yesterday - I have realized that intrinsics taking field: usize aren't a good design for nested field access, and would require multiple subsequent calls, therefore lowering to more LLVM intrinsic calls than necessary. It also requires the caller to keep track of field indices, which seems unnecessary, given that the compiler has the information about the type layout already.

What works better in that case are builtin-syntax wrapper macros, like:

# library/core/src/btf.rs

#[allow_internal_unstable(builtin_syntax)]
pub macro field_byte_offset($Container:ty, $($fields:expr)+ $(,)?) {
    builtin # btf_field_byte_offset($Container, $($fields)+)
}

#[allow_internal_unstable(builtin_syntax)]
pub macro field_exists($Container:ty, $($fields:expr)+ $(,)?) {
    builtin # btf_field_exists($Container, $($fields)+)
}

Which then could be used by the user the following way:

#![feature(btf_relocations)]

#[repr(Btf)]
pub struct load_weight {
    pub weight: usize,
}

#[repr(Btf)]
pub struct sched_entity {
    pub load: load_weight,
    pub vruntime: u64,
}

#[repr(Btf)]
pub struct task_struct {
    pub se: sched_entity,
}

impl task_struct {
    pub fn sched_vruntime(&self) -> Option<&u64> {
        if core::btf::field_exists!(task_struct, se.vruntime) {
            let offset = core::btf::field_byte_offset!(task_struct, se.vruntime);
            let ptr = self as *const task_struct as *const u8;

            // SAFETY: the BTF relocation says that `se.vruntime` exists in the
            // target layout, and the returned offset is relative to `task_struct`.
            Some(unsafe { &*(ptr.add(offset) as *const u64) })
        } else {
            None
        }
    }

    pub fn sched_load_weight(&self) -> Option<&usize> {
        if core::btf::field_exists!(task_struct, se.load.weight) {
            let offset = core::btf::field_byte_offset!(task_struct, se.load.weight);
            let ptr = self as *const task_struct as *const u8;

            // SAFETY: the BTF relocation says that `se.load.weight` exists in the
            // target layout, and the returned offset is relative to `task_struct`.
            Some(unsafe { &*(ptr.add(offset) as *const usize) })
        } else {
            None
        }
    }
}

I would appreciate the feedback on the RFC. I'm also going to provide the implementation the next days.

Discussion in the ATmosphere

Loading comments...