1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use crate::svc;

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(u64)]
pub enum FunctionId {
    Invalid = 0,
    GenerateRandomBytes = 0xC3000006
    // TODO: more
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(C)]
pub struct Input {
    pub function_id: FunctionId,
    pub arguments: [u64; 7],
}
const_assert!(core::mem::size_of::<Input>() == 0x40);

impl Input {
    pub const fn new(function_id: FunctionId) -> Self {
        Self { function_id, arguments: [0; 7] }
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
#[repr(u64)]
pub enum Result {
    #[default]
    Success = 0,
    NotImplemented = 1,
    InvalidArgument = 2,
    InProgress = 3,
    NoAsyncOperation = 4,
    InvalidAsyncOperation = 5,
    NotPermitted = 6
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(C)]
pub struct Output {
    pub result: Result,
    pub arguments: [u64; 7],
}
const_assert!(core::mem::size_of::<Output>() == core::mem::size_of::<Input>());

#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
#[repr(C)]
pub struct Arguments {
    pub arguments: [u64; 8]
}
const_assert!(core::mem::size_of::<Arguments>() == core::mem::size_of::<Output>());

impl Arguments {
    pub fn from_input(input: Input) -> Self {
        unsafe {
            core::mem::transmute(input)
        }
    }

    pub fn to_output(self) -> Output {
        unsafe {
            core::mem::transmute(self)
        }
    }
}

pub const GENERATE_RANDOM_BYTES_MAX_SIZE: usize = 0x38;

pub fn generate_random_bytes(dst: *mut u8, size: usize) -> Result {
    let mut input = Input::new(FunctionId::GenerateRandomBytes);
    input.arguments[0] = size as u64;

    let output = svc::call_secure_monitor(input);
    if output.result == Result::Success {
        unsafe {
            core::ptr::copy(output.arguments.as_ptr().offset(1) as *const u8, dst, size);
        }
    }
    output.result
}