Skip to main content

abi_application/
random.rs

1use crate::Status;
2use core::{ffi::c_void, slice};
3use file_system::Kind;
4use synchronization::once_lock::OnceLock;
5use task::Manager;
6use virtual_file_system::{File, VirtualFileSystem};
7
8const ENTROPY_PATH: &str = "/devices/random/source";
9static ENTROPY: OnceLock<&'static VirtualFileSystem> = OnceLock::new();
10
11/// Install the runtime's entropy source once if the system VFS has a character
12/// device at `/devices/random/source`. The native executable handler calls this
13/// before launch. If the device is absent, a later launch can retry.
14pub async fn initialize_random(vfs: &'static VirtualFileSystem) {
15    if ENTROPY.try_get().is_none()
16        && vfs
17            .get_statistics_for_task(Manager::ROOT_TASK_IDENTIFIER, &ENTROPY_PATH)
18            .await
19            .is_ok_and(|statistics| statistics.kind == Kind::CharacterDevice)
20    {
21        ENTROPY.get_or_init(|| vfs);
22    }
23}
24
25/// Fill the caller's buffer with random bytes from the host-granted entropy source.
26/// Zero size succeeds without touching the buffer or the source, and permits a
27/// null buffer. A pending source suspends the caller's coroutine. On failure the
28/// buffer contents are unspecified and must not be used.
29/// # Safety
30/// Buffer must be writable for size bytes.
31pub unsafe extern "C" fn xila_random_fill(buffer: *mut c_void, size: usize) -> Status {
32    if size > isize::MAX as usize || (size != 0 && buffer.is_null()) {
33        return Status::InvalidArgument;
34    }
35    if size == 0 {
36        return Status::Ok;
37    }
38    let Some(vfs) = ENTROPY.try_get() else {
39        return Status::Unavailable;
40    };
41    // SAFETY: non-null and at most isize::MAX bytes; the caller guarantees validity.
42    let buffer = unsafe { slice::from_raw_parts_mut(buffer.cast(), size) };
43    // A native coroutine opens the source with its own VFS permissions.
44    // Direct calls by the Rust host use the system task.
45    let in_coroutine = crate::is_in_coroutine();
46    // The source file is open only inside this future, so a cancelled process drops the
47    // future in place and closes it, which keeps the device from reading as busy.
48    let result = crate::suspend_on_cancellable(async {
49        let task = if in_coroutine {
50            vfs.task_manager()
51                .try_get_current_task_identifier()
52                .await
53                .map_err(file_system::IntoIoErrorKind::into_io_error_kind)?
54        } else {
55            Manager::ROOT_TASK_IDENTIFIER
56        };
57        File::read_slice_from_character_device(vfs, task, ENTROPY_PATH, buffer).await
58    });
59    match result {
60        Ok(()) => Status::Ok,
61        Err(error) => error.into(),
62    }
63}