Skip to main content

c/
vdso.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// ============================================================
5// vDSO fast paths
6// ============================================================
7//
8// The kernel maps a small ELF image (AT_SYSINFO_EHDR) into every process.
9// It exports clock_gettime, gettimeofday, getcpu and, on recent kernels,
10// getrandom.  Calling them avoids a ring transition; musl does the same for
11// clock_gettime and getcpu.  Every entry point here falls back to the real
12// syscall when the symbol or the kernel support is missing.
13//
14// The vDSO uses two naming schemes.  x86_64 and riscv64 export
15// __vdso_<name>; aarch64 exports __kernel_<name>.  Look both up and cache
16// whichever one the current kernel provides.
17
18const AT_SYSINFO_EHDR: c_ulong = 33;
19const AT_PAGESZ: c_ulong = 6;
20
21const PT_LOAD: u32 = 1;
22const PT_DYNAMIC: u32 = 2;
23const DT_HASH: u64 = 4;
24const DT_STRTAB: u64 = 5;
25const DT_SYMTAB: u64 = 6;
26
27const STT_FUNC: u8 = 2;
28const STB_GLOBAL: u8 = 1;
29const STB_WEAK: u8 = 2;
30
31const MADV_WIPEONFORK: i32 = 18;
32
33// Opaque per-thread state for vDSO getrandom.  One pointer lives in the
34// otherwise unused part of the 256-byte TCB (0x38; errno ends at 0x34).
35const GETRANDOM_TCB_OFFSET: usize = 0x38;
36
37// The state pointer uses 1 as an "allocation in progress" marker so a signal
38// handler that re-enters getrandom falls back to the syscall instead of
39// allocating a second state.
40const STATE_ALLOCATING: usize = 1;
41
42// vgetrandom_opaque_params from linux/random.h.
43#[repr(C)]
44struct VgetrandomParams {
45    size_of_opaque_state: u32,
46    mmap_prot: u32,
47    mmap_flags: u32,
48    reserved: [u32; 13],
49}
50
51const VGETRANDOM_UNINIT: usize = 0;
52const VGETRANDOM_INITIALIZING: usize = 1;
53const VGETRANDOM_READY: usize = 2;
54const VGETRANDOM_DISABLED: usize = 3;
55
56static VGETRANDOM_STATE: AtomicUsize = AtomicUsize::new(VGETRANDOM_UNINIT);
57static VGETRANDOM_FN: AtomicUsize = AtomicUsize::new(0);
58static VGETRANDOM_SIZE: AtomicUsize = AtomicUsize::new(0);
59static VGETRANDOM_PROT: AtomicUsize = AtomicUsize::new(0);
60static VGETRANDOM_FLAGS: AtomicUsize = AtomicUsize::new(0);
61static VGETRANDOM_PAGE: AtomicUsize = AtomicUsize::new(0);
62
63// Serializes first-time state allocation.  try_lock semantics are deliberate:
64// a signal handler that re-enters getrandom while its own thread is
65// allocating must fall back to the syscall, not spin forever.
66static VGETRANDOM_ALLOC: AtomicUsize = AtomicUsize::new(0);
67
68// usize::MAX means "not resolved yet"; 0 means "no vDSO".
69static CLOCK_GETTIME_VDSO: AtomicUsize = AtomicUsize::new(usize::MAX);
70
71// The getcpu cache starts as a callable resolver so the hot path only has to
72// test for NULL, matching musl's lazy vDSO pointer trick.
73static GETCPU_VDSO: core::sync::atomic::AtomicPtr<c_void> =
74    core::sync::atomic::AtomicPtr::new(getcpu_init as *mut c_void);
75
76#[inline]
77unsafe fn read_u16(p: *const u8) -> u16 {
78    u16::from_le(core::ptr::read_unaligned(p as *const u16))
79}
80
81#[inline]
82unsafe fn read_u32(p: *const u8) -> u32 {
83    u32::from_le(core::ptr::read_unaligned(p as *const u32))
84}
85
86#[inline]
87unsafe fn read_u64(p: *const u8) -> u64 {
88    u64::from_le(core::ptr::read_unaligned(p as *const u64))
89}
90
91/// Look up a symbol in the vDSO by name.  Versions are ignored: the vDSO
92/// exports exactly one definition of each entry point.
93unsafe fn vdso_lookup(want: &[u8]) -> usize {
94    let eh = crate::getauxval(AT_SYSINFO_EHDR) as usize;
95    if eh == 0 {
96        return 0;
97    }
98    let image = eh as *const u8;
99    if read_u32(image) != 0x464c_457f || *image.add(4) != 2 {
100        return 0; // not a 64-bit ELF image
101    }
102    let phoff = read_u64(image.add(32)) as usize;
103    let phentsize = read_u16(image.add(54)) as usize;
104    let phnum = read_u16(image.add(56)) as usize;
105
106    let mut load_base = usize::MAX;
107    let mut dynamic = 0usize;
108    let mut i = 0usize;
109    while i < phnum {
110        let ph = image.add(phoff + i * phentsize);
111        match read_u32(ph) {
112            PT_LOAD => {
113                let off = read_u64(ph.add(8)) as usize;
114                let vaddr = read_u64(ph.add(16)) as usize;
115                load_base = eh.wrapping_add(off).wrapping_sub(vaddr);
116            }
117            PT_DYNAMIC => {
118                dynamic = eh.wrapping_add(read_u64(ph.add(8)) as usize);
119            }
120            _ => {}
121        }
122        i += 1;
123    }
124    if load_base == usize::MAX || dynamic == 0 {
125        return 0;
126    }
127
128    let mut strtab = 0usize;
129    let mut symtab = 0usize;
130    let mut hash = 0usize;
131    let mut dp = dynamic as *const u8;
132    loop {
133        let tag = read_u64(dp);
134        if tag == 0 {
135            break;
136        }
137        let val = read_u64(dp.add(8)) as usize;
138        match tag {
139            DT_STRTAB => strtab = load_base.wrapping_add(val),
140            DT_SYMTAB => symtab = load_base.wrapping_add(val),
141            DT_HASH => hash = load_base.wrapping_add(val),
142            _ => {}
143        }
144        dp = dp.add(16);
145    }
146    if strtab == 0 || symtab == 0 || hash == 0 {
147        return 0;
148    }
149
150    // DT_HASH starts with nbucket/nchain; the vDSO always carries one.
151    let nsym = read_u32((hash + 4) as *const u8) as usize;
152    let mut i = 1usize;
153    while i < nsym {
154        let sym = (symtab + i * 24) as *const u8;
155        let info = *sym.add(4);
156        if info & 0xf != STT_FUNC {
157            i += 1;
158            continue;
159        }
160        let bind = info >> 4;
161        if bind != STB_GLOBAL && bind != STB_WEAK {
162            i += 1;
163            continue;
164        }
165        if read_u16(sym.add(6)) == 0 {
166            i += 1;
167            continue;
168        }
169        let name = strtab.wrapping_add(read_u32(sym) as usize);
170        if crate::cstr_eq(name as *const u8, want) {
171            return load_base.wrapping_add(read_u64(sym.add(8)) as usize);
172        }
173        i += 1;
174    }
175    0
176}
177
178/// Try the two names the kernel architectures use for the same entry point.
179unsafe fn vdso_lookup_either(vdso_name: &[u8], kernel_name: &[u8]) -> usize {
180    let p = vdso_lookup(vdso_name);
181    if p != 0 {
182        return p;
183    }
184    vdso_lookup(kernel_name)
185}
186
187#[inline]
188unsafe fn vdso_clock_gettime() -> usize {
189    let p = CLOCK_GETTIME_VDSO.load(Ordering::Relaxed);
190    if p != usize::MAX {
191        return p;
192    }
193    let p = vdso_lookup_either(b"__vdso_clock_gettime", b"__kernel_clock_gettime");
194    CLOCK_GETTIME_VDSO.store(p, Ordering::Relaxed);
195    p
196}
197
198#[no_mangle]
199pub unsafe extern "C" fn clock_gettime(clockid: c_int, ts: *mut timespec) -> c_int {
200    let p = vdso_clock_gettime();
201    if p != 0 {
202        let f: unsafe extern "C" fn(c_int, *mut timespec) -> c_int = core::mem::transmute(p);
203        let r = f(clockid, ts);
204        if r == 0 {
205            return 0;
206        }
207        if r == -EINVAL {
208            ERRNO!() = EINVAL;
209            return -1;
210        }
211        // Unsupported clock or an old vDSO: fall back to the syscall.
212    }
213    let r = sys_clock_gettime(clockid, ts);
214    if r < 0 {
215        ERRNO!() = (-r) as c_int;
216        -1
217    } else {
218        0
219    }
220}
221
222unsafe extern "C" fn getcpu_init(cpu: *mut u32, node: *mut u32, unused: *mut c_void) -> c_long {
223    let p = vdso_lookup_either(b"__vdso_getcpu", b"__kernel_getcpu");
224    GETCPU_VDSO.store(p as *mut c_void, Ordering::Relaxed);
225    if p == 0 {
226        -(ENOSYS as c_long)
227    } else {
228        let f: unsafe extern "C" fn(*mut u32, *mut u32, *mut c_void) -> c_long =
229            core::mem::transmute(p);
230        f(cpu, node, unused)
231    }
232}
233
234/// sched_getcpu() fast path.  Returns false when the vDSO is unavailable or
235/// declines this CPU, in which case the caller issues the real syscall.
236#[inline]
237unsafe fn vdso_getcpu(cpu: *mut u32) -> bool {
238    let p = GETCPU_VDSO.load(Ordering::Relaxed) as usize;
239    if p == 0 {
240        return false;
241    }
242    let f: unsafe extern "C" fn(*mut u32, *mut u32, *mut c_void) -> c_long =
243        core::mem::transmute(p);
244    f(cpu, core::ptr::null_mut(), core::ptr::null_mut()) == 0
245}
246
247// ============================================================
248// vDSO getrandom
249// ============================================================
250
251#[inline]
252unsafe fn tcb_slot(offset: usize) -> *mut usize {
253    let tp = arch_get_tp_fast();
254    if tp == 0 {
255        return core::ptr::null_mut();
256    }
257    #[cfg(target_arch = "x86_64")]
258    let tcb = tp;
259    #[cfg(target_arch = "powerpc64")]
260    let tcb = tp - (256 + 0x7000);
261    #[cfg(any(target_arch = "aarch64", target_arch = "riscv64", target_arch = "loongarch64"))]
262    let tcb = tp - 256;
263    if core::ptr::read_unaligned(tcb as *const usize) != tcb {
264        return core::ptr::null_mut();
265    }
266    (tcb + offset) as *mut usize
267}
268
269#[inline]
270unsafe fn getrandom_slot() -> *mut usize {
271    tcb_slot(GETRANDOM_TCB_OFFSET)
272}
273
274/// Query the vDSO once.  Returns true when getrandom() may use the vDSO and
275/// the per-thread state layout has been recorded.
276unsafe fn vgetrandom_init() -> bool {
277    match VGETRANDOM_STATE.load(Ordering::Acquire) {
278        VGETRANDOM_READY => return true,
279        VGETRANDOM_DISABLED => return false,
280        VGETRANDOM_UNINIT => {}
281        // Another thread is querying right now; use the syscall rather than
282        // waiting, so getrandom() always makes progress.
283        _ => return false,
284    }
285    if VGETRANDOM_STATE
286        .compare_exchange(
287            VGETRANDOM_UNINIT,
288            VGETRANDOM_INITIALIZING,
289            Ordering::AcqRel,
290            Ordering::Acquire,
291        )
292        .is_err()
293    {
294        return false;
295    }
296
297    let p = vdso_lookup_either(b"__vdso_getrandom", b"__kernel_getrandom");
298    let mut ready = false;
299    if p != 0 {
300        let query: unsafe extern "C" fn(
301            *mut u8,
302            usize,
303            u32,
304            *mut VgetrandomParams,
305            usize,
306        ) -> isize = core::mem::transmute(p);
307        let mut params: VgetrandomParams = core::mem::zeroed();
308        if query(core::ptr::null_mut(), 0, 0, &mut params, usize::MAX) == 0 {
309            let page = crate::getauxval(AT_PAGESZ) as usize;
310            let page = if page == 0 { 4096 } else { page };
311            let size = params.size_of_opaque_state as usize;
312            if size > 0 && size <= page {
313                VGETRANDOM_FN.store(p, Ordering::Relaxed);
314                VGETRANDOM_SIZE.store(size, Ordering::Relaxed);
315                VGETRANDOM_PROT.store(params.mmap_prot as usize, Ordering::Relaxed);
316                VGETRANDOM_FLAGS.store(params.mmap_flags as usize, Ordering::Relaxed);
317                VGETRANDOM_PAGE.store(page, Ordering::Relaxed);
318                ready = true;
319            }
320        }
321    }
322    VGETRANDOM_STATE.store(
323        if ready {
324            VGETRANDOM_READY
325        } else {
326            VGETRANDOM_DISABLED
327        },
328        Ordering::Release,
329    );
330    ready
331}
332
333/// Get (or allocate) this thread's opaque vDSO state.  Returns null when the
334/// syscall must be used instead.
335unsafe fn vgetrandom_thread_state() -> *mut u8 {
336    let slot = getrandom_slot();
337    if slot.is_null() {
338        return core::ptr::null_mut();
339    }
340    // The TCB is only 4-byte aligned when a loaded DSO's TLS alignment is 4,
341    // so the slot must not be touched through an &AtomicUsize (unaligned
342    // atomic references panic in debug builds and are not atomic on all
343    // architectures).  Only this thread, including its signal handlers, uses
344    // the slot; unaligned loads/stores plus a try-lock are sufficient.
345    let mut state = core::ptr::read_unaligned(slot);
346    if state == 0 {
347        if VGETRANDOM_ALLOC
348            .compare_exchange(0, 1, Ordering::Acquire, Ordering::Relaxed)
349            .is_err()
350        {
351            return core::ptr::null_mut();
352        }
353        // A previous signal handler may have completed the allocation while
354        // this invocation was interrupted before taking the lock.
355        state = core::ptr::read_unaligned(slot);
356        if state != 0 {
357            VGETRANDOM_ALLOC.store(0, Ordering::Release);
358            return if state == STATE_ALLOCATING {
359                core::ptr::null_mut()
360            } else {
361                state as *mut u8
362            };
363        }
364        core::ptr::write_unaligned(slot, STATE_ALLOCATING);
365        let saved_errno = ERRNO!();
366        let page = VGETRANDOM_PAGE.load(Ordering::Relaxed);
367        let prot = VGETRANDOM_PROT.load(Ordering::Relaxed) as i32;
368        let flags = VGETRANDOM_FLAGS.load(Ordering::Relaxed) as i32;
369        let mapped = sys_mmap(core::ptr::null_mut(), page, prot, flags, -1, 0);
370        if mapped.is_null() || mapped == MMAP_FAILED {
371            ERRNO!() = saved_errno;
372            core::ptr::write_unaligned(slot, 0);
373            VGETRANDOM_ALLOC.store(0, Ordering::Release);
374            return core::ptr::null_mut();
375        }
376        // fork() copies the state page.  Wiping it in the child forces the
377        // kernel's generation check to reseed instead of reusing the parent's
378        // buffered bytes.  Without this guarantee, do not use the vDSO.
379        let advice = <Arch as Syscalls>::syscall3(
380            SYS_MADVISE,
381            mapped as i64,
382            page as i64,
383            MADV_WIPEONFORK as i64,
384        );
385        if advice < 0 {
386            ERRNO!() = saved_errno;
387            sys_munmap(mapped, page);
388            core::ptr::write_unaligned(slot, 0);
389            VGETRANDOM_ALLOC.store(0, Ordering::Release);
390            VGETRANDOM_STATE.store(VGETRANDOM_DISABLED, Ordering::Release);
391            return core::ptr::null_mut();
392        }
393        // Keep the state from straddling a page boundary; mmap returns a
394        // page-aligned block and vgetrandom_init() rejected oversized states.
395        core::ptr::write_unaligned(slot, mapped as usize);
396        VGETRANDOM_ALLOC.store(0, Ordering::Release);
397        state = mapped as usize;
398    }
399    if state == STATE_ALLOCATING {
400        return core::ptr::null_mut();
401    }
402    state as *mut u8
403}
404
405/// vDSO getrandom().  Returns None when the caller must issue the syscall.
406unsafe fn vgetrandom(buf: *mut u8, len: usize, flags: u32) -> Option<isize> {
407    if len == 0 || !vgetrandom_init() {
408        return None;
409    }
410    let state = vgetrandom_thread_state();
411    if state.is_null() {
412        return None;
413    }
414    let p = VGETRANDOM_FN.load(Ordering::Relaxed);
415    if p == 0 {
416        return None;
417    }
418    let size = VGETRANDOM_SIZE.load(Ordering::Relaxed);
419    let f: unsafe extern "C" fn(*mut u8, usize, u32, *mut u8, usize) -> isize =
420        core::mem::transmute(p);
421    Some(f(buf, len, flags, state, size))
422}
423
424/// Release a thread's getrandom state when it exits.
425pub unsafe fn vdso_getrandom_thread_exit() {
426    let slot = getrandom_slot();
427    if slot.is_null() {
428        return;
429    }
430    let state = core::ptr::read_unaligned(slot);
431    if state > STATE_ALLOCATING {
432        core::ptr::write_unaligned(slot, 0);
433        let page = VGETRANDOM_PAGE.load(Ordering::Relaxed);
434        sys_munmap(state as *mut u8, page);
435    }
436}