Skip to main content

libc_rs/
raw.rs

1//! Raw AArch64 `svc #0` system call dispatch and syscall numbers.
2
3use crate::errno::{Errno, SysResult};
4
5/// AArch64 unikernel system call numbers.
6pub mod nr {
7    pub const GETCWD: usize = 17;
8    pub const EVENTFD2: usize = 19;
9    pub const EPOLL_CREATE1: usize = 20;
10    pub const EPOLL_CTL: usize = 21;
11    pub const DUP: usize = 23;
12    pub const DUP3: usize = 24;
13    pub const FCNTL: usize = 25;
14    pub const IOCTL: usize = 29;
15    pub const FLOCK: usize = 32;
16    pub const MKDIRAT: usize = 34;
17    pub const UNLINKAT: usize = 35;
18    pub const LINKAT: usize = 37;
19    pub const RENAMEAT: usize = 38;
20    pub const FTRUNCATE: usize = 46;
21    pub const FACCESSAT: usize = 48;
22    pub const CHDIR: usize = 49;
23    pub const FCHMOD: usize = 52;
24    pub const OPENAT: usize = 56;
25    pub const CLOSE: usize = 57;
26    pub const PIPE2: usize = 59;
27    pub const GETDENTS64: usize = 61;
28    pub const LSEEK: usize = 62;
29    pub const READ: usize = 63;
30    pub const WRITE: usize = 64;
31    pub const WRITEV: usize = 66;
32    pub const PREAD64: usize = 67;
33    pub const PWRITE64: usize = 68;
34    pub const PPOLL: usize = 73;
35    pub const READLINKAT: usize = 78;
36    pub const NEWFSTATAT: usize = 79;
37    pub const FSTAT: usize = 80;
38    pub const FSYNC: usize = 82;
39    pub const EXIT: usize = 93;
40    pub const EXIT_GROUP: usize = 94;
41    pub const FUTEX: usize = 98;
42    pub const CLOCK_SETTIME: usize = 112;
43    pub const CLOCK_GETTIME: usize = 113;
44    pub const CLOCK_NANOSLEEP: usize = 115;
45    pub const SCHED_YIELD: usize = 124;
46    pub const KILL: usize = 129;
47    pub const RT_SIGACTION: usize = 134;
48    pub const RT_SIGRETURN: usize = 139;
49    pub const SETPGID: usize = 154;
50    pub const SETSID: usize = 157;
51    pub const GETRLIMIT: usize = 163;
52    pub const SETRLIMIT: usize = 164;
53    pub const GETRUSAGE: usize = 165;
54    pub const UMASK: usize = 166;
55    pub const GETPID: usize = 172;
56    pub const GETUID: usize = 174;
57    pub const GETEUID: usize = 175;
58    pub const GETGID: usize = 176;
59    pub const GETEGID: usize = 177;
60    pub const GETTID: usize = 178;
61    pub const SOCKET: usize = 198;
62    pub const SOCKETPAIR: usize = 199;
63    pub const BIND: usize = 200;
64    pub const LISTEN: usize = 201;
65    pub const CONNECT: usize = 203;
66    pub const SENDTO: usize = 206;
67    pub const RECVFROM: usize = 207;
68    pub const SETSOCKOPT: usize = 208;
69    pub const GETSOCKOPT: usize = 209;
70    pub const SHUTDOWN: usize = 210;
71    pub const MUNMAP: usize = 215;
72    pub const CLONE: usize = 220;
73    pub const EXECVE: usize = 221;
74    pub const MMAP: usize = 222;
75    pub const MPROTECT: usize = 226;
76    pub const MINCORE: usize = 232;
77    pub const MADVISE: usize = 233;
78    pub const ACCEPT4: usize = 242;
79    pub const WAIT4: usize = 260;
80    pub const GETRANDOM: usize = 278;
81    pub const EPOLL_PWAIT2: usize = 441;
82}
83
84/// Decodes a raw `x0` return value from `svc #0` into [`SysResult<usize>`].
85///
86/// Negative values in `-4095..=-1` represent `-errno`.
87pub const fn decode_raw(raw: usize) -> SysResult<usize> {
88    let signed = raw as isize;
89    if signed >= -4095 && signed < 0 {
90        Err(Errno((-signed) as i32))
91    } else {
92        Ok(raw)
93    }
94}
95
96#[cfg(not(all(target_arch = "aarch64", target_os = "none")))]
97mod mock {
98    #[cfg(test)]
99    use core::sync::atomic::AtomicBool;
100    use core::sync::atomic::AtomicUsize;
101    use core::sync::atomic::Ordering;
102
103    use crate::errno::{ENOSYS, Errno, SysResult};
104
105    pub type SyscallHandler = fn(usize, [usize; 6]) -> SysResult<usize>;
106
107    pub static MOCK_SYSCALL: AtomicUsize = AtomicUsize::new(0);
108
109    #[cfg(test)]
110    static MOCK_LOCK: AtomicBool = AtomicBool::new(false);
111
112    #[cfg(test)]
113    struct LockGuard;
114
115    #[cfg(test)]
116    impl Drop for LockGuard {
117        fn drop(&mut self) {
118            MOCK_SYSCALL.store(0, Ordering::Release);
119            MOCK_LOCK.store(false, Ordering::Release);
120        }
121    }
122
123    #[cfg(test)]
124    pub fn with_mock_syscall<R>(handler: SyscallHandler, f: impl FnOnce() -> R) -> R {
125        while MOCK_LOCK
126            .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
127            .is_err()
128        {
129            core::hint::spin_loop();
130        }
131        let _guard = LockGuard;
132        MOCK_SYSCALL.store(handler as usize, Ordering::Release);
133        f()
134    }
135
136    pub fn dispatch(nr: usize, args: [usize; 6]) -> SysResult<usize> {
137        let ptr = MOCK_SYSCALL.load(Ordering::Acquire);
138        if ptr == 0 {
139            return Err(Errno(ENOSYS));
140        }
141        // SAFETY: `ptr` was stored from a `SyscallHandler` function pointer in `with_mock_syscall`.
142        let handler: SyscallHandler = unsafe { core::mem::transmute(ptr) };
143        handler(nr, args)
144    }
145}
146
147#[cfg(test)]
148pub(crate) fn with_mock_syscall<R>(
149    handler: fn(usize, [usize; 6]) -> SysResult<usize>,
150    f: impl FnOnce() -> R,
151) -> R {
152    mock::with_mock_syscall(handler, f)
153}
154
155/// Invokes a 0-argument system call.
156///
157/// # Safety
158///
159/// The caller must uphold the ABI and memory safety invariants required by syscall `nr`.
160#[inline]
161pub unsafe fn syscall0(nr: usize) -> SysResult<usize> {
162    #[cfg(all(target_arch = "aarch64", target_os = "none"))]
163    {
164        let ret: usize;
165        // SAFETY: The caller upholds the syscall contract for `nr`.
166        unsafe {
167            core::arch::asm!(
168                "svc #0",
169                in("x8") nr,
170                lateout("x0") ret,
171                options(nostack, preserves_flags),
172            );
173        }
174        decode_raw(ret)
175    }
176    #[cfg(not(all(target_arch = "aarch64", target_os = "none")))]
177    {
178        mock::dispatch(nr, [0, 0, 0, 0, 0, 0])
179    }
180}
181
182/// Invokes a 1-argument system call.
183///
184/// # Safety
185///
186/// The caller must uphold the ABI and memory safety invariants required by syscall `nr`.
187#[inline]
188pub unsafe fn syscall1(nr: usize, a0: usize) -> SysResult<usize> {
189    #[cfg(all(target_arch = "aarch64", target_os = "none"))]
190    {
191        let ret: usize;
192        // SAFETY: The caller upholds the syscall contract for `nr`.
193        unsafe {
194            core::arch::asm!(
195                "svc #0",
196                in("x8") nr,
197                inlateout("x0") a0 => ret,
198                options(nostack, preserves_flags),
199            );
200        }
201        decode_raw(ret)
202    }
203    #[cfg(not(all(target_arch = "aarch64", target_os = "none")))]
204    {
205        mock::dispatch(nr, [a0, 0, 0, 0, 0, 0])
206    }
207}
208
209/// Invokes a 2-argument system call.
210///
211/// # Safety
212///
213/// The caller must uphold the ABI and memory safety invariants required by syscall `nr`.
214#[inline]
215pub unsafe fn syscall2(nr: usize, a0: usize, a1: usize) -> SysResult<usize> {
216    #[cfg(all(target_arch = "aarch64", target_os = "none"))]
217    {
218        let ret: usize;
219        // SAFETY: The caller upholds the syscall contract for `nr`.
220        unsafe {
221            core::arch::asm!(
222                "svc #0",
223                in("x8") nr,
224                inlateout("x0") a0 => ret,
225                in("x1") a1,
226                options(nostack, preserves_flags),
227            );
228        }
229        decode_raw(ret)
230    }
231    #[cfg(not(all(target_arch = "aarch64", target_os = "none")))]
232    {
233        mock::dispatch(nr, [a0, a1, 0, 0, 0, 0])
234    }
235}
236
237/// Invokes a 3-argument system call.
238///
239/// # Safety
240///
241/// The caller must uphold the ABI and memory safety invariants required by syscall `nr`.
242#[inline]
243pub unsafe fn syscall3(nr: usize, a0: usize, a1: usize, a2: usize) -> SysResult<usize> {
244    #[cfg(all(target_arch = "aarch64", target_os = "none"))]
245    {
246        let ret: usize;
247        // SAFETY: The caller upholds the syscall contract for `nr`.
248        unsafe {
249            core::arch::asm!(
250                "svc #0",
251                in("x8") nr,
252                inlateout("x0") a0 => ret,
253                in("x1") a1,
254                in("x2") a2,
255                options(nostack, preserves_flags),
256            );
257        }
258        decode_raw(ret)
259    }
260    #[cfg(not(all(target_arch = "aarch64", target_os = "none")))]
261    {
262        mock::dispatch(nr, [a0, a1, a2, 0, 0, 0])
263    }
264}
265
266/// Invokes a 4-argument system call.
267///
268/// # Safety
269///
270/// The caller must uphold the ABI and memory safety invariants required by syscall `nr`.
271#[inline]
272pub unsafe fn syscall4(nr: usize, a0: usize, a1: usize, a2: usize, a3: usize) -> SysResult<usize> {
273    #[cfg(all(target_arch = "aarch64", target_os = "none"))]
274    {
275        let ret: usize;
276        // SAFETY: The caller upholds the syscall contract for `nr`.
277        unsafe {
278            core::arch::asm!(
279                "svc #0",
280                in("x8") nr,
281                inlateout("x0") a0 => ret,
282                in("x1") a1,
283                in("x2") a2,
284                in("x3") a3,
285                options(nostack, preserves_flags),
286            );
287        }
288        decode_raw(ret)
289    }
290    #[cfg(not(all(target_arch = "aarch64", target_os = "none")))]
291    {
292        mock::dispatch(nr, [a0, a1, a2, a3, 0, 0])
293    }
294}
295
296/// Invokes a 5-argument system call.
297///
298/// # Safety
299///
300/// The caller must uphold the ABI and memory safety invariants required by syscall `nr`.
301#[inline]
302pub unsafe fn syscall5(
303    nr: usize,
304    a0: usize,
305    a1: usize,
306    a2: usize,
307    a3: usize,
308    a4: usize,
309) -> SysResult<usize> {
310    #[cfg(all(target_arch = "aarch64", target_os = "none"))]
311    {
312        let ret: usize;
313        // SAFETY: The caller upholds the syscall contract for `nr`.
314        unsafe {
315            core::arch::asm!(
316                "svc #0",
317                in("x8") nr,
318                inlateout("x0") a0 => ret,
319                in("x1") a1,
320                in("x2") a2,
321                in("x3") a3,
322                in("x4") a4,
323                options(nostack, preserves_flags),
324            );
325        }
326        decode_raw(ret)
327    }
328    #[cfg(not(all(target_arch = "aarch64", target_os = "none")))]
329    {
330        mock::dispatch(nr, [a0, a1, a2, a3, a4, 0])
331    }
332}
333
334/// Invokes a 6-argument system call.
335///
336/// # Safety
337///
338/// The caller must uphold the ABI and memory safety invariants required by syscall `nr`.
339#[inline]
340pub unsafe fn syscall6(
341    nr: usize,
342    a0: usize,
343    a1: usize,
344    a2: usize,
345    a3: usize,
346    a4: usize,
347    a5: usize,
348) -> SysResult<usize> {
349    #[cfg(all(target_arch = "aarch64", target_os = "none"))]
350    {
351        let ret: usize;
352        // SAFETY: The caller upholds the syscall contract for `nr`.
353        unsafe {
354            core::arch::asm!(
355                "svc #0",
356                in("x8") nr,
357                inlateout("x0") a0 => ret,
358                in("x1") a1,
359                in("x2") a2,
360                in("x3") a3,
361                in("x4") a4,
362                in("x5") a5,
363                options(nostack, preserves_flags),
364            );
365        }
366        decode_raw(ret)
367    }
368    #[cfg(not(all(target_arch = "aarch64", target_os = "none")))]
369    {
370        mock::dispatch(nr, [a0, a1, a2, a3, a4, a5])
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use crate::errno::{EINVAL, ENOSYS};
378
379    #[test]
380    fn decode_raw_boundaries() {
381        assert_eq!(decode_raw(0), Ok(0));
382        assert_eq!(decode_raw(42), Ok(42));
383        assert_eq!(decode_raw((-22isize) as usize), Err(Errno(EINVAL)));
384        assert_eq!(decode_raw((-4095isize) as usize), Err(Errno(4095)));
385        assert_eq!(decode_raw((-4096isize) as usize), Ok((-4096isize) as usize));
386    }
387
388    #[test]
389    fn default_mock_returns_enosys() {
390        let res = unsafe { syscall0(nr::GETPID) };
391        assert_eq!(res, Err(Errno(ENOSYS)));
392    }
393}